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

import com.xisc.pm.app.service.PmHeatTreatFurnaceBtService;
import com.xisc.pm.domain.entity.PmHeatTreatFurnaceBt;
import com.xisc.pm.domain.entity.PmHeatTreatFurnaceBtTra;
import com.xisc.pm.domain.repository.PmHeatTreatFurnaceBtRepository;
import com.xisc.pm.domain.repository.PmHeatTreatFurnaceBtTraRepository;
import io.choerodon.core.domain.Page;
import io.choerodon.core.exception.CommonException;
import io.choerodon.core.oauth.DetailsHelper;
import io.choerodon.mybatis.pagehelper.PageHelper;
import io.choerodon.mybatis.pagehelper.domain.PageRequest;
import org.apache.commons.collections.CollectionUtils;
import org.hzero.mybatis.domian.Condition;
import org.hzero.mybatis.util.Sqls;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
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;

/**
 * 热处理炉基准规格表(PmHeatTreatFurnaceBt)应用服务
 *
 * @author 纪文桃 wentao.ji01@hand-china.com
 * @since 2024-07-24 12:24:42
 */
@Service
public class PmHeatTreatFurnaceBtServiceImpl implements PmHeatTreatFurnaceBtService {

    private PmHeatTreatFurnaceBtRepository pmHeatTreatFurnaceBtRepository;

    private PmHeatTreatFurnaceBtTraRepository pmHeatTreatFurnaceBtTraRepository;

    public PmHeatTreatFurnaceBtServiceImpl(PmHeatTreatFurnaceBtRepository pmHeatTreatFurnaceBtRepository, PmHeatTreatFurnaceBtTraRepository pmHeatTreatFurnaceBtTraRepository) {
        this.pmHeatTreatFurnaceBtRepository = pmHeatTreatFurnaceBtRepository;
        this.pmHeatTreatFurnaceBtTraRepository = pmHeatTreatFurnaceBtTraRepository;
    }

    @Override
    public Page<PmHeatTreatFurnaceBt> selectList(PageRequest pageRequest, PmHeatTreatFurnaceBt pmHeatTreatFurnaceBt) {
        return PageHelper.doPageAndSort(pageRequest, () -> pmHeatTreatFurnaceBtRepository.selectList(pmHeatTreatFurnaceBt));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveData(Long tenantId, List<PmHeatTreatFurnaceBt> pmHeatTreatFurnaceBtList) {
        // 检查列表是否为空，如果为空则直接返回
        if (CollectionUtils.isEmpty(pmHeatTreatFurnaceBtList)) {
            return;
        }

        // 唯一性索引：热处理炉号。
        Map<String, List<PmHeatTreatFurnaceBt>> furnaceBtMap = pmHeatTreatFurnaceBtList.stream()
                .collect(Collectors.groupingBy(PmHeatTreatFurnaceBt::getHeatTreatFurnaceNo));
        for (Map.Entry<String, List<PmHeatTreatFurnaceBt>> entry : furnaceBtMap.entrySet()) {
            if (entry.getValue().size() > 1) {
                throw new CommonException("pm.heat_treat_furnace_bt_001", entry.getKey());
            }
        }

        List<String> treatFurnaceNoList = pmHeatTreatFurnaceBtList.stream()
                .map(PmHeatTreatFurnaceBt::getHeatTreatFurnaceNo).collect(Collectors.toList());
        List<Long> idList = pmHeatTreatFurnaceBtList.stream().filter(item -> item.getPhtfbId() != null)
                .map(PmHeatTreatFurnaceBt::getPhtfbId).collect(Collectors.toList());
        List<PmHeatTreatFurnaceBt> heatTreatFurnaceBtList = pmHeatTreatFurnaceBtRepository.selectByCondition(Condition.builder(PmHeatTreatFurnaceBt.class)
                .andWhere(Sqls.custom().andIn(PmHeatTreatFurnaceBt.FIELD_HEAT_TREAT_FURNACE_NO, treatFurnaceNoList))
                .andWhere(Sqls.custom().andEqualTo(PmHeatTreatFurnaceBt.FIELD_TENANT_ID, tenantId))
                .andWhere(Sqls.custom().andNotIn(PmHeatTreatFurnaceBt.FIELD_PHTFB_ID, idList, true))
                .build());
        if (CollectionUtils.isNotEmpty(heatTreatFurnaceBtList)) {
           throw new CommonException("pm.heat_treat_furnace_bt_002",heatTreatFurnaceBtList.get(0).getHeatTreatFurnaceNo());
        }

        // 获取当前时间和用户信息
        Date now = new Date();
        String username = DetailsHelper.getUserDetails().getUsername();

        // 初始化用于记录操作历史的列表
        List<PmHeatTreatFurnaceBtTra> insertPmMoldSpecBtTraList = new ArrayList<>(pmHeatTreatFurnaceBtList.size());

        // 分别筛选出待新增和待更新的
        List<PmHeatTreatFurnaceBt> insertList = pmHeatTreatFurnaceBtList.stream().filter(line -> line.getPhtfbId() == null).collect(Collectors.toList());
        List<PmHeatTreatFurnaceBt> updateList = pmHeatTreatFurnaceBtList.stream().filter(line -> line.getPhtfbId() != null).collect(Collectors.toList());


        // 记录历史表
        for (PmHeatTreatFurnaceBt pmHeatTreatFurnaceBt : updateList) {
            PmHeatTreatFurnaceBtTra pmHeatTreatFurnaceBtTra = new PmHeatTreatFurnaceBtTra();
            BeanUtils.copyProperties(pmHeatTreatFurnaceBt, pmHeatTreatFurnaceBtTra);

            // 设置操作类型为更新（U），并记录操作时间和服务用户
            pmHeatTreatFurnaceBtTra.setOperationType("U");
            pmHeatTreatFurnaceBtTra.setOperationTime(now);
            pmHeatTreatFurnaceBtTra.setOperationUser(username);
            insertPmMoldSpecBtTraList.add(pmHeatTreatFurnaceBtTra);
        }

        // 执行批量插入和更新操作
        pmHeatTreatFurnaceBtRepository.batchUpdateByPrimaryKey(updateList);
        pmHeatTreatFurnaceBtRepository.batchInsertSelective(insertList);

        // 处理待新增的生成操作历史记录
        for (PmHeatTreatFurnaceBt pmHeatTreatFurnaceBt : insertList) {
            PmHeatTreatFurnaceBtTra pmHeatTreatFurnaceBtTra = new PmHeatTreatFurnaceBtTra();
            BeanUtils.copyProperties(pmHeatTreatFurnaceBt, pmHeatTreatFurnaceBtTra);

            // 设置操作类型为插入（I），并记录操作时间和服务用户
            pmHeatTreatFurnaceBtTra.setOperationType("I");
            pmHeatTreatFurnaceBtTra.setOperationTime(now);
            pmHeatTreatFurnaceBtTra.setOperationUser(username);
            insertPmMoldSpecBtTraList.add(pmHeatTreatFurnaceBtTra);
        }

        // 批量插入操作履历表记录
        pmHeatTreatFurnaceBtTraRepository.batchInsertSelective(insertPmMoldSpecBtTraList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteForUi(List<PmHeatTreatFurnaceBt> pmHeatTreatFurnaceBtList) {
        if (CollectionUtils.isNotEmpty(pmHeatTreatFurnaceBtList)) {
            // 删除
            pmHeatTreatFurnaceBtRepository.batchDeleteByPrimaryKey(pmHeatTreatFurnaceBtList);

            // 记录历史表
            Date now = new Date();
            String username = DetailsHelper.getUserDetails().getUsername();
            List<PmHeatTreatFurnaceBtTra> insertPmMoldSpecBtTraList = new ArrayList<>(pmHeatTreatFurnaceBtList.size());
            for (PmHeatTreatFurnaceBt pmHeatTreatFurnaceBt : pmHeatTreatFurnaceBtList) {
                PmHeatTreatFurnaceBtTra pmHeatTreatFurnaceBtTra = new PmHeatTreatFurnaceBtTra();

                // 设置操作类型为删除（D），并记录操作时间和服务用户。
                BeanUtils.copyProperties(pmHeatTreatFurnaceBt, pmHeatTreatFurnaceBtTra);
                pmHeatTreatFurnaceBtTra.setOperationType("D");
                pmHeatTreatFurnaceBtTra.setOperationTime(now);
                pmHeatTreatFurnaceBtTra.setOperationUser(username);
                insertPmMoldSpecBtTraList.add(pmHeatTreatFurnaceBtTra);

            }
            // 插入删除记录到对应履历表
            pmHeatTreatFurnaceBtTraRepository.batchInsertSelective(insertPmMoldSpecBtTraList);
        }
    }
}


