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

import cn.estsh.i3plus.ext.mes.api.base.bu.IBusiConfigService;
import cn.estsh.i3plus.ext.mes.api.busi.bu3.ISxProdDataPushNotifyStrategyFlagService;
import cn.estsh.i3plus.ext.mes.api.busi.bu3.ISxProdDataPushNotifyStrategyService;
import cn.estsh.i3plus.ext.mes.pojo.bean.MesAssistOutAndEnter;
import cn.estsh.i3plus.ext.mes.pojo.model.bu3.SxAssistOutAndEnterModel;
import cn.estsh.i3plus.ext.mes.pojo.model.bu3.SxPushDataNotifyParamAssistModel;
import cn.estsh.i3plus.ext.mes.pojo.repository.MesAssistOutAndEnterRepository;
import cn.estsh.i3plus.ext.mes.pojo.sqlpack.MesExtHqlPack;
import cn.estsh.i3plus.ext.mes.pojo.util.MesExtConstWords;
import cn.estsh.i3plus.ext.mes.pojo.util.MesExtEnumUtil;
import cn.estsh.i3plus.platform.common.tool.TimeTool;
import cn.estsh.i3plus.pojo.model.platform.PushDataNotifyModel;
import cn.estsh.impp.framework.boot.util.SpringContextsUtil;
import com.alibaba.fastjson.JSONObject;
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 javax.persistence.EntityManager;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

import java.util.*;

/**
 * @Description 援入援出选择器
 * @author jiaqi.hou
 * @date 2023-08-16 14:27
 **/
@Slf4j
@Service
public class SxProdDataPushNotifyStrategyAssistNewSwitchService implements ISxProdDataPushNotifyStrategyService {

    @Autowired
    private MesAssistOutAndEnterRepository assistOutAndEnterRepository;

    @Autowired
    private IBusiConfigService busiConfigService;

    @Override
    public List<PushDataNotifyModel> exec(PushDataNotifyModel data) {

        log.info("援入援出选择器 --- SxProdDataPushNotifyStrategyAssistNewSwitchService --- START --- DATA:{} --- THREAD:{}", JSONObject.toJSONString(data), Thread.currentThread().getName());

        SxPushDataNotifyParamAssistModel pushParam = analysisParam(data);

        SxAssistOutAndEnterModel queryParams = new SxAssistOutAndEnterModel(pushParam.getInfluenceDateStart(), pushParam.getInfluenceDateEnd()).organizeCode(pushParam.getOrganizeCode());

        if (pushParam.getFlag().equals(MesExtEnumUtil.PROD_DATA_PUSH_NOTIFY_STRATEGY_FLAG.NINE.getFlag())
                || pushParam.getFlag().equals(MesExtEnumUtil.PROD_DATA_PUSH_NOTIFY_STRATEGY_FLAG.TEN.getFlag()))
            queryParams.setConfirm(false);

        log.info("援入援出选择器 --- SxProdDataPushNotifyStrategyAssistNewSwitchService --- queryParams:{} --- THREAD:{}", JSONObject.toJSONString(queryParams), Thread.currentThread().getName());
        List<MesAssistOutAndEnter> dataList = assistOutAndEnterRepository.findByHqlWhere(MesExtHqlPack.getAssistOutAndEnter(queryParams,false));

        if (CollectionUtils.isEmpty(dataList)) return null;

        dataList = convertOwnerDepartmentToOwnerDepartmentName(queryParams, dataList);
        log.info("援入援出选择器 --- SxProdDataPushNotifyStrategyAssistNewSwitchService --- dataList.size:{} --- THREAD:{}", dataList.size(), Thread.currentThread().getName());

        ISxProdDataPushNotifyStrategyFlagService strategyFlagService = (ISxProdDataPushNotifyStrategyFlagService) SpringContextsUtil.getBean(MesExtEnumUtil.PROD_DATA_PUSH_NOTIFY_STRATEGY_FLAG.flagOfClazz(pushParam.getFlag()));

        log.info("援入援出选择器 --- SxProdDataPushNotifyStrategyAssistNewSwitchService --- END --- THREAD:{}", Thread.currentThread().getName());

        List<PushDataNotifyModel> resultList = (List<PushDataNotifyModel>) strategyFlagService.exec(data, pushParam, dataList);
        if (!CollectionUtils.isEmpty(resultList) && !CollectionUtils.isEmpty(resultList.get(MesExtConstWords.ZERO).getListDing())){
            LinkedHashMap<String, String> dataMap;
            for (PushDataNotifyModel model : resultList) {
                dataMap = new LinkedHashMap<>();
                dataMap.put("详情内容可在SFP管理端MES模块【援入援出明细记录】页面查看","TITLE");
                model.addListDing(dataMap);
            }
        }
        return resultList;
    }

    private List<MesAssistOutAndEnter> convertOwnerDepartmentToOwnerDepartmentName(SxAssistOutAndEnterModel queryParams, List<MesAssistOutAndEnter> dataList) {
        List<MesAssistOutAndEnter> resultList = new ArrayList<>();
        MesAssistOutAndEnter outAndEnter;
        Map<String, String> ownerDepartmentMap = busiConfigService.getConfigMap(queryParams.getOrganizeCode(), MesExtConstWords.OWNER_DEPARTMENT_CFG);
        if (ownerDepartmentMap!=null){
            for (MesAssistOutAndEnter enter : dataList) {
                if (ownerDepartmentMap.containsKey(enter.getOwnerDepartment())) {
                    outAndEnter = new MesAssistOutAndEnter();
                    BeanUtils.copyProperties(enter,outAndEnter,"id");
                    outAndEnter.setOwnerDepartment(ownerDepartmentMap.get(enter.getOwnerDepartment()));
                    resultList.add(outAndEnter);
                }
            }
        }
        return resultList;
    }

    private SxPushDataNotifyParamAssistModel analysisParam(PushDataNotifyModel data) {

        SxPushDataNotifyParamAssistModel pushParam = JSONObject.parseObject(data.getPushParam(), SxPushDataNotifyParamAssistModel.class);

        if (StringUtils.isEmpty(data.getApiParam())) return restockParamDate(pushParam);

        SxPushDataNotifyParamAssistModel apiParam = JSONObject.parseObject(data.getApiParam(), SxPushDataNotifyParamAssistModel.class);

        return restockParamDate(pushParam.influenceDateStart(apiParam.getInfluenceDateStart()).influenceDateEnd(apiParam.getInfluenceDateEnd()));

    }

    private SxPushDataNotifyParamAssistModel restockParamDate(SxPushDataNotifyParamAssistModel pushParam) {
        // 根据flag判断获取上月数据还是本月数据
        // flag = (7、8、11、12) 上月
        // flag = (9、10) 本月
        switch (pushParam.getFlag()){
            case "7" :
            case "8" :
            case "11" :
            case "12" :
                pushParam.influenceDateStart(StringUtils.isEmpty(pushParam.getInfluenceDateStart()) ?  getLastMonthFirstDay(): pushParam.getInfluenceDateStart())
                        .influenceDateEnd(StringUtils.isEmpty(pushParam.getInfluenceDateEnd()) ?  getCurrentMonthFirstDay(): pushParam.getInfluenceDateEnd());
                break;
            case "9" :
            case "10" :
                pushParam.influenceDateStart(StringUtils.isEmpty(pushParam.getInfluenceDateStart()) ?  getCurrentMonthFirstDay(): pushParam.getInfluenceDateStart())
                        .influenceDateEnd(StringUtils.isEmpty(pushParam.getInfluenceDateEnd()) ?  getCurrentMonthLastDay(): pushParam.getInfluenceDateEnd());
                break;
            default:
                //默认查本月
                pushParam.influenceDateStart(getCurrentMonthFirstDay()).influenceDateEnd(getCurrentMonthLastDay());
        }
        pushParam.influenceDate(pushParam.getInfluenceDateStart().substring(0, 7));
        return pushParam;
    }

    public static String getLastMonthFirstDay() {
        LocalDate today = LocalDate.now();
        LocalDate lastMonth = today.minusMonths(1);
        LocalDate firstDay = lastMonth.withDayOfMonth(1);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        return firstDay.format(formatter);
    }

    public static String getCurrentMonthFirstDay() {
        LocalDate today = LocalDate.now();
        LocalDate firstDay = today.withDayOfMonth(1);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        return firstDay.format(formatter);
    }

    public static String getCurrentMonthLastDay() {
        LocalDate today = LocalDate.now();
        int lastDayOfMonth = today.lengthOfMonth();
        LocalDate lastDay = today.withDayOfMonth(lastDayOfMonth);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        return lastDay.format(formatter);
    }
}
