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.PmSpeStAddvBtService;
import com.xisc.pm.domain.entity.PmSpeStAddvBt;
import com.xisc.pm.domain.repository.PmSpeStAddvBtRepository;
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 10:32
 */
@Slf4j
@ImportValidators({@ImportValidator(templateCode = "PM.SPE_ST_ADDV_BT")})
public class PmSpeStAddvBtValidator extends BatchValidatorHandler {

    private final ObjectMapper objectMapper;

    private final PmSpeStAddvBtRepository pmSpeStAddvBtRepository;


    private final PmSpeStAddvBtService pmSpeStAddvBtService;

    public PmSpeStAddvBtValidator(ObjectMapper objectMapper, PmSpeStAddvBtRepository pmSpeStAddvBtRepository, PmSpeStAddvBtService pmSpeStAddvBtService) {
        this.objectMapper = objectMapper;
        this.pmSpeStAddvBtRepository = pmSpeStAddvBtRepository;
        this.pmSpeStAddvBtService = pmSpeStAddvBtService;
    }


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

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

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

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

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

        // 新增记录之间校验区间是否交叉
        Map<String, List<PmSpeStAddvBt>> speStAddvBtMap = list.stream().collect(Collectors.groupingBy(pmSpeStAddvBtService::getTmpKey));
        for (Map.Entry<String, List<PmSpeStAddvBt>> entry : speStAddvBtMap.entrySet()) {
            List<PmSpeStAddvBt> speStAddvBtList = entry.getValue();
            for (int i = 0; i < speStAddvBtList.size() - 1; i++) {
                for (int j = i + 1; j < speStAddvBtList.size(); j++) {
                    // 校验钢板厚度区间是否交叉
                    boolean plateThickIntervalCheck = Utils.isIntersect(speStAddvBtList.get(i).getPlateThickFrom(), speStAddvBtList.get(i).getPlateThickTo(),
                            speStAddvBtList.get(j).getPlateThickFrom(), speStAddvBtList.get(j).getPlateThickTo());
                    if (!plateThickIntervalCheck) {
                        continue;
                    }
                    // 校验板坯厚度区间是否交叉
                    boolean normalCutLenIntervalCheck = Utils.isIntersect(speStAddvBtList.get(i).getSlabThickFrom(), speStAddvBtList.get(i).getSlabThickTo(),
                            speStAddvBtList.get(j).getSlabThickFrom(), speStAddvBtList.get(j).getSlabThickTo());
                    if (!normalCutLenIntervalCheck) {
                        continue;
                    }
                    addErrorMsg(idxMap.get(speStAddvBtList.get(i)), MessageAccessor.getMessage("pm.spe_st_addv_bt_001",
                            new Object[]{speStAddvBtList.get(j).getPlateThickFrom(), speStAddvBtList.get(j).getPlateThickTo(),
                                    speStAddvBtList.get(j).getSlabThickFrom(), speStAddvBtList.get(j).getSlabThickTo()}).getDesc());
                    flag = false;
                }
            }
        }

        // 与数据库记录校验区间是否交叉
        List<String> mscLineList = list.stream().map(PmSpeStAddvBt::getMscLineNo).distinct().collect(Collectors.toList());
        List<String> stNoList = list.stream().map(PmSpeStAddvBt::getStNo).distinct().collect(Collectors.toList());
        List<String> sgSignList = list.stream().map(PmSpeStAddvBt::getSgSign).distinct().collect(Collectors.toList());
        List<PmSpeStAddvBt> existSpeStAddvBtList = pmSpeStAddvBtRepository.selectByCondition(Condition.builder(PmSpeStAddvBt.class)
                .andWhere(Sqls.custom().andIn(PmSpeStAddvBt.FIELD_MSC_LINE_NO, mscLineList))
                .andWhere(Sqls.custom().andIn(PmSpeStAddvBt.FIELD_ST_NO, stNoList))
                .andWhere(Sqls.custom().andIn(PmSpeStAddvBt.FIELD_SG_SIGN, sgSignList))
                .andWhere(Sqls.custom().andEqualTo(PmSpeStAddvBt.FIELD_TENANT_ID, tenantId))
                .build());
        if (org.apache.commons.collections.CollectionUtils.isNotEmpty(existSpeStAddvBtList)) {
            Map<String, List<PmSpeStAddvBt>> existMap = existSpeStAddvBtList.stream().collect(Collectors.groupingBy(pmSpeStAddvBtService::getTmpKey));
            for (int i = 0; i < list.size(); i++) {
                if (existMap.containsKey(pmSpeStAddvBtService.getTmpKey(list.get(i)))) {
                    List<PmSpeStAddvBt> existBtList = existMap.get(pmSpeStAddvBtService.getTmpKey(list.get(i)));
                    for (PmSpeStAddvBt speStAddvBt : existBtList) {
                        // 校验钢板厚度区间是否交叉
                        boolean plateThickIntervalCheck = Utils.isIntersect(list.get(i).getPlateThickFrom(), list.get(i).getPlateThickTo(),
                                speStAddvBt.getPlateThickFrom(), speStAddvBt.getPlateThickTo());
                        if (!plateThickIntervalCheck) {
                            continue;
                        }

                        // 校验板坯厚度区间是否交叉
                        boolean slabThickIntervalCheck = Utils.isIntersect(list.get(i).getSlabThickFrom(), list.get(i).getSlabThickTo(),
                                speStAddvBt.getSlabThickFrom(), speStAddvBt.getSlabThickTo());
                        if (!slabThickIntervalCheck) {
                            continue;
                        }
                        addErrorMsg(i, MessageAccessor.getMessage("pm.spe_st_addv_bt_002",
                                new Object[]{speStAddvBt.getPlateThickFrom(), speStAddvBt.getPlateThickTo(),
                                        speStAddvBt.getSlabThickFrom(), speStAddvBt.getSlabThickTo()}).getDesc());
                        flag = false;
                    }
                }
            }
        }

        return flag;
    }
}
