package com.sw.mes.wms.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.sw.mes.core.dto.*;
import com.sw.mes.core.dto.store.*;
import com.sw.mes.yb.seed.api.service.supplier.SeedSupplierService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sw.mes.base.factory.init.dto.MachineCapacityInfoDataDto;
import com.sw.mes.base.factory.material.entity.MaterialModel;
import com.sw.mes.base.factory.material.service.MaterialModelService;
import com.sw.mes.core.api.system.FbFeignClients;
import com.sw.mes.core.api.system.StoreFeignClients;
import com.sw.mes.core.enums.InputBillTypeEnum;
import com.sw.mes.core.response.Result;
import com.sw.mes.sap.dto.jip.JipWMSResult;
import com.sw.mes.utils.StringUtils;
import com.sw.mes.wms.service.WMSInputService;
import org.springframework.util.ObjectUtils;

@Slf4j
@Service
public class WMSInputServiceImpl implements WMSInputService {
	
	
	@Autowired
    private StoreFeignClients storeFeignClients;
	
	@Autowired
    private FbFeignClients fbFeignClients;
	
	@Autowired
	private MaterialModelService materialModelService;

	@Autowired
	private SeedSupplierService seedSupplierService;

    @Override
    public void handlerRawmaterialEdgewarehouse(JSONObject data) {
        JSONObject dataItem = data.getJSONObject("IT_DATA");
        //发料信息
        JSONObject goodsInfo = dataItem.getJSONObject("header");
        
//        String direction = goodsInfo.getString("direction");//定向标识
//        if(StringUtils.isBlank(direction))
//        	throw new RuntimeException("定向标识不能为空");
        
        String factoryId = goodsInfo.getString("factoryId");//定向标识
        if(StringUtils.isBlank(factoryId))
        	throw new RuntimeException("工厂不能为空");
        
        String pickNo = goodsInfo.getString("pickNo");//定向标识
        if(StringUtils.isBlank(pickNo))
        	throw new RuntimeException("发料单号不能为空");
        
        String orderType = goodsInfo.getString("orderType");//定向标识
        if(StringUtils.isBlank(orderType))
        	throw new RuntimeException("订单类型不能为空");
        
        String senderCode = goodsInfo.getString("senderCode");//定向标识
        if(StringUtils.isBlank(senderCode))
        	throw new RuntimeException("发料人工号不能为空");
        
        String senderName = goodsInfo.getString("senderName");//定向标识
        if(StringUtils.isBlank(senderName))
        	throw new RuntimeException("发料人名称不能为空");
        
//        String warehouse = goodsInfo.getString("warehouse");//定向标识
//        if(StringUtils.isBlank(warehouse))
//        	throw new RuntimeException("来源库存地点不能为空");
        
        String lgort = goodsInfo.getString("lgort");//定向标识
        if(StringUtils.isBlank(lgort))
        	throw new RuntimeException("线边库存地点不能为空");
        
        String uniqueNo = goodsInfo.getString("uniqueNo");
        String workOrderNo = goodsInfo.getString("workOrderNo");
        String dedi04 = goodsInfo.getString("dedi04");
        String define1 = goodsInfo.getString("define1");
        String define2 = goodsInfo.getString("define2");
        String define3 = goodsInfo.getString("define3");
        String define4 = goodsInfo.getString("define4");
        String define5 = goodsInfo.getString("define5");
        
        
        //物料信息
        JSONArray materialInfo = dataItem.getJSONArray("details");
        
		WarehouseInputBillBo inputBillBo = new WarehouseInputBillBo();
		inputBillBo.setBillNo(pickNo);// 入库单号
		inputBillBo.setWarehouseCode(lgort); //库位编码
		
		inputBillBo.setType(InputBillTypeEnum.原辅料入库.getValue());// 入库类型
		
		inputBillBo.setFactoryId(factoryId);
		inputBillBo.setUniqueNo(uniqueNo);
		inputBillBo.setSenderCode(senderCode);
		inputBillBo.setSenderName(senderName);
		inputBillBo.setLgort(lgort);
		inputBillBo.setWorkOrderNo(workOrderNo);
		inputBillBo.setDedi04(dedi04);
		inputBillBo.setDefine1(define1);
		inputBillBo.setDefine2(define2);
		inputBillBo.setDefine3(define3);
		inputBillBo.setDefine4(define4);
		inputBillBo.setDefine5(define5);
//		inputBillBo.setDirection(direction);

        for (int j = 0; j < materialInfo.size(); j++) {
			JSONObject material = materialInfo.getJSONObject(j);
			String sku = material.getString("sku");//物料编码
			if(StringUtils.isBlank(sku))
	        	throw new RuntimeException("物料编码[sku]不能为空");
			
			String qty = material.getString("qty");//数量
			if(StringUtils.isBlank(qty))
	        	throw new RuntimeException("数量[qty]不能为空");
			
			String traceid = material.getString("traceid");//托号
			if(StringUtils.isBlank(traceid))
	        	throw new RuntimeException("托号[traceid]为空");
			
			String serialNo = material.getString("serialNo");//箱号
			if(StringUtils.isBlank(serialNo))
	        	throw new RuntimeException("箱号[serialNo]为空");
			
			String lotatt04 = material.getString("lotatt04");//物料批次号
			if(StringUtils.isBlank(serialNo))
	        	throw new RuntimeException("物料批次号[lotatt04]为空");
			
			String lotatt01 = material.getString("lotatt01");
			String lotatt02 = material.getString("lotatt02");
			String lotatt03 = material.getString("lotatt03");
			String lotatt05 = material.getString("lotatt05");
			String lotatt06 = material.getString("lotatt06");
			String lotatt07 = material.getString("lotatt07");
			String lotatt08 = material.getString("lotatt08");
			String lotatt09 = material.getString("lotatt09");//供应商
			String lotatt10 = material.getString("lotatt10");
			String lotatt11 = material.getString("lotatt11");
			String lotatt12 = material.getString("lotatt12");
			String lotatt13 = material.getString("lotatt13");
			String lotatt14 = material.getString("lotatt14");
			String lotatt15 = material.getString("lotatt15");
			String lotatt16 = material.getString("lotatt16");
			String lotatt17 = material.getString("lotatt17");
			String lotatt18 = material.getString("lotatt18");
			String lotatt19 = material.getString("lotatt19");
			String lotatt20 = material.getString("lotatt20");
			String lotatt21 = material.getString("lotatt21");
			String lotatt22 = material.getString("lotatt22");
			String lotatt23 = material.getString("lotatt23");
			String lotatt24 = material.getString("lotatt24");
			String dedi01 = material.getString("dedi01");
			String dedi02 = material.getString("dedi02");
			String dedi03 = material.getString("dedi03");
			String mdedi04 = material.getString("dedi04");
			String dedi05 = material.getString("dedi05");
			
			//TODO 处理WMS发料至MES线边仓业务逻辑
			//sku
			MaterialModel materialModel = materialModelService.findByCode(sku);
			
			if(materialModel==null) {
				throw new RuntimeException("未知物料编号,请先同步物料主数据");
			}
			
			MachineCapacityInfoDataDto infoData = null;
			try {
				infoData = materialModelService.getMachineCapacityInfoDataDto(materialModel.getId());
			}catch (Exception e) {}
			
			WarehouseInputBillDetailBo detail = new WarehouseInputBillDetailBo();
			detail.setMaterialModelId(Long.valueOf(materialModel.getId()));
			detail.setMaterialModelCode(sku);
			detail.setMaterialModelName(materialModel.getName());
			detail.setMaterialTypeName(materialModel.getWgbez());
			detail.setSpecification(materialModel.getSpecification());
//			detail.setSupplier("山西晶科（拉晶）智造工厂");
			detail.setMaterialTh("无");
			detail.setCount(new BigDecimal(qty));
			detail.setUnitName(materialModel.getMeins());
			detail.setSupplier(lotatt09);
			if(infoData!=null)
				detail.setSpecification(infoData.getSpecification());
			detail.setWarehouseCode(lgort);
			detail.setMaterialBoxNo(serialNo);
			detail.setTraceid(traceid);//托盘编号 载具编号
			detail.setMaterialTypeName(materialModel.getWgbez());
			detail.setCustomer(factoryId);
			detail.setBatchNo(lotatt04);
			
			inputBillBo.setSourceWarehouse(lotatt06);//来源库存地点
			detail.setSerialNo(serialNo);
			detail.setLotatt01(lotatt01);
			detail.setLotatt02(lotatt02);
			detail.setLotatt03(lotatt03);
			detail.setLotatt04(lotatt04);
			detail.setLotatt05(lotatt05);
			detail.setLotatt06(lotatt06);
			detail.setLotatt07(lotatt07);
			detail.setLotatt08(lotatt08);
			detail.setLotatt09(lotatt09);
			detail.setLotatt10(lotatt10);
			detail.setLotatt11(lotatt11);
			detail.setLotatt12(lotatt12);
			detail.setLotatt13(lotatt13);
			detail.setLotatt14(lotatt14);
			detail.setLotatt15(lotatt15);
			detail.setLotatt16(lotatt16);
			detail.setLotatt17(lotatt17);
			detail.setLotatt18(lotatt18);
			detail.setLotatt19(lotatt19);
			detail.setLotatt20(lotatt20);
			detail.setLotatt21(lotatt21);
			detail.setLotatt22(lotatt22);
			detail.setLotatt23(lotatt23);
			detail.setLotatt24(lotatt24);
			detail.setDedi01(dedi01);
			detail.setDedi02(dedi02);
			detail.setDedi03(dedi03);
			detail.setDedi04(mdedi04);
			detail.setDedi05(dedi05);
			detail.setUniqueKey(serialNo);
			//detail.setUniqueCode(serialNo);//设置唯一码为箱号 临时需求, 等待WMS传递并确认字段
			//线边仓库存地
			detail.setSourceWarehouse(lotatt06);
			
			inputBillBo.getInputBillDetails().add(detail);
		}
        
        Result<String> result = storeFeignClients.inputApply(inputBillBo);
        if(result.getCode()!=200) {
        	throw new RuntimeException(result.getMessage());
        }
    }

	@Override
	public void handlerReturnFeedback(JSONObject data, List<JipWMSResult> results) {
		WmsOutputBillDto inputBillBo = new WmsOutputBillDto();
		
		List<WmsOutputBillDetailsDto> detailsDtos = new ArrayList<WmsOutputBillDetailsDto>();
		
		JSONArray IT_DATA = data.getJSONArray("IT_DATA");
        for(int i=0;i<IT_DATA.size();i++){
            JSONObject dataItem = IT_DATA.getJSONObject(i);
			
			String ORGANIZATIONID = dataItem.getString("ORGANIZATIONID");//物料编码
			if(StringUtils.isBlank(ORGANIZATIONID))
				throw new RuntimeException("组织编号为空");
			
			String WAREHOUSEID = dataItem.getString("WAREHOUSEID");//物料编码
			if(StringUtils.isBlank(ORGANIZATIONID))
				throw new RuntimeException("仓库编号为空");
			
			String CUSTOMERID = dataItem.getString("CUSTOMERID");//物料编码
			if(StringUtils.isBlank(CUSTOMERID))
				throw new RuntimeException("货主ID为空");
			
			String DOCNO = dataItem.getString("DOCNO");//物料编码
			if(StringUtils.isBlank(DOCNO))
				throw new RuntimeException("单据编号为空");
			
			String ASNSTATUS = dataItem.getString("ASNSTATUS");//物料编码
			if(StringUtils.isBlank(ASNSTATUS))
				throw new RuntimeException("订单状态为空");
			
			String SKU = dataItem.getString("SKU");//物料编码
			if(StringUtils.isBlank(SKU))
				throw new RuntimeException("产品代码为空");
			
			String QTYORDERED = dataItem.getString("QTYORDERED");//物料编码
			if(StringUtils.isBlank(QTYORDERED))
				throw new RuntimeException("数量为空");
			
			String PACKUOM = dataItem.getString("PACKUOM");//物料编码
			if(StringUtils.isBlank(PACKUOM))
				throw new RuntimeException("单位为空");
			
			String CONTAINERID = dataItem.getString("CONTAINERID");//物料编码
			if(StringUtils.isBlank(CONTAINERID))
				throw new RuntimeException("箱编号为空");
			
			String TRACEID = dataItem.getString("TRACEID");//物料编码
			if(StringUtils.isBlank(TRACEID))
				throw new RuntimeException("托号为空");
			
			
			inputBillBo.setBillNo(DOCNO);
			inputBillBo.setStatus((!ASNSTATUS.equals("00"))?"拒收":"接收");
			
			WmsOutputBillDetailsDto dto = new WmsOutputBillDetailsDto();
			dto.setSku(SKU);
			dto.setTraceid(TRACEID);
			dto.setContainerid(CONTAINERID);
			dto.setNumber(new BigDecimal(QTYORDERED));
			dto.setUniqueKey(CONTAINERID);
			//dto.setUniqueCode(CONTAINERID);
			detailsDtos.add(dto);
			inputBillBo.setDetailsDtos(detailsDtos);
		}
        
        Result<String> result = storeFeignClients.statusReception(inputBillBo);
        if(result.getCode()!=200) {
        	throw new RuntimeException(result.getMessage());
        }
	}

	@Override
	public void handlerfbInboundFeedback(JSONObject data, List<JipWMSResult> results) {
		JSONArray IT_DATA = data.getJSONArray("IT_DATA");
        for(int i=0;i<IT_DATA.size();i++){
            JSONObject dataItem = IT_DATA.getJSONObject(i);
			String zinbd = dataItem.getString("ZINBD");
			
			String ZINBD = dataItem.getString("ZINBD");
			if(StringUtils.isBlank(ZINBD)) {
				JipWMSResult result = new JipWMSResult(JipWMSResult.ERROR,"MES入库单为空");
	        	results.add(result);
	        	continue;
			}
			
			String VBELN = dataItem.getString("VBELN");
			if(StringUtils.isBlank(VBELN)) {
				JipWMSResult result = new JipWMSResult(JipWMSResult.ERROR,"WMS入库单为空");
	        	results.add(result);
	        	continue;
			}
			
			String HUIDENT = dataItem.getString("HUIDENT");
			if(StringUtils.isBlank(HUIDENT)) {
				JipWMSResult result = new JipWMSResult(JipWMSResult.ERROR,"托盘号为空");
	        	results.add(result);
	        	continue;
			}
			
			String ZSHJG = dataItem.getString("ZSHJG");
			if(StringUtils.isBlank(ZSHJG)) {
				JipWMSResult result = new JipWMSResult(JipWMSResult.ERROR,"审核结果为空");
	        	results.add(result);
	        	continue;
			}
			
			String LGORT = dataItem.getString("LGORT");
//			if(StringUtils.isBlank(LGORT)) {
//				JipWMSResult result = new JipWMSResult(JipWMSResult.ERROR,"入库库存地点为空");
//	        	results.add(result);
//	        	continue;
//			}
			
			String CREATEDATE = dataItem.getString("CREATE_DATE");
			String CREATETIME = dataItem.getString("CREATE_TIME");
			
			
			
			String WAREHOUSEID = dataItem.getString("WAREHOUSEID");
			if(StringUtils.isBlank(WAREHOUSEID)) {
				JipWMSResult result = new JipWMSResult(JipWMSResult.ERROR,"仓库编号为空");
	        	results.add(result);
	        	continue;
			}
			
			String ORGANIZATIONID = dataItem.getString("ORGANIZATIONID");
			if(StringUtils.isBlank(ORGANIZATIONID)) {
				JipWMSResult result = new JipWMSResult(JipWMSResult.ERROR,"组织编号为空");
	        	results.add(result);
	        	continue;
			}
			
			
			//反馈方棒组托入库状态给线边仓 
			try {
				ArrayList<WmsToFbReceiveDto> wmsToFbReceiveDtos = new ArrayList<>();
				WmsToFbReceiveDto wmsToFbReceiveDto = new WmsToFbReceiveDto();
				wmsToFbReceiveDto.setBoxCode(HUIDENT);
				if ("A".equals(ZSHJG)){
					wmsToFbReceiveDto.setType(1);
				}else {
					wmsToFbReceiveDto.setType(2);
				}
				wmsToFbReceiveDto.setRejectionDate(new Date());
				wmsToFbReceiveDto.setRejectionUser("综计wms");
				wmsToFbReceiveDtos.add(wmsToFbReceiveDto);
				fbFeignClients.fbWmsReceive(wmsToFbReceiveDtos);

//				FbTurnstoreTrayDto fbTurnstoreTrayDto = new FbTurnstoreTrayDto();
//				fbTurnstoreTrayDto.setZinbd(ZINBD);
//				fbTurnstoreTrayDto.setVbeln(VBELN);
//				fbTurnstoreTrayDto.setHuident(HUIDENT);
//				fbTurnstoreTrayDto.setZshjg(ZSHJG);
//				fbTurnstoreTrayDto.setLgort(LGORT);
//				fbTurnstoreTrayDto.setCreateDate(CREATEDATE);
//				fbTurnstoreTrayDto.setCreateTime(CREATETIME);
//				fbTurnstoreTrayDto.setWarehouseid(WAREHOUSEID);
//				fbTurnstoreTrayDto.setOrganizationid(ORGANIZATIONID);
//				fbFeignClients.updateStateByTrayNo(fbTurnstoreTrayDto);
				//通过返回的MES入库单查询组托数据 如果查到则是籽晶组托业务
				Result<WarehouseOutputBillBo> result = storeFeignClients.findWarehouseOutputBillByCode(ZINBD);
				if(result.getCode().equals(200) && !ObjectUtils.isEmpty(result.getData())){
					WMSToSeedDto wmsToSeedDtos = new WMSToSeedDto();
					wmsToSeedDtos.setZinbd(ZINBD);
					wmsToSeedDtos.setVbeln(VBELN);
					wmsToSeedDtos.setHuident(HUIDENT);
					wmsToSeedDtos.setZshjg(ZSHJG);
					wmsToSeedDtos.setCreateDate(CREATEDATE);
					wmsToSeedDtos.setCreateTime(CREATETIME);
					wmsToSeedDtos.setWarehouseid(WAREHOUSEID);
					wmsToSeedDtos.setOrganizationid(ORGANIZATIONID);
					seedSupplierService.wmsReceive(wmsToSeedDtos);
				}
				//通过返回的MES入库单查询对应的入库单,如果查询到入库单则入库
			}catch (Exception e) {
				JipWMSResult result = new JipWMSResult(JipWMSResult.ERROR,e.getMessage());
				results.add(result);
				continue;
			}

        	JipWMSResult result = new JipWMSResult(JipWMSResult.SUCCESS,zinbd);
        	results.add(result);
        }
	}

	@Override
	public void handlerfbTransferOutbound(JSONObject data) {
		JSONObject dataItem = data.getJSONObject("IT_DATA");
        //发料信息
        JSONObject goodsInfo = dataItem.getJSONObject("header");
        //物料信息
        JSONArray materialInfo = dataItem.getJSONArray("details");

        String factoryId = goodsInfo.getString("factoryId");//定向标识
        if(StringUtils.isBlank(factoryId))
        	throw new RuntimeException("工厂不能为空");

        String pickNo = goodsInfo.getString("pickNo");//定向标识
        if(StringUtils.isBlank(pickNo))
        	throw new RuntimeException("发料单号不能为空");

        String orderType = goodsInfo.getString("orderType");//定向标识
        if(StringUtils.isBlank(orderType))
        	throw new RuntimeException("订单类型不能为空");


//        String warehouse = goodsInfo.getString("warehouse");//定向标识
//        if(StringUtils.isBlank(warehouse))
//        	throw new RuntimeException("来源库存地点不能为空");

        String lgort = goodsInfo.getString("lgort");//定向标识
        if(StringUtils.isBlank(lgort))
        	throw new RuntimeException("线边库存地点不能为空");

        String receiverCode = goodsInfo.getString("receiverCode");//出库人工号(非必填项)
        String receiverName = goodsInfo.getString("receiverName");//出库人名称(非必填项)
        String worktype = goodsInfo.getString("type");//类型


        String trayNo = "";
		String lotatt06="";


        List<RecheckInspectReceiveDetailDto> detailList = new ArrayList<RecheckInspectReceiveDetailDto>();
        for (int j = 0; j < materialInfo.size(); j++) {
			JSONObject material = materialInfo.getJSONObject(j);

			lotatt06 = material.getString("lotatt06");//定向标识
			if(StringUtils.isBlank(lotatt06))
				throw new RuntimeException("来源库存地点不能为空");

			String sku = material.getString("sku");//物料编码
			if(StringUtils.isBlank(sku))
	        	throw new RuntimeException("物料编码不能为空");

			String type = material.getString("type");//物料编码
			if(StringUtils.isBlank(type))
	        	throw new RuntimeException("类型不能为空");

			String qty = material.getString("qty");//物料编码
			if(StringUtils.isBlank(qty))
	        	throw new RuntimeException("数量不能为空");

			String traceid = material.getString("traceid");//物料编码
			if(StringUtils.isBlank(traceid))
	        	throw new RuntimeException("托号为空");

			String serialNo = material.getString("serialNo");//物料编码
			if(StringUtils.isBlank(serialNo))
	        	throw new RuntimeException("箱号为空");

			String dedi03 = material.getString("dedi03");//sap预留单号
			if(StringUtils.isBlank(dedi03))
				throw new RuntimeException("sap预留单号为空");

			String lotatt04 = material.getString("lotatt04");//批次号
			if(StringUtils.isBlank(lotatt04))
				throw new RuntimeException("批次号为空");

			trayNo = traceid;


			RecheckInspectReceiveDetailDto dto = new RecheckInspectReceiveDetailDto();
			dto.setTrayNo(traceid);
			dto.setWmsTrayNo(traceid);
			dto.setCrystalNo(serialNo);
			dto.setMaterialNumber(sku);
			dto.setWeight(new BigDecimal(qty));//称重(KG)
			dto.setWorkOrderDirectionalIdentification(type);
			dto.setWarehouseCode(lgort);
			dto.setSapWorkOrder(dedi03);
			dto.setBatchNo(lotatt04);
			//dto.setUniqueCode(serialNo);
			dto.setUniqueKey(serialNo);
			detailList.add(dto);
		}


        RecheckInspectReceiveDto headerDto = new RecheckInspectReceiveDto();
        headerDto.setTrayNo(trayNo);
        headerDto.setOutOrderNo(pickNo);
        headerDto.setCrystalNum(materialInfo.size());
        headerDto.setSource(lotatt06);
        headerDto.setUser(receiverName);
        headerDto.setApplyTime(new Date());
        headerDto.setQuitType(worktype);
        headerDto.setIsRecheck(1);


        RecheckInspectReceivePostDto dto = new RecheckInspectReceivePostDto();
        dto.setReceive(headerDto);
        dto.setDetailList(detailList);
		Result result = fbFeignClients.wmsReturnInspection(dto);
		if (result.getCode()!=200){
			throw new RuntimeException("wms退库复检接收失败:"+result.getMessage());
		}
	}
}
