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

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xisc.pm.domain.entity.PmPlateSpecYieldBt;
import com.xisc.pm.domain.repository.PmPlateSpecYieldBtRepository;
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/25 15:50
 * 已废弃
 */
@Slf4j
@ImportValidators({@ImportValidator(templateCode = "PM.PLATE_SPEC_YIELD_BT")})
public class PmPlateSpecYieldBtValidator extends BatchValidatorHandler {

    private final ObjectMapper objectMapper;

    private final PmPlateSpecYieldBtRepository pmPlateSpecYieldBtRepository;

    public PmPlateSpecYieldBtValidator(ObjectMapper objectMapper, PmPlateSpecYieldBtRepository pmPlateSpecYieldBtRepository) {
        this.objectMapper = objectMapper;
        this.pmPlateSpecYieldBtRepository = pmPlateSpecYieldBtRepository;
    }

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

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

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

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

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

        // 新增记录之间校验区间是否交叉
        for (int i = 0; i < list.size() - 1; i++) {
            for (int j = i + 1; j < list.size(); j++) {

                // 校验钢板厚度区间是否交叉
                boolean slabThickIntervalCheck = Utils.isIntersect(list.get(i).getPlateThickFrom(), list.get(i).getPlateThickTo(),
                        list.get(j).getPlateThickFrom(), list.get(j).getPlateThickTo());
                if (slabThickIntervalCheck) {
                    addErrorMsg(idxMap.get(list.get(i)), MessageAccessor.getMessage("pm.cut_place_bt_001", new Object[]{list.get(j).getPlateThickFrom(), list.get(j).getPlateThickTo()}).getDesc());
                    flag = false;
                }

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


            }
        }
        List<String> rollLineNoList = list.stream().map(PmPlateSpecYieldBt::getRollLineNo).distinct().collect(Collectors.toList());
        // 与数据库记录校验区间是否交叉
        List<PmPlateSpecYieldBt> existPlateSpecYieldBtList = pmPlateSpecYieldBtRepository.selectByCondition(Condition.builder(PmPlateSpecYieldBt.class)
                .andWhere(Sqls.custom().andEqualTo(PmPlateSpecYieldBt.FIELD_TENANT_ID, tenantId))
                .andWhere(Sqls.custom().andIn(PmPlateSpecYieldBt.FIELD_ROLL_LINE_NO, rollLineNoList, true))
                .build());
        if (CollectionUtils.isEmpty(existPlateSpecYieldBtList)) {
            return flag;
        }

        for (int i = 0; i < list.size(); i++) {
            for (int j = 0; j < existPlateSpecYieldBtList.size(); j++) {

                // 校验钢板厚度区间是否交叉
                boolean slabThickIntervalCheck = Utils.isIntersect(list.get(i).getPlateThickFrom(),
                        list.get(i).getPlateThickTo(), existPlateSpecYieldBtList.get(j).getPlateThickFrom(),
                        existPlateSpecYieldBtList.get(j).getPlateThickTo());
                if (slabThickIntervalCheck) {
                    addErrorMsg(idxMap.get(list.get(i)),MessageAccessor.getMessage("pm.cut_place_bt_001", new Object[]{existPlateSpecYieldBtList.get(j).getPlateThickFrom(), existPlateSpecYieldBtList.get(j).getPlateThickTo()}).getDesc());
                    flag = false;
                }

                // 校验组合板宽度区间是否交叉
                boolean combinePlateWidthIntervalCheck = Utils.isIntersect(list.get(i).getCombinePlateWidthFrom(),
                        list.get(i).getCombinePlateWidthTo(), existPlateSpecYieldBtList.get(j).getCombinePlateWidthFrom(),
                        existPlateSpecYieldBtList.get(j).getCombinePlateWidthTo());
                if (combinePlateWidthIntervalCheck) {
                    addErrorMsg(idxMap.get(list.get(i)), MessageAccessor.getMessage("pm.plate_spec_yield_bt", new Object[]{existPlateSpecYieldBtList.get(j).getCombinePlateWidthFrom(), existPlateSpecYieldBtList.get(j).getCombinePlateWidthTo()}).getDesc());
                    flag = false;
                }
            }
        }
        return flag;
    }

}
