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.PmHtolStatic;
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 java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 纪文桃 wentao.ji01@hand-china.com
 * @since 2024/7/26 10:42
 * 已废弃
 */
@Slf4j
@ImportValidators({@ImportValidator(templateCode = "PM.HTOL_STATIC")})
public class PmHtolStaticValidator extends BatchValidatorHandler {


    private final ObjectMapper objectMapper;

    public PmHtolStaticValidator(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }


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

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

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

                list.add(pmHtolStatic);
            } catch (JsonProcessingException e) {
                log.error(e.getMessage(), e);
            }
        }
        return flag;
    }
}
