package com.prolog.cs.biz.inbound.remote;

import com.prolog.cs.basic.item.model.vo.ItemMstQueryVO;
import com.prolog.cs.basic.item.model.vo.ItemMstVO2;
import com.prolog.cs.biz.inbound.dto.rcv.*;
import com.prolog.cs.biz.inbound.model.OmsAsnBillD;
import com.prolog.cs.biz.inbound.model.OmsAsnBillH;
import com.prolog.cs.biz.inbound.remote.dto.OmsAsnBillDDTO;
import com.prolog.cs.biz.inbound.remote.dto.OmsAsnBillDQueryVO;
import com.prolog.cs.biz.inbound.remote.dto.OmsAsnBillHDTO;
import com.prolog.cs.biz.inbound.remote.dto.OmsAsnBillHQueryVO;
import com.prolog.cs.biz.inbound.service.OmsAsnBillDService;
import com.prolog.cs.biz.inbound.utils.ObjectUtils;
import com.prolog.framework.common.message.RestMessage;
import com.prolog.framework.core.pojo.Page;
import com.prolog.framework.utils.DateUtils;
import com.prolog.framework.utils.SnowFlakeUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class OmsASNRemoteCallerMock {

	@Resource
	private OmsAsnBillDService omsAsnBillDService;

	@Resource
	private BaseItemRemoteCaller baseItemRemoteCaller;

	private Map<String, List<OmsAsnBillDDTO>> map;

	// 模拟取san订单
	public Page<OmsAsnBillHDTO> getAsnList() {
		List<OmsAsnBillHDTO> lsit = new ArrayList<>();
		for (int i = 1; i < 16; i++) {
			OmsAsnBillHDTO dto = new OmsAsnBillHDTO();
			excutueBuildModel(i, dto);
			lsit.add(dto);
		}
		Page<OmsAsnBillHDTO> page = new Page<>();
		page.setList(lsit);
		page.setPageNum(1);
		page.setPageSize(15);
		page.setTotalCount(15);
		page.setPageCount(1);
		return page;
	}

	private void excutueBuildModel(int i, OmsAsnBillHDTO dto) {
		String num = String.valueOf(i);
		dto.setBillid(num);
		dto.setBillno(num);
		dto.setBilltype("0");
		dto.setBranchAddress("001");
		dto.setArrivalMode(num);
		dto.setBilldate(new Date());
		dto.setConsignorid("001");
		dto.setTotAmt(BigDecimal.valueOf(i));
		dto.setAttainDate(new Date());
		dto.setArrivalMode(num);
		dto.setBranchareaid(num);
		dto.setBilldate(new Date());
		dto.setBrancharea(num);
		dto.setBranchareaid(num);
		dto.setBranchcode(num);
		dto.setBranchid(num);
		dto.setBranchname(num);
		dto.setBuyerName(num);
		dto.setBuyerTel(num);
		dto.setCarrierId(num);
		dto.setCarrierName(num);
		dto.setCategoryId(num);
		dto.setConsignorid(num);
		dto.setConsignorname(num);
		dto.setDelivererContactTel(num);
		dto.setExamineState(num);
		dto.setPenterpriseid(num);
		dto.setPriorityLevel(num);
		dto.setPriorityLevelName(num);
		dto.setRefBillid(num);
		dto.setRefBillno(num);
		dto.setRefBilltype("1");
		dto.setRemark("无");
		dto.setShipLineId(num);
		dto.setShipmentAddress(num);
		dto.setShipmentCityName(num);
		dto.setShipmentCityNo(num);
		dto.setShipmentCommunityNo(num);
		dto.setShipperId(num);
		dto.setShipperName(num);
		dto.setShipperType("1");
		dto.setShipTerm(num);
		dto.setStatus("1");
		dto.setTotAmt(BigDecimal.ZERO);
		dto.setTotNetamt(BigDecimal.ZERO);
		dto.setTotPcs(BigDecimal.ZERO);
		dto.setTotQty(BigDecimal.ZERO);
		dto.setTotVolume(BigDecimal.ZERO);
		dto.setTotWeight(BigDecimal.ZERO);
	}

	public Page<OmsAsnBillDDTO> getAsnDetailsList(String hid) {
		List<OmsAsnBillDDTO> lsit = new ArrayList<>();
		for (int i = 1; i < 16; i++) {
			OmsAsnBillDDTO dto = new OmsAsnBillDDTO();
			excutueBuildModel(i, dto);
			lsit.add(dto);
		}
		map = new HashMap<>();
		for (int i = 1; i < 16; i++) {
			map.put(String.valueOf(i), lsit);
		}
		Page<OmsAsnBillDDTO> page = new Page<>();
		page.setList(map.get(hid));
		page.setPageNum(1);
		page.setPageSize(15);
		page.setTotalCount(15);
		page.setPageCount(1);
		return page;
	}

	private void excutueBuildModel(int i, OmsAsnBillDDTO dto) {
		String num = String.valueOf(i);
		dto.setLineid(num);
		dto.setLotNo(num);
		dto.setAmt(BigDecimal.ZERO);
		dto.setApprovalNumber(num);
		dto.setBatchNo(num);
		dto.setBillid(num);
		dto.setBrancharea(num);
		dto.setBranchareaid(num);
		dto.setBranchcode(num);
		dto.setBranchid(num);
		dto.setBranchname(num);
		dto.setCategoryId(num);
		dto.setColorCode(num);
		dto.setConsignorname(num);
		dto.setSizeCode(num);
		dto.setEdition(num);
		dto.setFreeQty(BigDecimal.ZERO);
		dto.setItemid(num);
		dto.setItemcode(num);
		dto.setItemname(num);
		dto.setItemOdd(BigDecimal.ZERO);
		dto.setItemPcs(BigDecimal.ZERO);
		dto.setItemQty(BigDecimal.ZERO);
		dto.setItemVolume(BigDecimal.ZERO);
		dto.setParerntItemid("1");
		dto.setItemWeight(BigDecimal.ZERO);
		dto.setLineid(num);
		dto.setLineRemark(num + "备注");
		dto.setLotNo(num);
		dto.setMachType(num);
		dto.setManufacturer(num);
		dto.setPackSize(BigDecimal.ZERO);
		dto.setPackUnits(num);
		dto.setPaperno(num);
		dto.setParerntItemid(num);
		dto.setPdateFrom(new Date());
		dto.setPenterprisename(num);
		dto.setPrice(BigDecimal.ZERO);
		dto.setProductionPlace(num);
		dto.setRejectQty(BigDecimal.ZERO);
		dto.setRevision(num);
		dto.setRtreason(num);
		dto.setRtVendorid(num);
		dto.setSeqno(num);
		dto.setSizeCode(num);
		dto.setStatus("0");
		dto.setTniPrice(BigDecimal.ZERO);
		dto.setTniAmt(BigDecimal.ZERO);
	}

	public RestMessage<Object> queryOmsAsnBillHAudit(OmsAsnBillHQueryVO vo) {
//		Page<OmsAsnBillHDTO> asnList = this.getAsnList();
//		List<OmsAsnBillHDTO> list = asnList.getList();

		// 调用本地方法
		Page<OmsAsnBillH> asnList = omsAsnBillDService.queryOmsAsnBillHAudit(vo);
		List<OmsAsnBillH> list = asnList.getList();

		List<RcvHAndPDTO> collect = new ArrayList<RcvHAndPDTO>();
		for (OmsAsnBillH p : list) {
			RcvHAndPDTO hAndP = new RcvHAndPDTO();
			RcvHeadersDTO h = new RcvHeadersDTO();
			RcvHeadersProfilesDTO hp = new RcvHeadersProfilesDTO();
			String arrivalMode = p.getArrivalMode();
			Date attainDate = p.getAttainDate();
			Date billdate = p.getBillDate();
			String billid = p.getBillid();
			String billno = p.getBillno();
			String billtype = p.getBilltype();
			String branchid = p.getBranchid();
			String branchAddress = p.getBranchAddress();
			String brancharea = p.getBrancharea();
			String branchcode = p.getBranchcode();
			String branchareaid = p.getBranchareaid();
			String branchname = p.getBranchname();
			String buyerName = p.getBuyerName();
			String buyerTel = p.getBuyerTel();
			String refBillid = p.getRefBillid();
			String refBillno = p.getRefBillno();
			String refBilltype = p.getRefBilltype();
			String carrierId = p.getCarrierId();
			String carrierName = p.getCarrierName();
			String categoryId = p.getCategoryId();
			String consignorid = p.getConsignorid();
			String consignorname = p.getConsignorname();
			String delivererContactTel = p.getDelivererContactTel();
			String examineState = p.getExamineState();
			String penterpriseid = p.getPEnterpriseid();
			String priorityLevel = p.getPriorityLevel();
			String remark = p.getRemark();
			String rtReason = p.getRtReason();
			String shipLineId = p.getShipLineId();
			String shipmentAddress = p.getShipmentAddress();
			String shipmentCityName = p.getShipmentCityName();
			String shipmentCityNo = p.getShipmentCityNo();
			String shipmentCommunityName = p.getShipmentCommunityName();
			String shipmentCommunityNo = p.getShipmentCommunityNo();
			String shipmentCountryName = p.getShipmentCountryName();
			String shipmentCountryNo = p.getShipmentCountryNo();
			String shipmentDistrictName = p.getShipmentDistrictName();
			String shipmentDistrictNo = p.getShipmentDistrictNo();
			String shipmentProvinceName = p.getShipmentProvinceName();
			String shipmentProvinceNo = p.getShipmentProvinceNo();
			String shipmentTownName = p.getShipmentTownName();
			String shipmentTownNo = p.getShipmentTownNo();
			String shipperId = p.getShipperid();
			String shipperName = p.getShippername();
			String shipperType = p.getShipperType();
			String shipTerm = p.getShipTerm();
			String status = p.getStatus();
			BigDecimal totAmt = p.getTotamt();
			BigDecimal totNetamt = p.getTotnetamt();
			BigDecimal totPcs = p.getTotPcs();
			BigDecimal totQty = p.getTotQty();
			BigDecimal totVolume = p.getTotVolume();
			BigDecimal totWeight = p.getTotWeight();

			h.setAccessLevel("9");
			h.setWarehouseId(branchid);
			h.setAutoBillNum(String.valueOf(SnowFlakeUtils.getId()));
			h.setBuyerId(buyerTel); // 先用采购电话代替
			h.setCaseQty(totPcs);
			h.setComments(remark);
			h.setMtlOwnerId(consignorid);
//			h.setOrgnId(shipperId);
			h.setPieceQty(totQty);

			h.setRcvType(billtype);
			h.setAsnAutoBillNum(billno);
			h.setAsnHeaderId(billid);

			h.setVendorId(shipperId);
			h.setSrcHeaderId(refBillid);
			h.setSrcAutoBillNum(refBillno);
			h.setSrcBillType(refBilltype);

//			h.setWarehouseId(branchareaid);

			hp.setWarehouseName(branchname);
			hp.setWarehouseNum(branchcode);
//			hp.setArrivalMode(arrivalModeName);
			hp.setBuyerMane(buyerName);
			hp.setBuyerNum(buyerTel); // 采购员编号用电话代替
			hp.setCarriername(carrierName);
			hp.setMtlOwnerName(consignorname);
			hp.setMtlOwnerNum(consignorid); // 使用货主id代替
			hp.setOrderHeaderId(refBillid);
			hp.setOrderAutoNum(refBillno);
			hp.setShipType(shipTerm); // 运输方式 用运输条件代替
			hp.setTaTe(totNetamt);
			hp.setTaTi(totAmt);
			// 税率自己计算
			hp.setVendorName(shipperName);
			hp.setVendorNum(shipperId); // 使用供应商id代替
			hp.setWarehouseName(branchname);
			hp.setWarehouseNum(branchcode);

			hAndP.setRcvHeadersDTO(h);
			hAndP.setRcvHeadersProfilesDTO(hp);

			collect.add(hAndP);
		}

//		// 构建前端识别的字段
//		List<RcvHAndPDTO> collect = Optional.ofNullable(list).orElse(Collections.emptyList()).stream().distinct()
//				.map(p -> {
//					RcvHAndPDTO hAndP = new RcvHAndPDTO();
//					RcvHeadersDTO h = new RcvHeadersDTO();
//					RcvHeadersProfilesDTO hp = new RcvHeadersProfilesDTO();
//					String arrivalMode = p.getArrivalMode();

//					return hAndP;
//				}).collect(Collectors.toList());
		Page<RcvHAndPDTO> mapPage = new Page<>();
		mapPage.setEndRow(asnList.getEndRow());
		mapPage.setStartRow(asnList.getStartRow());
		mapPage.setPageCount(asnList.getPageCount());
		mapPage.setPageNum(asnList.getPageNum());
		mapPage.setPageSize(asnList.getPageSize());
		mapPage.setTotalCount(asnList.getTotalCount());
		mapPage.setList(collect);
		return RestMessage.doSuccess(mapPage);
	}

	public RestMessage<Object> queryOmsAsnBillD(OmsAsnBillDQueryVO vo) {
		String billid = vo.getBillid();
//		Page<OmsAsnBillDDTO> asnDetailsList = this.getAsnDetailsList(billid);
//		List<OmsAsnBillDDTO> list = asnDetailsList.getList();

		// 调用本地方法
		Page<OmsAsnBillD> asnDetailsList = omsAsnBillDService.queryOmsAsnBillD(vo);
		List<OmsAsnBillD> list = asnDetailsList.getList();

		// 是否需要关联item相关数据
		Set<String> itemIds = Optional.ofNullable(list).orElse(Collections.emptyList()).stream().distinct()
				.map(OmsAsnBillD::getItemid).collect(Collectors.toSet());
//		String mtlOwnerId = list.get(0).getCategoryId();
		ItemMstQueryVO itemVO = new ItemMstQueryVO();
		itemVO.setItemIds(itemIds);
//		itemVO.setCargoOwnerId(mtlOwnerId);
		RestMessage<Page<ItemMstVO2>> page = baseItemRemoteCaller.pagebyRelated(itemVO);
		boolean success = page.isSuccess();
		List<ItemMstVO2> ItemMstVO2List = null;
		if (success)
			ItemMstVO2List = page.getData().getList();
//		AssertUtils.notNull(ItemMstVO2List, "远程商品数据查询失败!");
		Map<String, List<ItemMstVO2>> collect3 = Optional.ofNullable(ItemMstVO2List).orElse(Collections.emptyList()).stream().distinct()
				.collect(Collectors.groupingBy(ItemMstVO2::getItemId));
//		if (ObjectUtils.isNotNull(ItemMstVO2List))
//			collect3 = Optional.ofNullable(ItemMstVO2List).orElse(Collections.emptyList()).stream().distinct()
//					.collect(Collectors.groupingBy(ItemMstVO2::getItemId));

		// 构建前端识别字段
		List<RcvLinesDTO> collect = Optional.ofNullable(list).orElse(Collections.emptyList()).stream().distinct()
				.map(p -> {
					RcvLinesDTO line = new RcvLinesDTO();
					RcvLinesProfilesDTO linePro = new RcvLinesProfilesDTO();
					line.setRcvLinesProfilesDTO(linePro);
					String itemid = p.getItemid();

					BigDecimal amt = p.getAmt();
					String approvalNumber = p.getApprovalNumber();
					String batchNo = p.getBatchNo();
					String billid2 = p.getBillid();
					String billno = p.getBillno();
					String brancharea = p.getBrancharea();
					String branchareaid = p.getBranchareaid();
					String branchcode = p.getBranchcode();
					String branchid = p.getBranchid();
					String branchname = p.getBranchname();
					String categoryId = p.getCategoryId();
					String consignorname = p.getConsignorname();
					String closedReason = p.getClosedReason();
					String consignorid = p.getConsignorid();
					String edition = p.getEdition();
					BigDecimal freeQty = p.getFreeQty();
					String itemcode = p.getItemcode();

					String itemname = p.getItemname();
					BigDecimal itemOdd = p.getItemOdd();
					BigDecimal itemPcs = p.getItemPcs();
					BigDecimal itemQty = p.getItemQty();
					BigDecimal itemVolume = p.getItemVolume();
					BigDecimal itemWeight = p.getItemWeight();
					String lineid = p.getLineid();
					String lineRemark = p.getLineRemark();
					String lotNo = p.getLotNo();
					String machType = p.getMachType();
					String manufacturer = p.getManufacturer();
					BigDecimal packSize = p.getPackSize();
					String packUnits = p.getPackUnits();
					String paperno = p.getPaperno();
					String parerntItemid = p.getParerntItemid();
					String pdateFrom = p.getPdateFrom();
					String penterpriseid = p.getPEnterpriseid();
					BigDecimal price = p.getPrice();
					String productionPlace = p.getProductionPlace();
					BigDecimal rejectQty = p.getRejectQty();
					String revision = p.getRevision();
					String rtreason = p.getRtreason();
					String rtVendorid = p.getRtVendorid();
					String seqno = p.getSeqno();
					String sizeCode = p.getSizeCode();
					String status = p.getStatus();
					BigDecimal tniAmt = p.getTniAmt();
					BigDecimal tniPrice = p.getTniPrice();
					String validUntil = p.getValidUntil();

					line.setBatchProductionDate(DateUtils.parse(pdateFrom));
					line.setBatchExpiredDate(DateUtils.parse(validUntil));
					line.setBatchId(String.valueOf(SnowFlakeUtils.getId())); // 无id 用编号代替
					line.setBatchNum(batchNo);
					line.setConversionRate(packSize);
					line.setErpBatchNum(batchNo);
					line.setItemId(itemid);
					line.setManufacturerLotNum(lotNo);
					line.setOddCaseQty(itemPcs);
					line.setOddPieceQty(itemOdd);
					line.setPieceQty(itemQty.multiply(packSize).add(itemOdd));
					line.setQty(itemQty);
					line.setAsnHeaderId(billid); // 以后可能多个合成一个
					line.setAsnLineId(lineid);
					line.setUom(packUnits);
//					line.setVendorBatchNum(); 使用头表数据
					line.setWarehouseAreaId(branchareaid); // 先用id代替
					line.setWmsPieceQty(BigDecimal.ZERO);

					// 加入item属性
					Random random = new Random();
					int nextInt = random.nextInt(100);
					// 调用远程item服务查询
					linePro.setItemAssistantCode("00" + nextInt);
					linePro.setItemHealthApprovalNbr("00" + nextInt);
					linePro.setIsCaseOrPiece("0");
					linePro.setQcMode("01");
					linePro.setCaseConversionRate(BigDecimal.valueOf(nextInt));

//					linePro.setCarriername(); // 使用头表
					linePro.setCategoryId(categoryId);
					linePro.setCmpacklotno(lotNo);
					linePro.setItemId(itemid);
					linePro.setItemName(itemname);
					linePro.setItemNum(itemcode);
//					linePro.setLinetype(lineid); 取头表
//					linePro.setLineNum(tniPrice); 取头表
					linePro.setPaperno(paperno);
					linePro.setParentitemid(parerntItemid);
					linePro.setPiecePriceTe(tniPrice);
					linePro.setPiecePriceTi(price);
					linePro.setUnitPriceTe(tniPrice);
					linePro.setUnitPriceTi(price);
					linePro.setTaTax(BigDecimal.ZERO); // 需要结合数量计算
					linePro.setTaTe(tniPrice);
					linePro.setTaTi(price);
//					linePro.setRefPurchasePriceTi(tniPrice);
					linePro.setSizecode(sizeCode);
//					BigDecimal divide = (tniPrice.subtract(price)).divide(tniPrice,2, RoundingMode.HALF_UP);
					linePro.setTaxRate(BigDecimal.ZERO);
//					linePro.setVendoritemcode(itemcode); // 需要远程调用

					excuteBuildItemFields(itemid, line, linePro,collect3);

					return line;
				}).collect(Collectors.toList());

		Page<RcvLinesDTO> mapPage = new Page<>();
		mapPage.setEndRow(asnDetailsList.getEndRow());
		mapPage.setStartRow(asnDetailsList.getStartRow());
		mapPage.setPageCount(asnDetailsList.getPageCount());
		mapPage.setPageNum(asnDetailsList.getPageNum());
		mapPage.setPageSize(asnDetailsList.getPageSize());
		mapPage.setTotalCount(asnDetailsList.getTotalCount());
		mapPage.setList(collect);

		return RestMessage.doSuccess(mapPage);
	}

	private void excuteBuildItemFields(String itemid, RcvLinesDTO line, RcvLinesProfilesDTO linePro,
			Map<String, List<ItemMstVO2>> collect3) {
		if (ObjectUtils.isNull(collect3)) 
			return;
		
		// 构建商品字段
		List<ItemMstVO2> itemModel = collect3.get(itemid);
		if (ObjectUtils.isNotNull(itemModel)) {
			ItemMstVO2 itemvo = itemModel.get(0);
			// 商品条码
			String barCode = itemvo.getBarCode();
			// 商品品牌名称
			String brandName = itemvo.getBrandName();
			// 货主编码
			String cargoOwnerCode = itemvo.getCargoOwnerCode();
			// 货主id
			String cargoOwnerId = itemvo.getCargoOwnerId();
			// 货主名称
			String cargoOwnerName = itemvo.getCargoOwnerName();
			// 最大箱规格
			BigDecimal caseConversionRate = itemvo.getCaseConversionRate();
			// 产地
			String countryOriginName = itemvo.getCountryOriginName();
			// 企业id
			String enterpriseId = itemvo.getEnterpriseId();
			// 整散分离标记 01整散合一/02整散分开
			Integer isCaseOrPiece2 = itemvo.getIsCaseOrPiece();
			String isCaseOrPiece = isCaseOrPiece2.toString();
			// 是否可用
			Integer isEnable = itemvo.getIsEnable();
			// 商品助记码
			String itemAssistantCode = itemvo.getItemAssistantCode();
			// 商品分类编码
			String itemCategoryCode = itemvo.getItemCategoryCode();
			// 商品分类名称
			String itemCategoryName = itemvo.getItemCategoryName();
			// 商品编码
			String itemCode = itemvo.getItemCode();
			// 批准文号
			String itemHealthApprovalNbr = itemvo.getItemHealthApprovalNbr();
			// 药品大类 内用/外用/精神/麻醉
			String itemHealthCategory = itemvo.getItemHealthCategory();
			// 商品通用名
			String itemHealthCommonName = itemvo.getItemHealthCommonName();
			// 医药行业类型 疫苗 、生物制品、中成药
			String itemHealthIndustry = itemvo.getItemHealthIndustry();
			// 双人业务类型(0:正常 1：双人验收，默认正常)
			Integer itemHealthIsDouble = itemvo.getItemHealthIsDouble();
			// 备案号
			String itemHealthRecordNbr = itemvo.getItemHealthRecordNbr();
			// 是否监管
			Integer itemHealthSuperviseflag = itemvo.getItemHealthSuperviseflag();
			// 注册证号
			String itemHealthRegisterNbr = itemvo.getItemHealthRegisterNbr();
			// 是否两票制
			Integer itemHealthTwovoteflag = itemvo.getItemHealthTwovoteflag();
			// 是否效期管理
			Integer itemIsExpire = itemvo.getItemIsExpire();
			// 商品名称
			String itemName = itemvo.getItemName();
			// 商品英文名
			String itemNameEn = itemvo.getItemNameEn();
			// 中文简称
			String itemShortName = itemvo.getItemShortName();
			// 效期
			String managementExpiredDate = itemvo.getManagementExpiredDate();
			// 批次号
			String managementLotNbr = itemvo.getManagementLotNbr();
			// 生产商编码
			String manufacturerCode = itemvo.getManufacturerCode();
			// 生产商名称
			String manufacturerName = itemvo.getManufacturerName();
			// 商品条码
			String pieceBarcode = itemvo.getPieceBarcode();
			// 最小箱规
			BigDecimal pieceConversionRate = itemvo.getPieceConversionRate();
			// 质量检查方式(不质检/质检方式1/质检方式2)
			String qcMode = itemvo.getQcMode();
			// 效期天数
			BigDecimal shelfLifeDays = itemvo.getShelfLifeDays();
			// 商品状态
			String status = itemvo.getStatus();
			// 存储条件
			String storeTemperature = itemvo.getStoreTemperature();
			// 供应商编码
			String supplierCode = itemvo.getSupplierCode();
			// 供应商名称
			String supplierName = itemvo.getSupplierName();
			
			String approvalNumber = line.getApprovalNumber();
			if (ObjectUtils.isNull(approvalNumber)) 
				line.setApprovalNumber(itemHealthApprovalNbr); // 批准文号
			// TODO 补充其他数据
			
		}
	}

	// 模拟更改san单状态

	// 需要远程调用商品服务补数据详情

}
