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

import cn.estsh.i3plus.ext.mes.pcn.api.base.IBomTakeEffectService;
import cn.estsh.i3plus.ext.mes.pcn.api.base.ISxPcnHttpService;
import cn.estsh.i3plus.ext.mes.pcn.api.busi.IProduceSnExtService;
import cn.estsh.i3plus.ext.mes.pcn.pojo.bean.MesBomTakeEffectRecord;
import cn.estsh.i3plus.ext.mes.pcn.pojo.bean.MesPartExt;
import cn.estsh.i3plus.ext.mes.pcn.pojo.bean.MesProduceSnExt;
import cn.estsh.i3plus.ext.mes.pcn.pojo.model.BomTakeEffectModel;
import cn.estsh.i3plus.ext.mes.pcn.pojo.model.WmsBomTotalModel;
import cn.estsh.i3plus.ext.mes.pcn.pojo.repository.MesBomTakeEffectRecordRepository;
import cn.estsh.i3plus.ext.mes.pcn.pojo.repository.MesPartExtRepository;
import cn.estsh.i3plus.ext.mes.pcn.pojo.util.MesPcnExtConstWords;
import cn.estsh.i3plus.mes.pcn.util.PcnHttpUtil;
import cn.estsh.i3plus.platform.common.convert.ConvertBean;
import cn.estsh.i3plus.platform.common.exception.ImppExceptionEnum;
import cn.estsh.i3plus.platform.common.tool.JsonUtilTool;
import cn.estsh.i3plus.platform.common.tool.TimeTool;
import cn.estsh.i3plus.platform.common.util.MesConstWords;
import cn.estsh.i3plus.pojo.base.bean.BaseResultBean;
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.MesBom;
import cn.estsh.i3plus.pojo.mes.repository.MesBomRepository;
import cn.estsh.impp.framework.boot.exception.ImppExceptionBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 文件描述
 *
 * @author xiangming.liao
 * @date 2021年03月27日 15:45
 */
@Slf4j
@Service
public class BomTakeEffectService implements IBomTakeEffectService {
    @Autowired
    private IProduceSnExtService produceSnExtService;
    @Autowired
    private ISxPcnHttpService pcnHttpService;
    @Autowired
    private MesBomRepository bomRepository;
    @Autowired
    private MesBomTakeEffectRecordRepository bomTakeEffectRecordRepository;
    @Autowired
    private MesPartExtRepository partExtRDao;

    @Override
    public MesProduceSnExt queryProduceSnBySn(String serialNumber, String organizeCode) {
        return produceSnExtService.getProduceSnExtBySn(organizeCode, serialNumber);
    }

    @Override
    public List<WmsBomTotalModel> queryWmsBomTotalByPartNo(String partNo, String organizeCode) throws IOException {
        String requestUrl = pcnHttpService.getRequestUrl(organizeCode, MesPcnExtConstWords.FIND_BY_PARTNO);
        Map<String, String> params = new HashMap<>();
        params.put(MesPcnExtConstWords.PART_NO, partNo);
        params.put(MesPcnExtConstWords.ORGANIZE_CODE, organizeCode);
        String data = PcnHttpUtil.doPost(requestUrl, params);
        BaseResultBean baseResultBean = null;
        List<WmsBomTotalModel> wmsBomTotalList = new ArrayList<>();
        if (!StringUtils.isEmpty(data)) {
            baseResultBean = JsonUtilTool.decode(data, BaseResultBean.class);
        } else {
            log.error("HTTP[{}]调用mes获取wmsBomTotal信息接口失败", requestUrl);
        }
        if (null != baseResultBean && baseResultBean.success) {
            wmsBomTotalList = (List<WmsBomTotalModel>) baseResultBean.getResultList();
        }
        if (CollectionUtils.isEmpty(wmsBomTotalList)) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES_PCN.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_EXIT.getCode())
                    .setErrorDetail("无法获取此bom信息")
                    .build();
        }
        return wmsBomTotalList;
    }

    @Override
    public void doEffect(BomTakeEffectModel bomTakeEffectModel) throws IOException {
        String organizeCode = bomTakeEffectModel.getOrganizeCode();
        List<WmsBomTotalModel> wmsBomTotalModels = bomTakeEffectModel.getWmsBomTotalModels();
        String userName = bomTakeEffectModel.getUserInfo();
        String partNo = bomTakeEffectModel.getPartNo();
        String workOrderNo = bomTakeEffectModel.getWorkOrderNo();
        String partNameRdd = bomTakeEffectModel.getPartNameRdd();
        String productSn = bomTakeEffectModel.getProductSn();

        //String jsonWmsBomTotalList = JSON.toJSONString(wmsBomTotalModels);
        String bomEffectRequestUrl = pcnHttpService.getRequestUrl(organizeCode, MesPcnExtConstWords.BOM_TASK_EFFECT);
        /*log.info("PCN获取MES接口路径:{}", bomEffectRequestUrl);
        for (int i = 0; i < wmsBomTotalModels.size(); i++) {
            wmsBomTotalModels.get(i).setModifyUser(userName);
            wmsBomTotalModels.get(i).setModifyDatetime(TimeTool.getNowTime(true));
            wmsBomTotalModels.get(i).setCreateUser(userName);
            wmsBomTotalModels.get(i).setCreateDatetime(TimeTool.getNowTime(true));
        }*/
        //Map<String, String> params = new HashMap<>();
        // params.put("wmsBomTotalModels", jsonWmsBomTotalList);
        Map<String, String> params = new HashMap<>();
        params.put(MesPcnExtConstWords.PART_NO, partNo);
        params.put(MesPcnExtConstWords.ORGANIZE_CODE, organizeCode);
        String bomEffectData = PcnHttpUtil.doPost(bomEffectRequestUrl, params);
        log.info("HTTP调用MES微服务接口得到结果:{}", bomEffectData);

        BaseResultBean bomEffectResultBean = null;
        if (!StringUtils.isEmpty(bomEffectData)) {
            bomEffectResultBean = JsonUtilTool.decode(bomEffectData, BaseResultBean.class);
        } else {
            log.error("HTTP[{}]调用mes Bom生效接口失败", bomEffectResultBean);
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES_PCN.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_EXIT.getCode())
                    .setErrorDetail("HTTP调用mes Bom生效接口失败,请联系管理员")
                    .build();
        }

        if (null != bomEffectResultBean && bomEffectResultBean.success) {
            log.info("MES进行BOM数据更新");
            //先删除bom表 该父物料下的BOM
            DdlPackBean packBean = DdlPackBean.getDdlPackBean(organizeCode);
            DdlPreparedPack.getStringEqualPack(partNo, MesPcnExtConstWords.PART_NO, packBean);
            List<MesBom> bomListByDb = bomRepository.findByHqlWhere(packBean);
            bomRepository.deleteAll(bomListByDb);
            //再插入MesBom表
            List<MesBom> mesBomList = new ArrayList<>();

            for (int i = 0; i < wmsBomTotalModels.size(); i++) {
                MesBom bom = new MesBom();
                BeanUtils.copyProperties(wmsBomTotalModels.get(i), bom, "id");
                bom.setUnit(wmsBomTotalModels.get(i).getUNIT());
                bom.setBomCode(wmsBomTotalModels.get(i).getBomNum());
                ConvertBean.serviceModelInitialize(bom, userName);
                mesBomList.add(bom);
            }
            bomRepository.saveAll(mesBomList);
            //插入BOM生效记录表
            MesBomTakeEffectRecord bomTakeEffectRecord = new MesBomTakeEffectRecord();
            bomTakeEffectRecord.setWorkOrderNo(workOrderNo);
            bomTakeEffectRecord.setPartNo(partNo);

            MesPartExt partExt = partExtRDao.getByProperty(
                    new String[]{MesConstWords.ORGANIZE_CODE, MesConstWords.IS_DELETED, MesConstWords.IS_VALID, MesPcnExtConstWords.PART_NO},
                    new Object[]{organizeCode, CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue(), CommonEnumUtil.IS_VAILD.VAILD.getValue(), partNo});
            if (null != partExt) {
                bomTakeEffectRecord.setPartName(partExt.getPartName());
            }
            bomTakeEffectRecord.setTakeEffectTime(TimeTool.getNowTime(true));
            bomTakeEffectRecord.setTaskUser(userName);
            bomTakeEffectRecord.setProductSn(productSn);
            bomTakeEffectRecord.setOrganizeCode(organizeCode);
            ConvertBean.serviceModelInitialize(bomTakeEffectRecord, userName);
            bomTakeEffectRecordRepository.save(bomTakeEffectRecord);
        }

    }

}
