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

import cn.estsh.i3plus.ext.mes.pcn.api.busi.IMesProdMouldStatisticsService;
import cn.estsh.i3plus.ext.mes.pcn.apiservice.dao.IMesProdMouldStatisticsDao;
import cn.estsh.i3plus.ext.mes.pcn.pojo.util.MesPcnExtConstWords;
import cn.estsh.i3plus.mes.pcn.api.iservice.base.IConfigService;
import cn.estsh.i3plus.mes.pcn.util.DateUtil;
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.repository.IMesMouldMappingCfgRepository;
import cn.estsh.i3plus.pojo.mes.repository.MesProdMouldRecordRepository;
import cn.estsh.i3plus.pojo.mes.repository.MesProdMouldStatisticsRepository;
import cn.estsh.i3plus.pojo.mes.repository.MesProductionRecordRepository;
import cn.estsh.i3plus.pojo.mes.util.MesExtEnumUtil;
import cn.hutool.http.HttpRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
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.Objects;
import java.util.stream.Collectors;

/**
 * @Description : 生产开模统计
 * @Reference :
 * @Author : junsheng.li
 * @CreateDate 2024/6/26 16:32
 * @Modify:
 **/
@Service
@Slf4j
public class MesProdMouldStatisticsServiceImpl implements IMesProdMouldStatisticsService {

    @Autowired
    private IMesProdMouldStatisticsDao mesProdMouldStatisticsDao;

    @Autowired
    private IMesMouldMappingCfgRepository mesMouldMappingCfgRDao;

    @Autowired
    private MesProductionRecordRepository mesProductionRecordRDao;

    @Autowired
    private MesProdMouldRecordRepository mesProdMouldRecordRDao;

    @Autowired
    private MesProdMouldStatisticsRepository mesProdMouldStatisticsRDao;

    @Autowired
    private IConfigService configService;

    @Override
    public void doSumMesProdMouldStatistics(String organizeCode, Integer pageSize, String userName) {
        //查询未统计的开模记录数据
        List<MesProdMouldRecord> undStatisticsMesProdMouldRecordList = mesProdMouldStatisticsDao.findUndStatisticsMesProdMouldRecord(organizeCode, pageSize);
        if (CollectionUtils.isEmpty(undStatisticsMesProdMouldRecordList)) {
            return;
        }
        Map<String, List<MesProdMouldRecord>> undStatisticsMesProdMouldRecordMap = undStatisticsMesProdMouldRecordList.stream().collect(Collectors.groupingBy(MesProdMouldRecord::getEquipmentCode));
        //数据处理
        for (MesMouldMappingCfg mesMouldMappingCfg : getMesMouldMappingCfgs(organizeCode, new ArrayList<>(undStatisticsMesProdMouldRecordMap.keySet()))) {
            List<MesProdMouldRecord> mesProdMouldRecords = undStatisticsMesProdMouldRecordMap.get(mesMouldMappingCfg.getEquipmentCode());
            //更新开模记录数据
            mesProdMouldRecords.forEach(mesProdMouldRecord -> {
                mesProdMouldRecord.setAssetNum(mesMouldMappingCfg.getAssetNum());
                mesProdMouldRecord.setMeterName(mesMouldMappingCfg.getMeterName());
                mesProdMouldRecord.setSystemSyncStatus(CommonEnumUtil.FALSE);
                ConvertBean.serviceModelUpdate(mesProdMouldRecord, userName);
            });
            mesProdMouldRecordRDao.saveAll(mesProdMouldRecords);
            //生产开模统计
            saveMesProdMouldStatistics(organizeCode, userName, mesMouldMappingCfg, mesProdMouldRecords);
        }
        //更新加工记录表状态
        updateMesProductionRecord(organizeCode, userName, undStatisticsMesProdMouldRecordList.stream().map(MesProdMouldRecord::getId).collect(Collectors.toList()));
    }

    @Override
    public void doSendMesProdMouldStatistics(String organizeCode, String userName) {
        Map<String, MesConfig> mesConfigMap = getMesConfigMap(organizeCode);
        if (mesConfigMap == null) {
            return;
        }
        //发送URL
        String sendUrl = getConfigValue(mesConfigMap, MesPcnExtConstWords.SEND_URL);
        //发送data
        String sendData = getConfigValue(mesConfigMap, MesPcnExtConstWords.SEND_DATA);
        //发送item
        String sendItemData = getConfigValue(mesConfigMap, MesPcnExtConstWords.SEND_ITEM_DATA);
        if (Objects.isNull(sendUrl) || Objects.isNull(sendData) || Objects.isNull(sendItemData)) {
            return;
        }
        //查询未发送数据
        DdlPackBean packBean = DdlPackBean.getDdlPackBean(organizeCode);
        DdlPreparedPack.getNumEqualPack(CommonEnumUtil.FALSE, "systemSyncStatus", packBean);
        DdlPreparedPack.getStringSmallerNotEqualPack(TimeTool.getToday(), "createDatetime", packBean);
        DdlPreparedPack.getOrderBy("modifyDatetime", CommonEnumUtil.ASC_OR_DESC.ASC.getValue(), packBean);
        List<MesProdMouldStatistics> mesProdMouldStatisticsList = mesProdMouldStatisticsRDao.findByHqlWhere(packBean);
        if (CollectionUtils.isEmpty(mesProdMouldStatisticsList)) {
            log.info("不存在未发送的数据");
            return;
        }
        //发送数据
        StringBuilder itemData = new StringBuilder();
        for (MesProdMouldStatistics statistics : mesProdMouldStatisticsList) {
            String time = TimeTool.parseStringFormat(statistics.getCreateDatetime(), "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd'T'HH:mm:ss");
            itemData.append(String.format(sendItemData, statistics.getAssetNum(), statistics.getMeterName(), statistics.getQty(), time, statistics.getOrganizeCode()));
        }
        String body = HttpRequest.post(sendUrl).header("Content-Type", "text/xml").body(String.format(sendData, itemData)).execute().body();
        //发送成功更新同步状态
        mesProdMouldStatisticsList.forEach(t -> {
            if (!body.contains("messageID")) {
                t.setSystemSyncStatus(CommonEnumUtil.FALSE);
                t.setDescription(body);
            } else {
                t.setSystemSyncStatus(CommonEnumUtil.TRUE_OR_FALSE.TRUE.getValue());
            }
            ConvertBean.serviceModelUpdate(t, userName);
        });
        mesProdMouldStatisticsRDao.saveAll(mesProdMouldStatisticsList);

    }

    private void updateMesProductionRecord(String organizeCode, String userName, List<Long> idList) {
        //查询加工记录表
        List<MesProductionRecord> mesProductionRecordList = getProductionRecordList(organizeCode, idList);
        //更新加工记录表状态
        if (!CollectionUtils.isEmpty(mesProductionRecordList)) {
            List<Long> noUpdateSyncStatusId = mesProductionRecordList.stream().filter(t -> MesExtEnumUtil.REPORT_STATUS.REPORT_STATUS_10.getValue() == t.getReportStatus()).map(MesProductionRecord::getId).collect(Collectors.toList());
            List<Long> updateSyncStatusId = mesProductionRecordList.stream().filter(t -> MesExtEnumUtil.REPORT_STATUS.REPORT_STATUS_10.getValue() != t.getReportStatus()).map(MesProductionRecord::getId).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(noUpdateSyncStatusId)) {
                mesProdMouldStatisticsDao.updateMesProductionRecord(noUpdateSyncStatusId, organizeCode, false, userName);
            }
            if (!CollectionUtils.isEmpty(updateSyncStatusId)) {
                mesProdMouldStatisticsDao.updateMesProductionRecord(updateSyncStatusId, organizeCode, true, userName);
            }
        }
    }

    private void saveMesProdMouldStatistics(String organizeCode, String userName, MesMouldMappingCfg mesMouldMappingCfg, List<MesProdMouldRecord> mesProdMouldRecords) {
        Map<String, List<MesProdMouldRecord>> mesProdMouldRecordMap = mesProdMouldRecords.stream().collect(Collectors.groupingBy(t -> TimeTool.parseStringFormat(t.getCreateDatetime(), null, DateUtil.SHORT_FORMAT)));
        Map<String, MesProdMouldStatistics> mouldStatisticsMap = getMesProdMouldStatistics(organizeCode, mesMouldMappingCfg.getAssetNum(), mesMouldMappingCfg.getMeterName());
        for (Map.Entry<String, List<MesProdMouldRecord>> mesProdMouldRecordEntry : mesProdMouldRecordMap.entrySet()) {
            if (Objects.isNull(mouldStatisticsMap) || !mouldStatisticsMap.containsKey(mesProdMouldRecordEntry.getKey())) {
                MesProdMouldStatistics mesProdMouldStatistic = new MesProdMouldStatistics();
                mesProdMouldStatistic.setWorkDate(mesProdMouldRecordEntry.getKey());
                mesProdMouldStatistic.setAssetNum(mesMouldMappingCfg.getAssetNum());
                mesProdMouldStatistic.setMeterName(mesMouldMappingCfg.getMeterName());
                mesProdMouldStatistic.setQty(mesProdMouldRecordEntry.getValue().size());
                mesProdMouldStatistic.setOrganizeCode(organizeCode);
                ConvertBean.serviceModelInitialize(mesProdMouldStatistic, userName);
                mesProdMouldStatisticsRDao.insert(mesProdMouldStatistic);
            } else {
                MesProdMouldStatistics prodMouldStatistics = mouldStatisticsMap.get(mesProdMouldRecordEntry.getKey());
                prodMouldStatistics.setQty(prodMouldStatistics.getQty() + mesProdMouldRecordEntry.getValue().size());
                prodMouldStatistics.setSystemSyncStatus(CommonEnumUtil.FALSE);
                ConvertBean.serviceModelUpdate(prodMouldStatistics, userName);
                mesProdMouldStatisticsRDao.update(prodMouldStatistics);
            }
        }
    }

    private Map<String, MesProdMouldStatistics> getMesProdMouldStatistics(String organizeCode, String assetNum, String meterName) {
        DdlPackBean packBean = DdlPackBean.getDdlPackBean(organizeCode);
        DdlPreparedPack.getStringEqualPack(assetNum, "assetNum", packBean);
        DdlPreparedPack.getStringEqualPack(meterName, "meterName", packBean);
        List<MesProdMouldStatistics> mesProdMouldStatistics = mesProdMouldStatisticsRDao.findByHqlWhere(packBean);
        if (!CollectionUtils.isEmpty(mesProdMouldStatistics)) {
            return mesProdMouldStatistics.stream().collect(Collectors.toMap(MesProdMouldStatistics::getWorkDate, t -> t));
        }
        return null;
    }

    private List<MesMouldMappingCfg> getMesMouldMappingCfgs(String organizeCode, List<String> equipmentCodeList) {
        DdlPackBean packBean = DdlPackBean.getDdlPackBean(organizeCode);
        DdlPreparedPack.getInPackList(equipmentCodeList, "equipmentCode", packBean);
        return mesMouldMappingCfgRDao.findByHqlWhere(packBean);
    }

    private List<MesProductionRecord> getProductionRecordList(String organizeCode, List<Long> idList) {
        DdlPackBean packBean = DdlPackBean.getDdlPackBean(organizeCode);
        DdlPreparedPack.getInPackList(idList, "mouldRecordId", packBean);
        return mesProductionRecordRDao.findByHqlWhere(packBean);
    }

    private String getConfigValue(Map<String, MesConfig> mesConfigMap, String key) {
        MesConfig mesConfig = mesConfigMap.get(key);
        if (Objects.isNull(mesConfig) || StringUtils.isEmpty(mesConfig.getCfgValue())) {
            log.info("参数【{}】未维护", key);
            return null;
        }
        return mesConfig.getCfgValue();
    }

    private Map<String, MesConfig> getMesConfigMap(String organizeCode) {
        List<MesConfig> mesConfigList = configService.findMesConfigByCfgCode(MesPcnExtConstWords.SEND_MES_PROD_MOULD_STATISTICS, organizeCode);
        if (CollectionUtils.isEmpty(mesConfigList)) {
            log.info("发送开模统计参数【{}】未维护", MesPcnExtConstWords.SEND_MES_PROD_MOULD_STATISTICS);
            return null;
        }
        return mesConfigList.stream().collect(Collectors.toMap(MesConfig::getCfgKey, t -> t));
    }
}
