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.PmStCodeBtService;
import com.xisc.pm.domain.entity.PmStCodeBt;
import com.xisc.pm.domain.repository.PmStCodeBtRepository;
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/9/25 14:33
 */
@Slf4j
@ImportValidators({@ImportValidator(templateCode = "PM.ST_CODE_BT")})
public class PmStCodeBtValidator extends BatchValidatorHandler {

    private final ObjectMapper objectMapper;

    private final PmStCodeBtRepository pmStCodeBtRepository;

    private final PmStCodeBtService pmStCodeBtService;

    public PmStCodeBtValidator(ObjectMapper objectMapper, PmStCodeBtRepository pmStCodeBtRepository, PmStCodeBtService pmStCodeBtService) {
        this.objectMapper = objectMapper;
        this.pmStCodeBtRepository = pmStCodeBtRepository;
        this.pmStCodeBtService = pmStCodeBtService;
    }

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

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

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

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

        // 如果集合为空，则结束
        if (CollectionUtils.isEmpty(list)) {
            return flag;
        }
        // 校验新增或者更新的数据是否满足唯一性校验
        Map<String, List<PmStCodeBt>> pmStCodeBtMap = list.stream().collect(Collectors.groupingBy(pmStCodeBtService::getStCodeKey));
        for (int i = 0; i < list.size(); i++) {
            if (pmStCodeBtMap.get(pmStCodeBtService.getStCodeKey(list.get(i))).size() > 1) {
                addErrorMsg(i, MessageAccessor.getMessage("pm.st_code_bt_001",
                        new Object[]{list.get(i).getStCode(), list.get(i).getStNo(), list.get(i).getRollLineNo()}).getDesc());
                flag = false;
            }
        }
        // 获取字段集合，查询数据库在该范围内数据
        List<String> stCodeList = list.stream().map(PmStCodeBt::getStCode).distinct().collect(Collectors.toList());
        List<String> stNoList = list.stream().map(PmStCodeBt::getStNo).distinct().collect(Collectors.toList());
        List<String> rollLineNoList = list.stream().map(PmStCodeBt::getRollLineNo).distinct().collect(Collectors.toList());
        List<PmStCodeBt> existPmStCodeBtList = pmStCodeBtRepository.selectByCondition(Condition.builder(PmStCodeBt.class)
                .andWhere(Sqls.custom().andEqualTo(PmStCodeBt.FIELD_TENANT_ID, tenantId))
                .andWhere(Sqls.custom().andIn(PmStCodeBt.FIELD_ST_CODE, stCodeList))
                .andWhere(Sqls.custom().andIn(PmStCodeBt.FIELD_ST_NO, stNoList))
                .andWhere(Sqls.custom().andIn(PmStCodeBt.FIELD_ROLL_LINE_NO, rollLineNoList))
                .build());
        if (org.apache.commons.collections.CollectionUtils.isNotEmpty(existPmStCodeBtList)) {
            // 校验数据唯一性
            Map<String, PmStCodeBt> existPmStCodeBtMap = existPmStCodeBtList.stream().collect(Collectors.toMap(pmStCodeBtService::getStCodeKey, t -> t));
            for (int i = 0; i < list.size(); i++) {
                if (existPmStCodeBtMap.containsKey(pmStCodeBtService.getStCodeKey(list.get(i)))) {
                    addErrorMsg(i, MessageAccessor.getMessage("pm.st_code_bt_002",
                            new Object[]{list.get(i).getStCode(), list.get(i).getStNo(), list.get(i).getRollLineNo()}).getDesc());
                    flag = false;
                }
            }
        }

        return flag;
    }
}
