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.PmProContProdTtr;
import com.xisc.pm.domain.entity.PmRetainSt;
import com.xisc.pm.domain.repository.PmIrsubableContRepository;
import com.xisc.pm.infra.mapper.PmIrsubableContMapper;
import com.xisc.pm.infra.mapper.PmProContProdTtrMapper;
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.beans.BeanUtils;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
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_CONT")
public class PmIrsubableContImportImpl implements IBatchImportService {

    private final ObjectMapper objectMapper;

    private final PmIrsubableContRepository pmIrsubableContRepository;

    private final PmProContProdTtrMapper pmProContProdTtrMapper;

    private final PmIrsubableContMapper pmIrsubableContMapper;



    public PmIrsubableContImportImpl(ObjectMapper objectMapper, PmIrsubableContRepository pmIrsubableContRepository, PmProContProdTtrMapper pmProContProdTtrMapper, PmIrsubableContMapper pmIrsubableContMapper) {
        this.objectMapper = objectMapper;
        this.pmIrsubableContRepository = pmIrsubableContRepository;
        this.pmProContProdTtrMapper = pmProContProdTtrMapper;
        this.pmIrsubableContMapper = pmIrsubableContMapper;
    }

    @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<PmIrsubableCont> list = new ArrayList<>(data.size());
        List<String> orderNoList = new ArrayList<>();

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

        for(PmIrsubableCont pmIrsubableCont:PmIrsubableContList){
            pmIrsubableCont.setTenantId(tenantId);
            list.add(pmIrsubableCont);
        }

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


        List<PmIrsubableCont> checkList = pmIrsubableContMapper.checkList(uniqueIncomingCombinationList);

        Map<String, PmIrsubableCont> checkListMap = checkList.stream()
                .collect(Collectors.toMap(
                        cont -> cont.getOrderNo(),
                        cont -> cont
                ));

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

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

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