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

import cn.estsh.i3plus.ext.mes.pcn.api.busi.IDcsForEquipmentService;
import cn.estsh.i3plus.platform.common.convert.ConvertBean;
import cn.estsh.i3plus.platform.common.tool.TimeTool;
import cn.estsh.i3plus.pojo.base.bean.DdlPackBean;
import cn.estsh.i3plus.pojo.base.enumutil.CommonEnumUtil;
import cn.estsh.i3plus.pojo.base.tool.DdlPreparedPack;
import cn.estsh.i3plus.pojo.mes.bean.*;
import cn.estsh.i3plus.pojo.mes.model.MesReturnModel;
import cn.estsh.i3plus.pojo.mes.repository.*;
import cn.estsh.i3plus.pojo.mes.util.MesExtEnumUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Locale;

@Slf4j
@Service
public class DcsForEquipmentServiceImpl implements IDcsForEquipmentService {

    @Autowired
    private MesCustomerSnTransformService mesCustomerSnTransformService;

    @Autowired
    private MesProduceSnRepository mesProduceSnRao;

    @Autowired
    private MesConfigRepository mesConfigRao;

    @Autowired
    private MesPcScanLogRepository scanLogRao;


    @Autowired
    private MesCustomerPartRepository customerPartRao;

    @Autowired
    private MesProductionRecordRepository recordRao;

    @Autowired
    private MesPartSapRepository partSapRao;




    @Override
    public String doGetConsoleItemCode(String barcode, String custCode, String custPlantCode, String workCenterCode, String workCellCode) {
        //通用二维码组成部分('RS'为记录分隔符ASCII:30，'GS'为分组符ASCII:29,'EOT'为传输结束符ASCII:04)
        //[)>+'RS'+06+'GS'+Y+vpps+'GS'+P+8位客户零件号+'GS'+12V+DUNS+'GS'+T+1位line num+1位班次号+2位年份+3位天数+1位追溯(精确追溯A，批次追溯@)+2工程更改记录+2位自定义+4位流水号+'RS'+'EOT'
        //如：[)>+'RS'+06+'GS'+Y+4110000000000X+'GS'+P+12345678+'GS'+12V+545295227+'GS'+T+1A13304A2B4C0001+'RS'+'EOT'
        //包含ASCII码的条码 65位，不包含的 58位

        barcode = mesCustomerSnTransformService.transformBarCodeGm(barcode);

        //todo 读取配置文件 获取工厂
            String organizeCode;
            DdlPackBean ddlPackBean = DdlPackBean.getDdlPackBean();
            DdlPreparedPack.getStringEqualPack("ORGANIZE_CODE","cfgKey",ddlPackBean);
            List<MesConfig> organizeConfig = mesConfigRao.findByHqlWhere(ddlPackBean);
            if (!organizeConfig.isEmpty()) {
                organizeCode = organizeConfig.get(0).getCfgValue();
            }else {
                log.error("请在mes_cfg中配置工厂代码,cfgCode为ORGANIZE_CODE");
                return "2";
            }
        //2.根据条码表查询一条，排序条码表条码唯一
        DdlPackBean producePackBean = DdlPackBean.getDdlPackBean(organizeCode);
        DdlPreparedPack.getStringEqualPack(barcode,"productSn",producePackBean);
        DdlPreparedPack.getOrderBy("createDatetime", CommonEnumUtil.ASC_OR_DESC.DESC.getValue(), producePackBean);
        List<MesProduceSn> produceSnList = mesProduceSnRao.findByHqlTopWhere(producePackBean, 1);

        String custPartNo="";
        //4.如果在条码表中能查询出数据，插入到scanMonitor一条记录
        if (!produceSnList.isEmpty()) {
            MesPcScanLog scanLog = new MesPcScanLog();
            scanLog.setScanTime(TimeTool.getNowTime(true));
            scanLog.setWorkCenterCode(workCenterCode);
            scanLog.setWorkCellCode(workCellCode);
            scanLog.setCustSn(barcode);
            scanLog.setOrganizeCode(organizeCode);
            ConvertBean.saveOrUpdate(scanLog,"JOB");
            scanLogRao.insert(scanLog);
            //4.返回客户条码
            custPartNo = produceSnList.get(0).getCustPartNo();
            String partNo = produceSnList.get(0).getPartNo();
            if (StringUtils.isEmpty(custPartNo)){
                //根据erpPartNo查询客户零件号
                DdlPackBean custPartPackBean = DdlPackBean.getDdlPackBean(organizeCode);
                DdlPreparedPack.getStringEqualPack(partNo,"erpPartNo",custPartPackBean);
                if (!StringUtils.isEmpty(custCode)){
                    DdlPreparedPack.getStringEqualPack(custPartNo,"custCode",custPartPackBean);
                }
                List<MesCustomerPart> customerPartList = customerPartRao.findByHqlTopWhere(custPartPackBean, 1);
                if (!customerPartList.isEmpty()) {
                    custPartNo = customerPartList.get(0).getCustPartNo();
                }
            }
            log.info("castle-返回的客户零件号为:{}",custPartNo);
            return custPartNo;
        }
        return "";
    }

    @Override
    public String doFillConsoleResultExt( String barcode, String partNo, String result, String workCenterCode, String workCellCode, String custCode) {
        barcode = mesCustomerSnTransformService.transformBarCodeGm(barcode);
            String organizeCode="";
            DdlPackBean ddlPackBean = DdlPackBean.getDdlPackBean();
            DdlPreparedPack.getStringEqualPack("ORGANIZE_CODE","cfgKey",ddlPackBean);
            List<MesConfig> organizeConfig = mesConfigRao.findByHqlWhere(ddlPackBean);
            if (!organizeConfig.isEmpty()) {
                organizeCode = organizeConfig.get(0).getCfgValue();
            }

        MesPcScanLog scanLog = new MesPcScanLog();
        scanLog.setScanTime(TimeTool.getNowTime(true));
        scanLog.setWorkCenterCode(workCenterCode);
        scanLog.setWorkCellCode(workCellCode);
        scanLog.setCustSn(barcode);
        scanLog.setOrganizeCode(organizeCode);
        scanLog.setRemark(partNo+":"+result);
        ConvertBean.saveOrUpdate(scanLog,"JOB");
        scanLogRao.insert(scanLog);

        String erpPartNo = "";
        //查询erp零件号 根据客户零件号
        DdlPackBean custPartPackBean = DdlPackBean.getDdlPackBean(organizeCode);
        DdlPreparedPack.getStringEqualPack(partNo,"custPartNo",custPartPackBean);
        if (!StringUtils.isEmpty(custCode)){
            DdlPreparedPack.getStringEqualPack(custCode,"custCode",custPartPackBean);
        }
        DdlPreparedPack.getOrderBy("createDatetime",CommonEnumUtil.ASC_OR_DESC.DESC.getValue(), custPartPackBean);
        List<MesCustomerPart> customerPartList = customerPartRao.findByHqlTopWhere(custPartPackBean, 1);
        if (!customerPartList.isEmpty()){
             erpPartNo = customerPartList.get(0).getErpPartNo();
        }

        if (StringUtils.isNotBlank(erpPartNo)){
            DdlPackBean erpPartPackBean = DdlPackBean.getDdlPackBean(organizeCode);
            DdlPreparedPack.getStringEqualPack(erpPartNo,"partNo",erpPartPackBean);
            List<MesPartSap> partSapList = partSapRao.findByHqlTopWhere(erpPartPackBean, 1);
            String partName = "";
            if (!partSapList.isEmpty()){
                 partName = partSapList.get(0).getPartName();
            }
            //插入生产记录表 reportType 无需汇报 status 无需汇报
            MesProductionRecord mesProductionRecord = new MesProductionRecord();
            mesProductionRecord.setPartNo(erpPartNo);
            mesProductionRecord.setPartName(partName);
            mesProductionRecord.setProductSn(barcode);
            mesProductionRecord.setWorkCellCode(workCellCode);
            mesProductionRecord.setWorkCenterCode(workCenterCode);
            mesProductionRecord.setReportStatus(MesExtEnumUtil.REPORT_STATUS.REPORT_STATUS_30.getValue());
            mesProductionRecord.setReportType(MesExtEnumUtil.MES_REPORT_TYPE.NO_REPORT.getValue());
            mesProductionRecord.setOrganizeCode(organizeCode);
            mesProductionRecord.setStartDateTime(TimeTool.getNowTime(true));
            mesProductionRecord.setCompleteDateTime(TimeTool.getNowTime(true));
            mesProductionRecord.setRemark("电测试:"+result);
            ConvertBean.saveOrUpdate(mesProductionRecord,"电测试");
            recordRao.insert(mesProductionRecord);

        }
        return "1";
    }

    @Override
    public String doGetConsoleItemCode(String organizeCode, String barcode, String custCode, String custPlantCode) {
        //1.根据barcode 和 organizeCode查询条码表mes_produce_sn
        DdlPackBean snPackBean = DdlPackBean.getDdlPackBean(organizeCode);
        DdlPreparedPack.getStringEqualPack(barcode,"produceSn",snPackBean);
        List<MesProduceSn> produceSnList = mesProduceSnRao.findByHqlTopWhere(snPackBean, 1);
        if (!produceSnList.isEmpty()) {

            //2.查询生产记录表，如果生产记录数量 <= 0 return ""
            DdlPackBean productionLogPackBean = DdlPackBean.getDdlPackBean(organizeCode);
            DdlPreparedPack.getStringEqualPack(barcode,"sn",productionLogPackBean);
            int count = recordRao.findByHqlWhereCount(productionLogPackBean);
            if (count <= 0){
                return "";
            }
            //3.
            MesProduceSn mesProduceSn = produceSnList.get(0);

            MesPcScanLog scanLog = new MesPcScanLog();
            scanLog.setScanTime(TimeTool.getNowTime(true));
            scanLog.setWorkCenterCode("ZP1008");
            scanLog.setWorkCellCode("ZP1008");
            scanLog.setCustSn(barcode);
            scanLog.setOrganizeCode(organizeCode);
            ConvertBean.saveOrUpdate(scanLog,"webService-doGetConsoleItemCode");
            scanLogRao.insert(scanLog);
            return mesProduceSn.getCustPartNo();
        }
        return "";
    }

    @Override
    public String doFillConsoleResult(String organizeCode,String barcode, String partNO, String result, String workCenterCode, String workCellCode) {
        if (StringUtils.isBlank(organizeCode)) {
            DdlPackBean ddlPackBean = DdlPackBean.getDdlPackBean();
            DdlPreparedPack.getStringEqualPack("ORGANIZE_CODE","cfgCode",ddlPackBean);
            List<MesConfig> organizeConfig = mesConfigRao.findByHqlWhere(ddlPackBean);
            if (!organizeConfig.isEmpty()) {
                organizeCode = organizeConfig.get(0).getCfgValue();
            }
        }

        MesPcScanLog scanLog = new MesPcScanLog();
        scanLog.setScanTime(TimeTool.getNowTime(true));
        scanLog.setWorkCenterCode(workCenterCode);
        scanLog.setWorkCellCode(workCellCode);
        scanLog.setCustSn(barcode);
        scanLog.setOrganizeCode(organizeCode);
        scanLog.setRemark(partNO+":"+result);
        ConvertBean.saveOrUpdate(scanLog,"JOB");
        scanLogRao.insert(scanLog);

        return "1";
    }

    @Override
    public MesReturnModel doGetConsoleItemCodeAndProcess(String organizeCode, String barcode, String custCode, String custPlantCode) {
        MesReturnModel mesReturnModel = new MesReturnModel();
        //1.根据barcode 和 organizeCode查询条码表mes_produce_sn
        DdlPackBean snPackBean = DdlPackBean.getDdlPackBean(organizeCode);
        DdlPreparedPack.getStringEqualPack(barcode,"productSn",snPackBean);
        List<MesProduceSn> produceSnList = mesProduceSnRao.findByHqlTopWhere(snPackBean, 1);
        if (!produceSnList.isEmpty()) {

            //2.查询生产记录表，如果生产记录数量 <= 0 return ""
            DdlPackBean productionLogPackBean = DdlPackBean.getDdlPackBean(organizeCode);
            DdlPreparedPack.getStringEqualPack(barcode,"productSn",productionLogPackBean);
            DdlPreparedPack.getOrderBy("createDatetime",CommonEnumUtil.ASC_OR_DESC.DESC.getValue(),productionLogPackBean);
            List<MesProductionRecord> productionRecords = recordRao.findByHqlTopWhere(productionLogPackBean,1);
            if (!productionRecords.isEmpty()){
                String processCode = productionRecords.get(0).getProcessCode();
                mesReturnModel.setProcessCode(processCode);
            }
            //3.
            MesProduceSn mesProduceSn = produceSnList.get(0);
            mesReturnModel.setPartNo(mesProduceSn.getPartNo());
            MesPcScanLog scanLog = new MesPcScanLog();
            scanLog.setScanTime(TimeTool.getNowTime(true));
            scanLog.setWorkCenterCode("ZP1008");
            scanLog.setWorkCellCode("ZP1008");
            scanLog.setCustSn(barcode);
            scanLog.setOrganizeCode(organizeCode);
            ConvertBean.saveOrUpdate(scanLog,"webService-doGetConsoleItemCodeAndProcess");
            scanLogRao.insert(scanLog);
            return mesReturnModel;
        }
        return mesReturnModel;
    }


    private String createBarCode(String barcode){
        String barcodeResult = "";
        if (StringUtils.isEmpty(barcode)){
            return barcodeResult;
        }
        //缺少了ascii码,根据规则拼接出来
        //正常65 [)>06Y4110000000000XP2656085012V545238347T1A24269A2B4C0003
        //异常58 [)>06Y4110000000000XP2656085012V545238347T1A24269A2B4C0003
        if (barcode.length() == 58){
            String part1 = barcode.substring(0, 3);
            String part2 = barcode.substring(3, 5);
            String part3 = barcode.substring(5, 20);
            String part4 = barcode.substring(20, 29);
            String part5 = barcode.substring(29,41);
            String part6 = barcode.substring(41);

            barcodeResult = part1 + (char)30 + part2 +(char)29 + part3 + (char)29 + part4 +(char)29 + part5 +(char)29 + part6 + (char)30 + (char)04;
        }
        return barcodeResult;
    }
}
