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.PmPlateSpecBtService;
import com.xisc.pm.domain.entity.PmPlateSpecBt;
import com.xisc.pm.domain.repository.PmPlateSpecBtRepository;
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 8:50
 */
@Slf4j
@ImportValidators({@ImportValidator(templateCode = "PM.PLATE_SPEC_BT")})
public class PmPlateSpecBtValidator extends BatchValidatorHandler {

    private final ObjectMapper objectMapper;

    private final PmPlateSpecBtRepository pmPlateSpecBtRepository;

    private final PmPlateSpecBtService pmPlateSpecBtService;

    public PmPlateSpecBtValidator(ObjectMapper objectMapper, PmPlateSpecBtRepository pmPlateSpecBtRepository, PmPlateSpecBtService pmPlateSpecBtService) {
        this.objectMapper = objectMapper;
        this.pmPlateSpecBtRepository = pmPlateSpecBtRepository;
        this.pmPlateSpecBtService = pmPlateSpecBtService;
    }


    @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<PmPlateSpecBt> list = new ArrayList<>(data.size());
        Map<PmPlateSpecBt, Integer> idxMap = new HashMap<>(data.size());

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

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

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

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

        for (int i = 0; i < list.size(); i++) {
            //单条记录中，“钢板厚度起”必须小于“钢板厚度止”；
            if (list.get(i).getPlateThickFrom().compareTo(list.get(i).getPlateThickTo()) >= 0) {
                addErrorMsg(i, MessageAccessor.getMessage("pm.plate_spec_bt_001",  new Object[]{list.get(i).getPlateThickFrom(), list.get(i).getPlateThickTo()}).getDesc());
            }
            //单条记录中，“组合板宽度起”必须小于“组合板宽度止
            if (list.get(i).getCombinePlateWidthFrom().compareTo(list.get(i).getCombinePlateWidthTo()) >= 0) {
                addErrorMsg(i,MessageAccessor.getMessage("pm.plate_spec_bt_002",  new Object[]{list.get(i).getCombinePlateWidthFrom(), list.get(i).getCombinePlateWidthTo()}).getDesc());
            }
        }

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

                    // 校验组合板宽度区间是否交叉
                    boolean slabWidthIntervalCheck = Utils.isIntersect(valuelist.get(i).getCombinePlateWidthFrom(), valuelist.get(i).getCombinePlateWidthTo(),
                            valuelist.get(j).getCombinePlateWidthFrom(), valuelist.get(j).getCombinePlateWidthTo());
                    if (!slabWidthIntervalCheck) {
                        continue;
                    }
                    addErrorMsg(idxMap.get(valuelist.get(i)), MessageAccessor.getMessage("pm.thick_addv_bt_003", new Object[]{
                            valuelist.get(j).getPlateThickFrom(), valuelist.get(j).getPlateThickTo(),
                            valuelist.get(j).getCombinePlateWidthFrom(), valuelist.get(j).getCombinePlateWidthTo()}).getDesc());
                    flag = false;
                }
            }
        }

        // 获取字段集合，查询数据库该范围内数据
        List<String> stCodeList = list.stream().map(PmPlateSpecBt::getStCode).distinct().collect(Collectors.toList());
        List<String> formPlateModeList = list.stream().map(PmPlateSpecBt::getFormPlateMode).distinct().collect(Collectors.toList());
        List<String> adTypeModeList = list.stream().map(PmPlateSpecBt::getAdTypeMode).distinct().collect(Collectors.toList());
        List<String> rollModeList = list.stream().map(PmPlateSpecBt::getRollMode).distinct().collect(Collectors.toList());
        List<String> wholeHeatTreatmentTypeList = list.stream().map(PmPlateSpecBt::getWholeHeatTreatmentType).distinct().collect(Collectors.toList());
        List<String> rollLineNoList = list.stream().map(PmPlateSpecBt::getRollLineNo).distinct().collect(Collectors.toList());
        List<Long> idList = list.stream().filter(item -> item.getPptabId() != null).map(PmPlateSpecBt::getPptabId).collect(Collectors.toList());
        List<PmPlateSpecBt> existList = pmPlateSpecBtRepository.selectByCondition(Condition.builder(PmPlateSpecBt.class)
                .andWhere(Sqls.custom().andEqualTo(PmPlateSpecBt.FIELD_TENANT_ID, tenantId))
                .andWhere(Sqls.custom().andIn(PmPlateSpecBt.FIELD_ST_CODE, stCodeList))
                .andWhere(Sqls.custom().andIn(PmPlateSpecBt.FIELD_FORM_PLATE_MODE, formPlateModeList))
                .andWhere(Sqls.custom().andIn(PmPlateSpecBt.FIELD_AD_TYPE_MODE, adTypeModeList))
                .andWhere(Sqls.custom().andIn(PmPlateSpecBt.FIELD_ROLL_MODE, rollModeList))
                .andWhere(Sqls.custom().andIn(PmPlateSpecBt.FIELD_WHOLE_HEAT_TREATMENT_TYPE, wholeHeatTreatmentTypeList))
                .andWhere(Sqls.custom().andIn(PmPlateSpecBt.FIELD_ROLL_LINE_NO, rollLineNoList))
                .andWhere(Sqls.custom().andNotIn(PmPlateSpecBt.FIELD_PPTAB_ID, idList, true))
                .build());

        // 与数据库记录校验区间是否交叉
        if (org.apache.commons.collections.CollectionUtils.isNotEmpty(existList)) {
            // 校验板坯厚度
            Map<String, List<PmPlateSpecBt>> existSlabBtMap = existList.stream().collect(Collectors.groupingBy(pmPlateSpecBtService::getSlabKey));

            for (int i = 0; i < list.size(); i++) {
                if (existSlabBtMap.containsKey(pmPlateSpecBtService.getSlabKey(list.get(i)))) {
                    List<PmPlateSpecBt> slabSpecBtValueList = existSlabBtMap.get(pmPlateSpecBtService.getSlabKey(list.get(i)));
                    for (PmPlateSpecBt specBt : slabSpecBtValueList) {
                        // 校验钢板厚度区间是否交叉
                        boolean slabThickIntervalCheck = Utils.isIntersect(list.get(i).getPlateThickFrom()
                                , list.get(i).getPlateThickTo(), specBt.getPlateThickFrom(), specBt.getPlateThickTo());
                        if (!slabThickIntervalCheck) {
                            continue;
                        }

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

                        addErrorMsg(i, MessageAccessor.getMessage("pm.thick_addv_bt_004",
                                new Object[]{ list.get(i).getPlateThickFrom(), list.get(i).getPlateThickTo(),
                                        list.get(i).getCombinePlateWidthFrom(), list.get(i).getCombinePlateWidthTo()}).getDesc());
                        flag = false;
                    }
                }
            }
        }

        return flag;
    }

}
