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

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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.init.entity.MachineCapacityInfo;
import com.sw.mes.base.factory.init.service.FactoryModelService;
import com.sw.mes.base.factory.init.service.MachineCapacityInfoService;
import com.sw.mes.base.factory.material.entity.MaterialModel;
import com.sw.mes.base.factory.material.service.MaterialModelService;
import com.sw.mes.base.factory.product.entity.ProductModel;
import com.sw.mes.base.factory.product.service.ProductModelService;
import com.sw.mes.base.system.entity.DictionaryItem;
import com.sw.mes.base.system.service.DictionaryItemService;
import com.sw.mes.core.annotation.Jinko;
import com.sw.mes.core.utils.BeanUtil;
import com.sw.mes.core.utils.DateUtil;
import com.sw.mes.core.utils.StringUtils;
import com.sw.mes.jip.constant.JIPConstant;
import com.sw.mes.jip.utils.JipUtil;
import com.sw.mes.sap.dto.jip.JipCloseOrderVerifyResult;
import com.sw.mes.sap.dto.jip.JipOrderStateResult;
import com.sw.mes.sap.dto.jip.JipProductionOrderResult;
import com.sw.mes.sap.service.SAPInputServiceService;
import com.sw.mes.sap.verify.VerifyWorkOrderState;
import com.sw.mes.sap.verify.VerifyWorkOrderStateFactory;
import com.sw.mes.yb.plan.entity.PlanProductionOrderBom;
import com.sw.mes.yb.plan.entity.ProductionOrder;
import com.sw.mes.yb.plan.service.PlanProductionOrderBomService;
import com.sw.mes.yb.plan.service.ProductionOrderService;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
@Transactional
@Jinko(value="针对晶科SAP数据交互处理业务逻辑Service",author = "liru")
public class SAPInputServiceImpl implements SAPInputServiceService {

    @Autowired
    private ProductionOrderService productionOrderService;
    
    @Autowired
    private PlanProductionOrderBomService planProductionOrderBomService;

    @Autowired
    private ProductModelService productModelService;

    @Autowired
    private MaterialModelService materialModelService;

    @Autowired
    private MachineCapacityInfoService machineCapacityInfoService;

    @Autowired
    private FactoryModelService factoryModelService;
    
    @Autowired
    private DictionaryItemService dictionaryItemService;
    @Autowired
    private VerifyWorkOrderStateFactory verifyWorkOrderStateFactory;


    @Override
    public void handlerProductonOrderData(JSONObject data, List<JipProductionOrderResult> results) throws RuntimeException {

        JSONArray IT_DATA = data.getJSONArray("IT_DATA");

        int length = IT_DATA.size();
        for (int i=0;i<length;i++){
            JSONObject orderJson = IT_DATA.getJSONObject(i);

            String WERKS = orderJson.getString("WERKS");
            String AUFNR = orderJson.getString("AUFNR");//订单编号
            String AUART = orderJson.getString("AUART");
            String AUARTTXT = orderJson.getString("AUARTTXT");
            Date GSTRP = orderJson.getDate("GSTRP");
            Date GLTRP = orderJson.getDate("GLTRP");
            /**于2024年1月19日拉晶定向工单标识管理方案沟通
会议决定，需要在拉晶工单上增加“定向标识”。逻辑如下：
1.定向标识为2位字符，Char类型。通过自定义配置表（表名请开发按规则定义）进行配置，该配置表中包含工厂代码（参考系统字段WERK_D），“工单类型”（参考系统字段AUART）“定向标识”（Char类型，2位），“定向标识描述”（Char类型，50位）。
2.在SAP中创建生产工单界面增加自定义字段，并且增加判断，对于配置表中的工厂+工单类型有配置的，则必须按配置表中满足条件输入定向标识。否则报错“你创建的是XX工厂XX工单类型，该工单为定向工单，请选择准确的定向标识！”。
3.如果用户有选择满足配置表中的定向标识，则将该标识保存至生产工单AUFK相应自定义字段中（还请在AUFK中增加本字段Z_ORIENTATION_IND）。并在SAP-MES工单下发接口中传输至MES。**/
            String Z_ORIENTATION_IND = orderJson.getString("Z_ORIENTATION_IND");
            String STAT = orderJson.getString("STAT");
            String RSNUM = orderJson.getString("RSNUM");
            String ZZORDER = orderJson.getString("ZZORDER");//研发订单号  -  内部研发唯一标识

            JipProductionOrderResult result = new JipProductionOrderResult(AUFNR,JipProductionOrderResult.SUCCESS,DateUtil.formatDate(new Date())+" Success");
            results.add(result);

            JSONArray ORDERLIST = orderJson.getJSONArray("ORDERLIST");
            int o_length = ORDERLIST.size();
            for (int j=0;j<o_length;j++){
            	 //订单物料信息
                JSONObject ORDER = ORDERLIST.getJSONObject(j);
                String MATNR = ORDER.getString("MATNR");
            	
            	ProductionOrder productionOrder = productionOrderService.findByAufnrAndMatnr(AUFNR,MATNR);
                if(productionOrder==null)
                    productionOrder = new ProductionOrder();
                productionOrder.setAufnr(AUFNR);//生产工单 - 订单编号
                productionOrder.setFbOrderNo(AUFNR);//订单编号
                productionOrder.setWerks(WERKS);//
                productionOrder.setAuart(AUART);
                productionOrder.setGstrp(GSTRP);
                productionOrder.setGltrp(GLTRP);
                
                //订单结束时间 23:59:59
                Date gltrpValue = productionOrder.getGltrp();
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(gltrpValue);
                calendar.set(Calendar.HOUR_OF_DAY, 23);
                calendar.set(Calendar.MINUTE, 59);
                calendar.set(Calendar.SECOND, 59);
                productionOrder.setGltrp(calendar.getTime());
                
                productionOrder.setStatus(STAT);//REL/TECO/DLFL
                productionOrder.setComment(RSNUM);//预留/相关需求的编号
                productionOrder.setAuarttxt(AUARTTXT);
                productionOrder.setZorientationind(Z_ORIENTATION_IND);//拉晶工单定向标识
                productionOrder.setRdonlylogo(ZZORDER);//内部研发唯一标识  -  研发订单号
            	
                String POSNR = ORDER.getString("POSNR");
                String MEINS = ORDER.getString("MEINS");
                BigDecimal GAMNG = ORDER.getBigDecimal("GAMNG");
                String ARBPL = ORDER.getString("ARBPL");
                String KTEXT = ORDER.getString("KTEXT");
                String Z_COLLECT_NO = ORDER.getString("Z_COLLECT_NO");
                String Z_COLLECT_ITM = ORDER.getString("Z_COLLECT_ITM");
                String KDAUF = ORDER.getString("KDAUF");
                String KDPOS = ORDER.getString("KDPOS");
                String ZEINR = ORDER.getString("ZEINR");
                String ZJSWJBH = ORDER.getString("ZJSWJBH");
                String KUNNR = ORDER.getString("KUNNR");
                String NAME1 = ORDER.getString("NAME1");
                String ZZLANDD = ORDER.getString("ZZLANDD");
                String VORNR = ORDER.getString("VORNR");
                String ZARBPL_LB = ORDER.getString("ZARBPL_LB");
                String ZWF_FLAG = ORDER.getString("ZWF_FLAG");
                String netGamng = ORDER.getString("net_gamng");
                String BEZEI = ORDER.getString("BEZEI");
                String ZZCOUNTRY = ORDER.getString("ZZCOUNTRY");
                

                productionOrder.setMatnr(MATNR);//物料编号
                productionOrder.setMenge(GAMNG);//总订单数量
                productionOrder.setMeins(MEINS);//基本计量单位
                productionOrder.setRdNum(POSNR);//订单项目编号
                //productionOrder.setRdonlylogo(POSNR);//订单项目编号
                productionOrder.setCustomerid(KUNNR);//客户编号
                productionOrder.setField4(ARBPL);//工作中心
                productionOrder.setField5(KTEXT);//工作中心描述
                productionOrder.setSalesorder(KDAUF);//销售订单号
                productionOrder.setKdpos(KDPOS);//销售订单行号
                productionOrder.setZCollectNo(Z_COLLECT_NO);//组合号
                productionOrder.setZCollectItm(Z_COLLECT_ITM);
                productionOrder.setZeinr(ZEINR);
                productionOrder.setZjswjbh(ZJSWJBH);
                productionOrder.setName1(NAME1);
                productionOrder.setZzlandd(ZZLANDD);
                productionOrder.setVornr(VORNR);
                productionOrder.setZarbplLb(ZARBPL_LB);//工作中心类别 20240105新增
                productionOrder.setZwfFlag(ZWF_FLAG);//外发标识 20240106新增
                productionOrder.setNetGamng(netGamng);
                productionOrder.setBezei(BEZEI);
                productionOrder.setZzcountry(ZZCOUNTRY);

                
                List<PlanProductionOrderBom> bomlist  = new ArrayList<PlanProductionOrderBom>();

                JSONArray BOMLIST = ORDER.getJSONArray("BOMLIST");
                int b_length = BOMLIST.size();
                for (int n=0;n<b_length;n++){
                    //订单物料信息
                    JSONObject BOM = BOMLIST.getJSONObject(n);
                    
                    String RSPOS = BOM.getString("RSPOS");
                    String LINESTAT = BOM.getString("LINESTAT");
                    String BOM_ARBPL = BOM.getString("ARBPL");
                    String BOM_MATNR = BOM.getString("MATNR");
                    String BDMNG = BOM.getString("BDMNG");
                    String ALPOS = BOM.getString("ALPOS");
                    String RGEKZ = BOM.getString("RGEKZ");
                    String DUMPS = BOM.getString("DUMPS");
                    String SCHGT = BOM.getString("SCHGT");
                    String KZKUP = BOM.getString("KZKUP");
                    String ZFCP = BOM.getString("ZFCP");
                    String BOM_MEINS = BOM.getString("MEINS");
                    String ZCHARG = BOM.getString("ZCHARG");
                    String POTX1 = BOM.getString("POTX1");
                    String SORTF = BOM.getString("SORTF");
                    String BOMQTY = BOM.getString("BOMQTY");
                    String MAKTX = BOM.getString("MAKTX");
                    
                    
                    PlanProductionOrderBom orderBom = new PlanProductionOrderBom();
                    orderBom.setRspos(RSPOS);
                    orderBom.setLinestat(LINESTAT);
                    orderBom.setArbpl(BOM_ARBPL);
                    orderBom.setMatnr(BOM_MATNR);
                    orderBom.setBdmng(BDMNG);
                    orderBom.setAlpos(ALPOS);
                    orderBom.setRgekz(RGEKZ);
                    orderBom.setDumps(DUMPS);
                    orderBom.setSchgt(SCHGT);
                    orderBom.setKzkup(KZKUP);
                    orderBom.setZfcp(ZFCP);
                    orderBom.setMeins(BOM_MEINS);
                    orderBom.setZcharg(ZCHARG);
                    orderBom.setPotx1(POTX1);
                    orderBom.setSortf(SORTF);
                    orderBom.setBomqty(BOMQTY);
                    orderBom.setMaktx(MAKTX);
                    bomlist.add(orderBom);
                }

                JSONArray CHRCTLIST = ORDER.getJSONArray("CHRCTLIST");
                int c_length = CHRCTLIST.size();
                for (int c=0;c<c_length;c++){
                    //CHRCTLIST信息
                    JSONObject CHRCT = CHRCTLIST.getJSONObject(c);
                    String ATNAM = CHRCT.getString("ATNAM");
                    String ATBEZ = CHRCT.getString("ATBEZ");
                    String ATWRT = CHRCT.getString("ATWRT");
                    String ATWTB = CHRCT.getString("ATWTB");

                    productionOrder.setAtnam(ATNAM);
                    productionOrder.setTbez(ATBEZ);
                    productionOrder.setAtwrt(ATWRT);
                    productionOrder.setAtwtb(ATWTB);


                }
                productionOrder.setCreateDate(new Date());

                
                productionOrder.setWorkType(Integer.parseInt(productionOrder.getZarbplLb()));

                ProductModel productModel = productModelService.findByCode(productionOrder.getMatnr());
                productionOrder.setProductModel(productModel);

                MaterialModel materialModel = materialModelService.findByCode(productionOrder.getMatnr());
                productionOrder.setMaterialModel(materialModel);
                
                if(materialModel!=null) {
                	productionOrder.setWgbez(materialModel.getWgbez());
                	productionOrder.setMtbez(materialModel.getName());
                	productionOrder.setVtext(materialModel.getVtext());
                	productionOrder.setMatkl(materialModel.getMatkl());
                	productionOrder.setNtgew(materialModel.getNtgew());
                	productionOrder.setLaeng(materialModel.getLaeng());
                	productionOrder.setBreit(materialModel.getBreit());
                	productionOrder.setHoehe(materialModel.getHoehe());
                	productionOrder.setProductType(materialModel.getProductName());//产品类别 - 产品简称
                	productionOrder.setResistanceType(materialModel.getType());//导电类型
                	productionOrder.setField3(materialModel.getSpecification());//规格
                	productionOrder.setField1(materialModel.getDopant());//掺杂剂
                }
                
                try {
	                MachineCapacityInfoDataDto dataDto = materialModelService.getMachineCapacityInfoDataDto(materialModel.getId());
	                if(dataDto.getConductionType()!=null && dataDto.getSpecification()!=null && dataDto.getDopant() !=null && dataDto.getSimpleName()!=null) {
	                	MachineCapacityInfo info = machineCapacityInfoService.getMachineCapacityInfoJk(dataDto.getConductionType(), dataDto.getSpecification(),dataDto.getDopant(),dataDto.getSimpleName());
	                	productionOrder.setMachineCapacityId(info.getId());
	    	        }
                }catch (Exception e) {
				}
                
                //默认自动生产
                if(StringUtils.isNotBlank(productionOrder.getStatus()) && ((productionOrder.getStatus().equals("TECO"))  || (productionOrder.getStatus().equals("DLFL")))){
                	productionOrder.setProductionStatus(false);
                }else {
                	productionOrder.setProductionStatus(true);
                }
                
                productionOrderService.saveOrUpdate(productionOrder);
                
                //保存更新bom信息
                for (PlanProductionOrderBom orderBom : bomlist) {
                	PlanProductionOrderBom targetBom = planProductionOrderBomService.findByOrderIdAndMatnr(productionOrder.getId(), orderBom.getMatnr());
                	if(targetBom==null) {
                		targetBom = new PlanProductionOrderBom();
                	}
                	
                	BeanUtil.copyProperties(orderBom, targetBom, "id");
                	targetBom.setPlanProductionOrderId(productionOrder.getId());
                	planProductionOrderBomService.saveOrUpdate(targetBom);
                }
            }
        }
    }
    
    
    @Override
    public void synProductonOrderBomData(Long orderId , JSONObject data) throws RuntimeException {

        JSONArray IT_DATA = data.getJSONArray("IT_DATA");

        int length = IT_DATA.size();
        for (int i=0;i<length;i++){
            JSONObject orderJson = IT_DATA.getJSONObject(i);

            JSONArray ORDERLIST = orderJson.getJSONArray("ORDERLIST");
            int o_length = ORDERLIST.size();
            for (int j=0;j<o_length;j++){
            	 //订单物料信息
                JSONObject ORDER = ORDERLIST.getJSONObject(j);
            	
            	ProductionOrder productionOrder = productionOrderService.get(orderId);
                
                List<PlanProductionOrderBom> bomlist  = new ArrayList<PlanProductionOrderBom>();

                JSONArray BOMLIST = ORDER.getJSONArray("BOMLIST");
                int b_length = BOMLIST.size();
                for (int n=0;n<b_length;n++){
                    //订单物料信息
                    JSONObject BOM = BOMLIST.getJSONObject(n);
                    
                    String RSPOS = BOM.getString("RSPOS");
                    String LINESTAT = BOM.getString("LINESTAT");
                    String BOM_ARBPL = BOM.getString("ARBPL");
                    String BOM_MATNR = BOM.getString("MATNR");
                    String BDMNG = BOM.getString("BDMNG");
                    String ALPOS = BOM.getString("ALPOS");
                    String RGEKZ = BOM.getString("RGEKZ");
                    String DUMPS = BOM.getString("DUMPS");
                    String SCHGT = BOM.getString("SCHGT");
                    String KZKUP = BOM.getString("KZKUP");
                    String ZFCP = BOM.getString("ZFCP");
                    String BOM_MEINS = BOM.getString("MEINS");
                    String ZCHARG = BOM.getString("ZCHARG");
                    String POTX1 = BOM.getString("POTX1");
                    String SORTF = BOM.getString("SORTF");
                    String BOMQTY = BOM.getString("BOMQTY");
                    String MAKTX = BOM.getString("MAKTX");
                    
                    
                    PlanProductionOrderBom orderBom = new PlanProductionOrderBom();
                    orderBom.setRspos(RSPOS);
                    orderBom.setLinestat(LINESTAT);
                    orderBom.setArbpl(BOM_ARBPL);
                    orderBom.setMatnr(BOM_MATNR);
                    orderBom.setBdmng(BDMNG);
                    orderBom.setAlpos(ALPOS);
                    orderBom.setRgekz(RGEKZ);
                    orderBom.setDumps(DUMPS);
                    orderBom.setSchgt(SCHGT);
                    orderBom.setKzkup(KZKUP);
                    orderBom.setZfcp(ZFCP);
                    orderBom.setMeins(BOM_MEINS);
                    orderBom.setZcharg(ZCHARG);
                    orderBom.setPotx1(POTX1);
                    orderBom.setSortf(SORTF);
                    orderBom.setBomqty(BOMQTY);
                    orderBom.setMaktx(MAKTX);
                    bomlist.add(orderBom);
                }
                
                //保存更新bom信息
                for (PlanProductionOrderBom orderBom : bomlist) {
                	PlanProductionOrderBom targetBom = planProductionOrderBomService.findByOrderIdAndMatnr(productionOrder.getId(), orderBom.getMatnr());
                	if(targetBom==null) {
                		targetBom = new PlanProductionOrderBom();
                	}
                	
                	BeanUtil.copyProperties(orderBom, targetBom, "id");
                	targetBom.setPlanProductionOrderId(productionOrder.getId());
                	planProductionOrderBomService.saveOrUpdate(targetBom);
                }
            }
        }
    }
    

    @Override
    public void handlerOrderState(Object data, JipOrderStateResult result) {
        Map<String,Object> mapData = JipUtil.getMap(data, JIPConstant.IT_DATA);
        Object moName = mapData.get("moName");
        if(StringUtils.isNotBlank(moName.toString())) {
            ProductionOrder productionOrder = productionOrderService.findByAufnr(moName.toString());
            if(productionOrder!=null && productionOrder.getStatus()!=null && productionOrder.getStatus().equals("CLOSE")){
                result.setCode(1);
                result.setMessage("工单【"+moName+"】不存在在制工序，能关单！");
            }else{
                result.setCode(0);
                result.setMessage("工单【"+moName+"】存在在制工序，不能关单！");
            }
        }
    }


	@Override
	public void handlerVerifyWorkOrderState(Object data, JipCloseOrderVerifyResult result) {
		Map<String,Object> mapData = JipUtil.getMap(data, JIPConstant.IT_DATA);
        Object WERKS = mapData.get("WERKS");
        Object AUFNR = mapData.get("AUFNR");
        
        if(WERKS==null || StringUtils.isBlank(WERKS.toString())) {
        	result.setStatus(false);
            result.setMsg("工厂编码未传入");
            return;
        }
        
        if(AUFNR==null || StringUtils.isBlank(AUFNR.toString())) {
        	result.setStatus(false);
            result.setMsg("工单未传入");
            return;
        }
        
        //初始化返回结果
        result.setWerks(WERKS.toString());
        result.setAufnr(AUFNR.toString());
        result.setStatus(true);
        result.setMsg("工单【"+AUFNR+"】验证通过,可以关单！");
        
        List<DictionaryItem> closeVerifySwitchs = dictionaryItemService.findByThemeValueAndEnableOrderByPriority("CloseVerifySwitch", true);
        for (DictionaryItem dictionaryItem : closeVerifySwitchs) {
			if(StringUtils.isNotBlank(dictionaryItem.getValue()) && dictionaryItem.getValue().equals("true")) {
				VerifyWorkOrderState verify = verifyWorkOrderStateFactory.getVerify(dictionaryItem);
				if(verify!=null) {
					verify.executeVerify(result,AUFNR.toString(),WERKS.toString());
					if(!result.getStatus()) {
						log.info("[{}]:{},验证器地址:{},验证结果:{}",AUFNR.toString(),dictionaryItem.getName(),dictionaryItem.getExtendValue(),result.getMsg());
						break;
					}else {
						log.info("[{}]:{},验证器地址:{},验证结果:{}",AUFNR.toString(),dictionaryItem.getName(),dictionaryItem.getExtendValue(),"验证通过");
					}
				}
			}
		}
	}
}
