package com.xisc.pm.app.service.validator;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xisc.pm.app.service.PmPdTmpYieldBtService;
import com.xisc.pm.domain.entity.PmPdTmpYieldBt;
import com.xisc.pm.domain.repository.PmPdTmpYieldBtRepository;
import com.xisc.pm.infra.util.Utils;
import io.choerodon.core.exception.CommonException;
import io.choerodon.core.oauth.DetailsHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.hzero.boot.imported.app.service.BatchValidatorHandler;
import org.hzero.boot.imported.infra.validator.annotation.ImportValidator;
import org.hzero.boot.imported.infra.validator.annotation.ImportValidators;
import org.hzero.core.message.MessageAccessor;
import org.hzero.mybatis.domian.Condition;
import org.hzero.mybatis.util.Sqls;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 纪文桃 wentao.ji01@hand-china.com
 * @since 2024/7/26 9:39
 */

@Slf4j
@ImportValidators({@ImportValidator(templateCode = "PM.PD_TMP_YIELD_BT")})
public class PmPdTmpYieldBtValidator extends BatchValidatorHandler {

    private final ObjectMapper objectMapper;

    private final PmPdTmpYieldBtRepository pmPdTmpYieldBtRepository;

    private final PmPdTmpYieldBtService pmPdTmpYieldBtService;

    public PmPdTmpYieldBtValidator(ObjectMapper objectMapper, PmPdTmpYieldBtRepository pmPdTmpYieldBtRepository, PmPdTmpYieldBtService pmPdTmpYieldBtService) {
        this.objectMapper = objectMapper;
        this.pmPdTmpYieldBtRepository = pmPdTmpYieldBtRepository;
        this.pmPdTmpYieldBtService = pmPdTmpYieldBtService;
    }


    @Override
    public boolean validate(List<String> data) {
        if (CollectionUtils.isEmpty(data)) {
            throw new CommonException("pm.import_data_is_empty_list");
        }
        boolean flag = true;
        Long tenantId = 0L;
        if (DetailsHelper.getUserDetails() != null && DetailsHelper.getUserDetails().getTenantId() != null) {
            tenantId = DetailsHelper.getUserDetails().getTenantId();
        }
        List<PmPdTmpYieldBt> list = new ArrayList<>(data.size());
        Map<PmPdTmpYieldBt, Integer> idxMap = new HashMap<>(data.size());

        for (int i = 0; i < data.size(); i++) {
            try {
                // 转换对象
                PmPdTmpYieldBt pmPdTmpYieldBt = objectMapper.readValue(data.get(i), PmPdTmpYieldBt.class);
                pmPdTmpYieldBt.setTenantId(tenantId);

                Integer integer = idxMap.putIfAbsent(pmPdTmpYieldBt, i);
                if (integer != null && integer != i) {
                    // 重复数据
                    addErrorMsg(i, MessageAccessor.getMessage("pm.exist_same_data").getDesc());
                    continue;
                }

                list.add(pmPdTmpYieldBt);
            } catch (JsonProcessingException e) {
                log.error(e.getMessage(), e);
            }
        }

        // 如果集合为空，则结束
        if (CollectionUtils.isEmpty(list)) {
            return flag;
        }

        // 新增记录之间校验区间是否交叉
        Map<String, List<PmPdTmpYieldBt>> plateFromMap = list.stream().collect(Collectors.groupingBy(pmPdTmpYieldBtService::getTmpKey));
        for (Map.Entry<String, List<PmPdTmpYieldBt>> entry : plateFromMap.entrySet()) {
            List<PmPdTmpYieldBt> pdTmpYieldBtList = entry.getValue();
            for (int i = 0; i < pdTmpYieldBtList.size() - 1; i++) {
                for (int j = i + 1; j < pdTmpYieldBtList.size(); j++) {
                    // 校验钢板厚度区间是否交叉
                    boolean plateThickIntervalCheck = Utils.isIntersect(pdTmpYieldBtList.get(i).getPlateThickFrom(), pdTmpYieldBtList.get(i).getPlateThickTo(),
                            pdTmpYieldBtList.get(j).getPlateThickFrom(), pdTmpYieldBtList.get(j).getPlateThickTo());
                    if (!plateThickIntervalCheck) {
                        continue;
                    }
                    // 校验板坯厚度区间是否交叉
                    boolean normalCutLenIntervalCheck = Utils.isIntersect(pdTmpYieldBtList.get(i).getSlabThickFrom(), pdTmpYieldBtList.get(i).getSlabThickTo(),
                            pdTmpYieldBtList.get(j).getSlabThickFrom(), pdTmpYieldBtList.get(j).getSlabThickTo());
                    if (!normalCutLenIntervalCheck) {
                        continue;
                    }

                    // 校验板坯宽度区间是否交叉
                    boolean qtCutLenIntervalCheck = Utils.isIntersect(pdTmpYieldBtList.get(i).getSlabWidthFrom(), pdTmpYieldBtList.get(i).getSlabWidthTo(),
                            pdTmpYieldBtList.get(j).getSlabWidthFrom(), pdTmpYieldBtList.get(j).getSlabWidthTo());
                    if (!qtCutLenIntervalCheck) {
                        continue;
                    }

                    addErrorMsg(idxMap.get(pdTmpYieldBtList.get(i)),MessageAccessor.getMessage("pm.cut_place_bt_005",
                            new Object[]{ pdTmpYieldBtList.get(j).getSlabThickFrom(), pdTmpYieldBtList.get(j).getSlabThickTo(),
                                    pdTmpYieldBtList.get(j).getSlabWidthFrom(), pdTmpYieldBtList.get(j).getSlabWidthTo(),
                                    pdTmpYieldBtList.get(j).getPlateThickFrom(), pdTmpYieldBtList.get(j).getPlateThickTo()}).getDesc());
                    flag = false;
                }
            }
        }

        // 与数据库记录校验区间是否交叉
        List<String> ccTypeList = list.stream().map(PmPdTmpYieldBt::getCcType).distinct().collect(Collectors.toList());
        List<String> pdProdCodeHpList = list.stream().map(PmPdTmpYieldBt::getProdCodeHp).distinct().collect(Collectors.toList());
        List<String> withSideFlagList = list.stream().map(PmPdTmpYieldBt::getWithSideFlag).distinct().collect(Collectors.toList());
        List<String> rollineNoList = list.stream().map(PmPdTmpYieldBt::getRollLineNo).distinct().collect(Collectors.toList());
        List<Long> idList = list.stream().filter(item -> item.getPptybId() != null).map(PmPdTmpYieldBt::getPptybId).collect(Collectors.toList());
        List<PmPdTmpYieldBt> existPmPdTmpYieldBtList = pmPdTmpYieldBtRepository.selectByCondition(Condition.builder(PmPdTmpYieldBt.class)
                .andWhere(Sqls.custom().andIn(PmPdTmpYieldBt.FIELD_CC_TYPE, ccTypeList))
                .andWhere(Sqls.custom().andIn(PmPdTmpYieldBt.FIELD_PROD_CODE_HP, pdProdCodeHpList))
                .andWhere(Sqls.custom().andIn(PmPdTmpYieldBt.FIELD_WITH_SIDE_FLAG, withSideFlagList))
                .andWhere(Sqls.custom().andIn(PmPdTmpYieldBt.FIELD_ROLL_LINE_NO, rollineNoList))
                .andWhere(Sqls.custom().andEqualTo(PmPdTmpYieldBt.FIELD_TENANT_ID, tenantId))
                .andWhere(Sqls.custom().andNotIn(PmPdTmpYieldBt.FIELD_PPTYB_ID, idList, true))
                .build());
        if (CollectionUtils.isNotEmpty(existPmPdTmpYieldBtList)) {
            Map<String, List<PmPdTmpYieldBt>> existMap = existPmPdTmpYieldBtList.stream().collect(Collectors.groupingBy(pmPdTmpYieldBtService::getTmpKey));
            for (int i = 0; i < list.size() ; i++) {
                if (existMap.containsKey(pmPdTmpYieldBtService.getTmpKey(list.get(i)))) {
                    List<PmPdTmpYieldBt> existYieldBtList = existMap.get(pmPdTmpYieldBtService.getTmpKey(list.get(i)));
                    for (PmPdTmpYieldBt pdTmpYieldBt : existYieldBtList) {
                        // 校验钢板厚度区间是否交叉
                        boolean plateThickIntervalCheck = Utils.isIntersect(list.get(i).getPlateThickFrom(), list.get(i).getPlateThickTo(),
                                pdTmpYieldBt.getPlateThickFrom(), pdTmpYieldBt.getPlateThickTo());
                        if (!plateThickIntervalCheck) {
                            continue;
                        }
                        // 校验板坯厚度区间是否交叉
                        boolean normalCutLenIntervalCheck = Utils.isIntersect(list.get(i).getSlabThickFrom(), list.get(i).getSlabThickTo(),
                                pdTmpYieldBt.getSlabThickFrom(), pdTmpYieldBt.getSlabThickTo());
                        if (!normalCutLenIntervalCheck) {
                            continue;
                        }

                        // 校验板坯宽度区间是否交叉
                        boolean qtCutLenIntervalCheck = Utils.isIntersect(list.get(i).getSlabWidthFrom(), list.get(i).getSlabWidthTo(),
                                pdTmpYieldBt.getSlabWidthFrom(), pdTmpYieldBt.getSlabWidthTo());
                        if (!qtCutLenIntervalCheck) {
                            continue;
                        }

                        addErrorMsg(i, MessageAccessor.getMessage("pm.cut_place_bt_002",
                                new Object[]{   pdTmpYieldBt.getSlabThickFrom(), pdTmpYieldBt.getSlabThickTo(),
                                        pdTmpYieldBt.getSlabWidthFrom(), pdTmpYieldBt.getSlabWidthTo(),
                                        pdTmpYieldBt.getPlateThickFrom(), pdTmpYieldBt.getPlateThickTo()}).getDesc());
                        flag = false;
                    }
                }
            }
        }
        return flag;
    }
}
