package com.xisc.pm.infra.job;

import com.xisc.pm.app.service.PmMeterJobService;
import com.xisc.pm.domain.entity.PmSteelCastFlowItf;
import com.xisc.pm.domain.entity.PmSteelCastHeatItf;
import com.xisc.pm.domain.entity.PmSteelCastLotItf;
import com.xisc.pm.domain.entity.PmSteelCastSlab;
import com.xisc.pm.domain.entity.PmSteelCastSlabItf;
import com.xisc.pm.domain.repository.PmSteelCastFlowItfRepository;
import com.xisc.pm.domain.repository.PmSteelCastHeatItfRepository;
import com.xisc.pm.domain.repository.PmSteelCastLotItfRepository;
import com.xisc.pm.domain.repository.PmSteelCastSlabItfRepository;
import com.xisc.pm.infra.constant.Constants;
import com.xisc.pm.infra.util.DateUtils;
import io.choerodon.core.oauth.CustomUserDetails;
import io.choerodon.core.oauth.DetailsHelper;
import org.apache.commons.collections.CollectionUtils;
import org.hzero.boot.scheduler.infra.annotation.JobHandler;
import org.hzero.boot.scheduler.infra.enums.ReturnT;
import org.hzero.boot.scheduler.infra.handler.IJobHandler;
import org.hzero.boot.scheduler.infra.tool.SchedulerTool;
import org.hzero.mybatis.domian.Condition;
import org.hzero.mybatis.util.Sqls;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 三米八/五米线棒MES电文
 *
 * @author 纪文桃 wentao.ji01@hand-china.com
 * @date 2024/11/4 8:57
 * @description
 */
@JobHandler("ThreeMeterEightJobHander")
public class ThreeMeterEightJobHander implements IJobHandler {

    @Autowired
    private PmSteelCastHeatItfRepository pmSteelCastHeatItfRepository;

    @Autowired
    private PmSteelCastLotItfRepository pmSteelCastLotItfRepository;

    @Autowired
    private PmSteelCastFlowItfRepository pmSteelCastFlowItfRepository;

    @Autowired
    private PmSteelCastSlabItfRepository pmSteelCastSlabItfRepository;


    @Autowired
    private PmMeterJobService pmMeterJobService;

    private static final String TENANT_ID = "tenantId";

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ReturnT execute(Map<String, String> map, SchedulerTool tool) {
        // 校验
        Long tenantId;
        try {
            tenantId = Long.parseLong(map.get(TENANT_ID));
        } catch (Exception e) {
            tool.info("=====参数有误: 请维护租户ID,且只能维护整数类型, 不执行本次任务=====");
            return ReturnT.FAILURE;
        }

        CustomUserDetails userDetails = DetailsHelper.getUserDetails();
        userDetails.setTenantId(tenantId);
        userDetails.setOrganizationId(tenantId);
        userDetails.setTenantIds(Arrays.asList(tenantId));
        DetailsHelper.setCustomUserDetails(userDetails);

        List<PmSteelCastSlabItf> allPmSteelCastSlabItfList = pmSteelCastSlabItfRepository.selectByCondition(Condition.builder(PmSteelCastSlabItf.class)
                .andWhere(Sqls.custom().andEqualTo(PmSteelCastSlabItf.FIELD_ITF_STATUS, Constants.ItfStatus.N))
                .andWhere(Sqls.custom().andEqualTo(PmSteelCastSlabItf.FIELD_MAIN_BACKLOG_CODE, Constants.MainBacklogCode.CODE_A))
                .andWhere(Sqls.custom().andEqualTo(PmSteelCastSlabItf.FIELD_TENANT_ID, tenantId))
                .orderByAsc(PmSteelCastSlab.FIELD_CREATION_DATE).build());
        if (CollectionUtils.isEmpty(allPmSteelCastSlabItfList)) {
            tool.info("=====未查询到炼钢连铸制造命令板坯-接口表数据, 不执行本次任务=====");
            return ReturnT.FAILURE;
        }

        List<PmSteelCastLotItf> allPmSteelCastLotItfList = pmSteelCastLotItfRepository.selectByCondition(Condition.builder(PmSteelCastLotItf.class)
                .andWhere(Sqls.custom().andEqualTo(PmSteelCastLotItf.FIELD_ITF_STATUS, Constants.ItfStatus.N))
                .andWhere(Sqls.custom().andEqualTo(PmSteelCastLotItf.FIELD_MAIN_BACKLOG_CODE, Constants.MainBacklogCode.CODE_A))
                .andWhere(Sqls.custom().andEqualTo(PmSteelCastLotItf.FIELD_TENANT_ID, tenantId))
                .orderByAsc(PmSteelCastSlab.FIELD_CREATION_DATE)
                .build());
        if (CollectionUtils.isEmpty(allPmSteelCastLotItfList)) {
            tool.info("=====未查询到炼钢连铸制造命令LOT-接口表数据, 不执行本次任务=====");
            return ReturnT.FAILURE;
        }

        List<PmSteelCastHeatItf> allPmSteelCastHeatItfList = pmSteelCastHeatItfRepository.selectByCondition(Condition.builder(PmSteelCastHeatItf.class)
                .andWhere(Sqls.custom().andEqualTo(PmSteelCastHeatItf.FIELD_ITF_STATUS, Constants.ItfStatus.N))
                .andWhere(Sqls.custom().andEqualTo(PmSteelCastHeatItf.FIELD_MAIN_BACKLOG_CODE, Constants.MainBacklogCode.CODE_A))
                .orderByAsc(PmSteelCastSlab.FIELD_CREATION_DATE)
                .andWhere(Sqls.custom().andEqualTo(PmSteelCastHeatItf.FIELD_TENANT_ID, tenantId))
                .build());
        if (CollectionUtils.isEmpty(allPmSteelCastHeatItfList)) {
            tool.info("=====未查询到炼钢连铸制造命令炉次-接口表数据, 不执行本次任务=====");
            return ReturnT.FAILURE;
        }

        List<PmSteelCastFlowItf> allPmSteelCastFlowItfList = pmSteelCastFlowItfRepository.selectByCondition(Condition.builder(PmSteelCastFlowItf.class)
                .andWhere(Sqls.custom().andEqualTo(PmSteelCastFlowItf.FIELD_ITF_STATUS, Constants.ItfStatus.N))
                .andWhere(Sqls.custom().andEqualTo(PmSteelCastFlowItf.FIELD_MAIN_BACKLOG_CODE, Constants.MainBacklogCode.CODE_A))
                .orderByAsc(PmSteelCastSlab.FIELD_CREATION_DATE)
                .andWhere(Sqls.custom().andEqualTo(PmSteelCastFlowItf.FIELD_TENANT_ID, tenantId))
                .build());
        if (CollectionUtils.isEmpty(allPmSteelCastFlowItfList)) {
            tool.info("=====未查询到炼钢连铸制造命令铸机流-接口表数据, 不执行本次任务=====");
            return ReturnT.FAILURE;
        }

        // 过滤掉一天前的,默认失败
        Date yesEndOfDay = DateUtils.getYesterdayEndOfDay();
        List<PmSteelCastSlabItf> yesSteelCastSlabList = allPmSteelCastSlabItfList.stream().filter(item -> item.getCreationDate().compareTo(yesEndOfDay) <= 0).collect(Collectors.toList());
        List<PmSteelCastLotItf> yesSteelCastLotList =  allPmSteelCastLotItfList.stream().filter(item -> item.getCreationDate().compareTo(yesEndOfDay) <= 0).collect(Collectors.toList());
        List<PmSteelCastHeatItf> yesSteelCastHeatList = allPmSteelCastHeatItfList.stream().filter(item -> item.getCreationDate().compareTo(yesEndOfDay) <= 0).collect(Collectors.toList());
        List<PmSteelCastFlowItf> yesSteelCastFlowList = allPmSteelCastFlowItfList.stream().filter(item -> item.getCreationDate().compareTo(yesEndOfDay) <= 0).collect(Collectors.toList());
        pmMeterJobService.updateItfToProcess(yesSteelCastSlabList, yesSteelCastLotList, yesSteelCastHeatList, yesSteelCastFlowList, Constants.ItfStatus.E,"一天之前数据默认失败");

        // 获取今天的数据，令接口表数据状态（ITF_STATUS）的值为“P”，表示数据正在处理中
        List<PmSteelCastSlabItf> pmSteelCastSlabItfList = allPmSteelCastSlabItfList.stream().filter(item -> item.getCreationDate().after(yesEndOfDay)).collect(Collectors.toList());
        List<PmSteelCastLotItf> pmSteelCastLotItfList =  allPmSteelCastLotItfList.stream().filter(item -> item.getCreationDate().after(yesEndOfDay)).collect(Collectors.toList());
        List<PmSteelCastHeatItf> pmSteelCastHeatItfList = allPmSteelCastHeatItfList.stream().filter(item -> item.getCreationDate().after(yesEndOfDay)).collect(Collectors.toList());
        List<PmSteelCastFlowItf> pmSteelCastFlowItfList = allPmSteelCastFlowItfList.stream().filter(item -> item.getCreationDate().after(yesEndOfDay)).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(pmSteelCastSlabItfList)) {
            tool.info("=====未获取到今天的炼钢连铸制造命令板坯-接口表数据, 不执行本次任务=====");
            return ReturnT.FAILURE;
        }
        if (CollectionUtils.isEmpty(pmSteelCastLotItfList)) {
            tool.info("=====未获取到今天的炼钢连铸制造命令LOT-接口表数据, 不执行本次任务=====");
            return ReturnT.FAILURE;
        }
        if (CollectionUtils.isEmpty(pmSteelCastHeatItfList)) {
            tool.info("=====未获取到今天的炼钢连铸制造命令炉次-接口表数据, 不执行本次任务=====");
            return ReturnT.FAILURE;
        }
        if (CollectionUtils.isEmpty(pmSteelCastFlowItfList)) {
            tool.info("=====未获取到今天的炼钢连铸制造命令铸机流-接口表数据, 不执行本次任务=====");
            return ReturnT.FAILURE;
        }
        // 更改状态为P
        pmMeterJobService.updateItfToProcess(pmSteelCastSlabItfList, pmSteelCastLotItfList, pmSteelCastHeatItfList, pmSteelCastFlowItfList, Constants.ItfStatus.P, null);

        try {
            // 同步业务表并下达
            pmMeterJobService.syncToSteelCast(pmSteelCastSlabItfList, pmSteelCastLotItfList, pmSteelCastHeatItfList, pmSteelCastFlowItfList, tenantId);
            tool.info("===程序执行成功===");
        }catch (Exception e) {
            // 更新状态为E
            pmMeterJobService.updateItfToProcess(pmSteelCastSlabItfList, pmSteelCastLotItfList, pmSteelCastHeatItfList, pmSteelCastFlowItfList,
                    Constants.ItfStatus.E, e.getMessage());
            tool.info("===程序执行失败===");
        }
        return ReturnT.SUCCESS;
    }
}
