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

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xisc.pm.domain.entity.PmIrsubableCont;
import com.xisc.pm.domain.entity.PmIrsubableSlab;
import com.xisc.pm.domain.repository.PmIrsubableSlabRepository;
import com.xisc.pm.infra.mapper.PmIrsubableSlabMapper;
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.IBatchImportService;
import org.hzero.boot.imported.infra.validator.annotation.ImportService;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author BKGY
 * @since 2024年12月19日09:05:39
 */
@Slf4j
@ImportService(templateCode = "PM.IRSUBABLE_SLAB")
public class PmIrsubableSlabImportImpl implements IBatchImportService {

    private final ObjectMapper objectMapper;

    private final PmIrsubableSlabRepository pmIrsubableSlabRepository;

    private final PmIrsubableSlabMapper pmIrsubableSlabMapper;



    public PmIrsubableSlabImportImpl(ObjectMapper objectMapper, PmIrsubableSlabRepository pmIrsubableSlabRepository, PmIrsubableSlabMapper pmIrsubableSlabMapper) {
        this.objectMapper = objectMapper;
        this.pmIrsubableSlabRepository = pmIrsubableSlabRepository;
        this.pmIrsubableSlabMapper = pmIrsubableSlabMapper;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean doImport(List<String> data) {
        // 如果集合为空，则返回
        if (CollectionUtils.isEmpty(data)) {
            throw new CommonException("pm.import_data_is_empty_list");
        }
        // 获取租户id以及用户信息
        Long tenantId = 0L;
        if (DetailsHelper.getUserDetails() != null && DetailsHelper.getUserDetails().getTenantId() != null) {
            tenantId = DetailsHelper.getUserDetails().getTenantId();
        }
        // 定义要插入的List
        List<PmIrsubableSlab> list = new ArrayList<>(data.size());
        List<String> slabNoList = new ArrayList<>();

        // 数据转对象
        for (String json : data) {
            try {
                PmIrsubableSlab pmIrsubableSlab = objectMapper.readValue(json, PmIrsubableSlab.class);
                slabNoList.add(pmIrsubableSlab.getSlabNo());
            } catch (JsonProcessingException e) {
                log.error(e.getMessage(), e);
            }
        }
        // 如果集合为空，则结束
        if (CollectionUtils.isEmpty(slabNoList)) {
            throw new CommonException("pm.import_data_is_empty_list");
        }
        List<PmIrsubableSlab> pmIrsubableSlabList = pmIrsubableSlabMapper.querySaveList(slabNoList,tenantId);

        for(PmIrsubableSlab pmIrsubableSlab:pmIrsubableSlabList){
            pmIrsubableSlab.setTenantId(tenantId);
            list.add(pmIrsubableSlab);
        }

        // 提取传入数据的 orderNo
        List<String> uniqueIncomingCombinationList = list.stream()
                .map(stack -> stack.getSlabNo())
                .collect(Collectors.toList());


        List<PmIrsubableSlab> checkList = pmIrsubableSlabMapper.checkList(uniqueIncomingCombinationList);

        Map<String, PmIrsubableSlab> checkListMap = checkList.stream()
                .collect(Collectors.toMap(
                        slab -> slab.getSlabNo(),
                        slab -> slab
                ));

        // 遍历list，根据组合字符串查找checkListMap中的id并赋值
        list.forEach(slab -> {
            String key = slab.getSlabNo();
            if (checkListMap.containsKey(key)) {
                PmIrsubableSlab existingCont = checkListMap.get(key);
                slab.setId(existingCont.getId());
                slab.setObjectVersionNumber(existingCont.getObjectVersionNumber());
            }
        });

        List<PmIrsubableSlab> insertList = list.stream().filter(line -> line.getId() == null).collect(Collectors.toList());
        List<PmIrsubableSlab> updateList = list.stream().filter(line -> line.getId() != null).collect(Collectors.toList());

        pmIrsubableSlabRepository.batchInsertSelective(insertList);
        pmIrsubableSlabRepository.batchUpdateByPrimaryKeySelective(updateList);
        return true;
    }
}
