package cn.estsh.i3plus.ext.mes.pcn.apiservice.serviceimpl.busi.collect;

import cn.estsh.i3plus.ext.mes.pcn.api.busi.ISxThirdPartyPlcCollectDataStepService;
import cn.estsh.i3plus.ext.mes.pcn.api.busi.jx.IJxPlcExtService;
import cn.estsh.i3plus.ext.mes.pcn.api.busi.jx.IJxProductDataService;
import cn.estsh.i3plus.ext.mes.pcn.pojo.util.MesPcnExtConstWords;
import cn.estsh.i3plus.ext.mes.pcn.pojo.util.MesPcnExtEnumUtil;
import cn.estsh.i3plus.platform.common.convert.ConvertBean;
import cn.estsh.i3plus.pojo.mes.bean.MesObjectCfg;
import cn.estsh.i3plus.pojo.mes.bean.MesProductData;
import cn.estsh.i3plus.pojo.mes.model.ProductDataModel;
import cn.estsh.i3plus.pojo.mes.model.StepResult;
import cn.estsh.impp.framework.boot.util.SpringContextsUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 第三方PLC数据采集定时任务---步骤执行---写节拍
 */
@Slf4j
public class SxThirdPartyPlcCollectProductDataStepService implements ISxThirdPartyPlcCollectDataStepService {

    private IJxPlcExtService plcExtService;

    private IJxProductDataService productDataService;

    protected List<String> targetFieldList;

    public SxThirdPartyPlcCollectProductDataStepService() {
        this.plcExtService = (IJxPlcExtService) SpringContextsUtil.getBean("jxPlcExtService");
        this.productDataService = (IJxProductDataService) SpringContextsUtil.getBean("jxProductDataService");
    }

    public SxThirdPartyPlcCollectProductDataStepService targetField(List<String> targetFieldList) {
        this.targetFieldList = targetFieldList;
        return this;
    }

    @Override
    public StepResult exec(StepResult stepResult) {

        String organizeCode = (String) ((Map<String, Object>) stepResult.getData()).get(MesPcnExtConstWords.ORGANIZE_CODE);
        String userInfo = (String) ((Map<String, Object>) stepResult.getData()).get(MesPcnExtConstWords.USER_INFO);
        String workCenterCode = (String) ((Map<String, Object>) stepResult.getData()).get(MesPcnExtConstWords.WORK_CENTER_CODE);
        String workCellCode = (String) ((Map<String, Object>) stepResult.getData()).get(MesPcnExtConstWords.WORK_CELL_CODE);
        String serialNumber = (String) ((Map<String, Object>) stepResult.getData()).get(MesPcnExtConstWords.SERIAL_NUMBER);
        String productSn = (String) ((Map<String, Object>) stepResult.getData()).get(MesPcnExtConstWords.PRODUCT_SN);
        String manageCode = (String) ((Map<String, Object>) stepResult.getData()).get(MesPcnExtConstWords.MANAGE_CODE);
        String workOrderNo = (String) ((Map<String, Object>) stepResult.getData()).get(MesPcnExtConstWords.WORK_ORDER_NO);
        String partNo = (String) ((Map<String, Object>) stepResult.getData()).get(MesPcnExtConstWords.PART_NO);
        String partNameRdd = (String) ((Map<String, Object>) stepResult.getData()).get(MesPcnExtConstWords.PART_NAME_RDD);
        String key = (String) ((Map<String, Object>) stepResult.getData()).get(MesPcnExtConstWords.KEY);

        String objectCfgStr = plcExtService.getCachedData(key, MesPcnExtConstWords.OBJECT_CODE_UC);
        if (StringUtils.isEmpty(objectCfgStr)) return stepResult.isCompleted(false).msg(String.format("生产线[%s]工位[%s]缓存信息缺失对象结构信息!", workCenterCode, workCellCode));
        List<MesObjectCfg> objectCfgList = JSONObject.parseArray(objectCfgStr, MesObjectCfg.class);
        if (CollectionUtils.isEmpty(objectCfgList)) return stepResult.isCompleted(false).msg(String.format("生产线[%s]工位[%s]缓存信息缺失有效的对象结构信息!", workCenterCode, workCellCode));

        Map<String, List<MesObjectCfg>> objectCodeMap = objectCfgList.stream().filter(o -> null != o).collect(Collectors.groupingBy(MesObjectCfg::getObjectCode));

        List<MesProductData> productDataList = new ArrayList<>();
        for (String objectCode : objectCodeMap.keySet()) {
            if (StringUtils.isEmpty(objectCode)) continue;

            MesProductData productData = new MesProductData();
            productData.setOrganizeCode(organizeCode);
            productData.setWorkCenterCode(workCenterCode);
            productData.setWorkCellCode(workCellCode);
            productData.setSerialNumber(serialNumber);
            productData.setProductSn(productSn);
            productData.setGroupNo(manageCode);
            productData.setPartNo(partNo);
            productData.setPartDesc(partNameRdd);
            productData.setOrderNo(workOrderNo);
            productData.setObjectCode(objectCode);
            productData.setLineData(JSON.toJSONString(getLineDataList(stepResult, objectCodeMap.get(objectCode))));
            productData.setSystemSyncStatus(MesPcnExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue());
            ConvertBean.serviceModelInitialize(productData, userInfo);
            productDataList.add(productData);
        }

        productDataService.insertProductDataNoRollback(productDataList);

        return stepResult;
    }

    private List<ProductDataModel> getLineDataList(StepResult stepResult, List<MesObjectCfg> objectCfgList) {
        List<ProductDataModel> lineDataList = new ArrayList<>();
        for (MesObjectCfg objectCfg : objectCfgList) {
            if (null == objectCfg) continue;
            ProductDataModel productDataModel = new ProductDataModel();
            productDataModel.setFieldCode(objectCfg.getFieldCode());
            productDataModel.setFieldName(objectCfg.getFieldName());
            productDataModel.setFieldValue((String) ((Map<String, Object>) stepResult.getData()).get(objectCfg.getPlcCode()));
            lineDataList.add(productDataModel);
        }
        return lineDataList;
    }

}
