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.PmMoldSpecBt;
import com.xisc.pm.domain.entity.PmMoldSpecBtTra;
import com.xisc.pm.domain.repository.PmMoldSpecBtRepository;
import com.xisc.pm.domain.repository.PmMoldSpecBtTraRepository;
import com.xisc.pm.infra.constant.Constants;
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.hzero.boot.platform.lov.adapter.LovAdapter;
import org.hzero.boot.platform.lov.dto.LovValueDTO;
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 纪文桃 wentao.ji01@hand-china.com
 * @since 2024/9/25 15:13
 */
@Slf4j
@ImportService(templateCode = "PM.MOLD_SPEC_BT")
public class PmMoldSpecBtImportImpl implements IBatchImportService {

    private final ObjectMapper objectMapper;

    private final PmMoldSpecBtRepository pmMoldSpecBtRepository;

    private final PmMoldSpecBtTraRepository pmMoldSpecBtTraRepository;

    private final LovAdapter lovAdapter;

    public PmMoldSpecBtImportImpl(ObjectMapper objectMapper, PmMoldSpecBtRepository pmMoldSpecBtRepository,
                                  PmMoldSpecBtTraRepository pmMoldSpecBtTraRepository, LovAdapter lovAdapter) {
        this.objectMapper = objectMapper;
        this.pmMoldSpecBtRepository = pmMoldSpecBtRepository;
        this.pmMoldSpecBtTraRepository = pmMoldSpecBtTraRepository;
        this.lovAdapter = lovAdapter;
    }

    @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;
        Date now = new Date();
        String username = DetailsHelper.getUserDetails().getUsername();
        if (DetailsHelper.getUserDetails() != null && DetailsHelper.getUserDetails().getTenantId() != null) {
            tenantId = DetailsHelper.getUserDetails().getTenantId();
        }
        // 定义要插入的List
        List<PmMoldSpecBt> list = new ArrayList<>(data.size());
        List<PmMoldSpecBtTra> tralist = new ArrayList<>(data.size());

        // 数据转对象
        for (String json : data) {
            try {
                PmMoldSpecBt pmMoldSpecBt = objectMapper.readValue(json, PmMoldSpecBt.class);
                pmMoldSpecBt.setTenantId(tenantId);
                list.add(pmMoldSpecBt);

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

        // 如果集合为空，则结束
        if (CollectionUtils.isEmpty(list)) {
            throw new CommonException("pm.import_data_is_empty_list");
        }

        // 获取连铸机值集含义
        List<LovValueDTO> ccTypeList = lovAdapter.queryLovValue(Constants.LovCode.BT_CC_TYPE, tenantId);
        // 赋值连铸机含义
        if (CollectionUtils.isNotEmpty(ccTypeList)) {
            Map<String, String> ccTypeLovMap = ccTypeList.stream().collect(Collectors.toMap(LovValueDTO::getValue,
                    LovValueDTO::getMeaning));
            list.forEach(item->{
                item.setCcDesc(ccTypeLovMap.getOrDefault(item.getCcType(), item.getCcType()));
            });
        }
        // 插入表
        pmMoldSpecBtRepository.batchInsertSelective(list);

        // 获取履历表数据
        for (PmMoldSpecBt pmMoldSpecBt : list) {
            PmMoldSpecBtTra pmMoldSpecBtTra = new PmMoldSpecBtTra();
            BeanUtils.copyProperties(pmMoldSpecBt, pmMoldSpecBtTra);
            // 设置操作类型为新增（I），并记录操作时间和用户
            pmMoldSpecBtTra.setOperationType("I");
            pmMoldSpecBtTra.setOperationTime(now);
            pmMoldSpecBtTra.setOperationUser(username);
            tralist.add(pmMoldSpecBtTra);
        }
        // 插入履历表
        pmMoldSpecBtTraRepository.batchInsertSelective(tralist);
        return true;
    }
}
