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.PmPlateCutLenBtService;
import com.xisc.pm.domain.entity.PmPlateCutLenBt;
import com.xisc.pm.domain.repository.PmPlateCutLenBtRepository;
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:13
 */
@Slf4j
@ImportValidators({@ImportValidator(templateCode = "PM.PLATE_CUT_LEN_BT")})
public class PmPlateCutLenBtValidator extends BatchValidatorHandler {

    private final ObjectMapper objectMapper;

    private final PmPlateCutLenBtRepository pmPlateCutLenBtRepository;

    private final PmPlateCutLenBtService pmPlateCutLenBtService;

    public PmPlateCutLenBtValidator(ObjectMapper objectMapper, PmPlateCutLenBtRepository pmPlateCutLenBtRepository, PmPlateCutLenBtService pmPlateCutLenBtService) {
        this.objectMapper = objectMapper;
        this.pmPlateCutLenBtRepository = pmPlateCutLenBtRepository;
        this.pmPlateCutLenBtService = pmPlateCutLenBtService;
    }


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

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

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

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

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

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

                    // 校验组合板宽度区间是否交叉
                    boolean combinePlateWidthIntervalCheck = Utils.isIntersect(plateCutValueList.get(i).getCombinePlateWidthFrom(),
                            plateCutValueList.get(i).getCombinePlateWidthTo(), plateCutValueList.get(j).getCombinePlateWidthFrom(),
                            plateCutValueList.get(j).getCombinePlateWidthTo());
                    if (!combinePlateWidthIntervalCheck) {
                        continue;
                    }

                    // 校验板坯厚度起止区间是否交叉
                    boolean slabThickIntervalCheck = Utils.isIntersect(plateCutValueList.get(i).getSlabThickFrom(),
                            plateCutValueList.get(i).getSlabThickTo(), plateCutValueList.get(j).getSlabThickFrom(),
                            plateCutValueList.get(j).getSlabThickTo());
                    if (!slabThickIntervalCheck) {
                        continue;
                    }

                    addErrorMsg(idxMap.get(plateCutValueList.get(i)), MessageAccessor.getMessage("pm.thick_addv_bt_005",
                            new Object[]{plateCutValueList.get(j).getPlateThickFrom(), plateCutValueList.get(j).getPlateThickTo(),
                                    plateCutValueList.get(j).getCombinePlateWidthFrom(), plateCutValueList.get(j).getCombinePlateWidthTo(),
                                    plateCutValueList.get(j).getSlabThickFrom(), plateCutValueList.get(j).getSlabThickTo()}).getDesc());
                    flag = false;
                }
            }
        }

        // 获取字段集合，查询数据库该范围内数据
        List<String> brrNeedList = list.stream().map(PmPlateCutLenBt::getBrrNeed).distinct().collect(Collectors.toList());
        List<String> rollModeList = list.stream().map(PmPlateCutLenBt::getRollMode).distinct().collect(Collectors.toList());
        List<String> rollDirectCodeList = list.stream().map(PmPlateCutLenBt::getRollDirectCode).distinct().collect(Collectors.toList());
        List<String> rollLineNoList = list.stream().map(PmPlateCutLenBt::getMscLineNo).distinct().collect(Collectors.toList());
        List<Long> idList = list.stream().filter(item -> item.getPpclbId() != null).map(PmPlateCutLenBt::getPpclbId).collect(Collectors.toList());
        // 根据提取的条件查询数据库中已存在的PmPlateCutLenBt记录
        List<PmPlateCutLenBt> existPmPlateCutLenBtList = pmPlateCutLenBtRepository.selectByCondition(Condition.builder(PmPlateCutLenBt.class)
                .andWhere(Sqls.custom().andEqualTo(PmPlateCutLenBt.FIELD_TENANT_ID, tenantId))
                .andWhere(Sqls.custom().andIn(PmPlateCutLenBt.FIELD_BRR_NEED, brrNeedList))
                .andWhere(Sqls.custom().andIn(PmPlateCutLenBt.FIELD_ROLL_MODE, rollModeList))
                .andWhere(Sqls.custom().andIn(PmPlateCutLenBt.FIELD_ROLL_DIRECT_CODE, rollDirectCodeList))
                .andWhere(Sqls.custom().andIn(PmPlateCutLenBt.FIELD_MSC_LINE_NO, rollLineNoList))
                .andWhere(Sqls.custom().andNotIn(PmPlateCutLenBt.FIELD_PPCLB_ID, idList, true))
                .build());
        // 与数据库记录校验区间是否交叉
        if (org.apache.commons.collections.CollectionUtils.isNotEmpty(existPmPlateCutLenBtList)) {
            Map<String, List<PmPlateCutLenBt>> existPlateFromMap = existPmPlateCutLenBtList.stream()
                    .collect(Collectors.groupingBy(pmPlateCutLenBtService::getPlateFromKey));
            for (int i = 0; i < list.size(); i++) {
                if (existPlateFromMap.containsKey(pmPlateCutLenBtService.getPlateFromKey(list.get(i)))) {
                    List<PmPlateCutLenBt> existCutLenBtList = existPlateFromMap.get(pmPlateCutLenBtService.getPlateFromKey(list.get(i)));
                    for (PmPlateCutLenBt plateCutLenBt : existCutLenBtList) {
                        // 校验钢板厚度区间是否交叉
                        boolean plateThickIntervalCheck = Utils.isIntersect(list.get(i).getPlateThickFrom(), list.get(i).getPlateThickTo(),
                                plateCutLenBt.getPlateThickFrom(), plateCutLenBt.getPlateThickTo());
                        if (!plateThickIntervalCheck) {
                            continue;
                        }

                        // 校验组合板宽度区间是否交叉
                        boolean combinePlateWidthIntervalCheck = Utils.isIntersect(list.get(i).getCombinePlateWidthFrom(),
                                list.get(i).getCombinePlateWidthTo(),
                                plateCutLenBt.getCombinePlateWidthFrom(), plateCutLenBt.getCombinePlateWidthTo());
                        if (!combinePlateWidthIntervalCheck) {
                            continue;
                        }

                        // 校验板坯厚度起止区间是否交叉
                        boolean slabThickIntervalCheck = Utils.isIntersect(list.get(i).getSlabThickFrom(),
                                list.get(i).getSlabThickTo(), plateCutLenBt.getSlabThickFrom(),
                                plateCutLenBt.getSlabThickTo());
                        if (!slabThickIntervalCheck) {
                            continue;
                        }

                        addErrorMsg(i, MessageAccessor.getMessage("pm.thick_addv_bt_006",
                                new Object[]{ plateCutLenBt.getPlateThickFrom(), plateCutLenBt.getPlateThickTo(),
                                        plateCutLenBt.getCombinePlateWidthFrom(), plateCutLenBt.getCombinePlateWidthTo(),
                                        plateCutLenBt.getSlabThickFrom(), plateCutLenBt.getSlabThickTo()}).getDesc());
                        flag = false;
                    }
                }
            }
        }

        return flag;
    }
}
