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

import com.xisc.pm.app.service.PmIngotTypeBtService;
import com.xisc.pm.domain.entity.PmHeatTreatFurnaceBt;
import com.xisc.pm.domain.entity.PmIngotTypeBt;
import com.xisc.pm.domain.entity.PmIngotTypeBtTra;
import com.xisc.pm.domain.repository.PmIngotTypeBtRepository;
import com.xisc.pm.domain.repository.PmIngotTypeBtTraRepository;
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;

/**
 * 锭坯型基表(PmIngotTypeBt)应用服务
 *
 * @author 纪文桃 wentao.ji01@hand-china.com
 * @since 2024-07-29 14:54:10
 */
@Service
public class PmIngotTypeBtServiceImpl implements PmIngotTypeBtService {

    private PmIngotTypeBtRepository pmIngotTypeBtRepository;

    private PmIngotTypeBtTraRepository pmIngotTypeBtTraRepository;

    public PmIngotTypeBtServiceImpl(PmIngotTypeBtRepository pmIngotTypeBtRepository, PmIngotTypeBtTraRepository pmIngotTypeBtTraRepository) {
        this.pmIngotTypeBtRepository = pmIngotTypeBtRepository;
        this.pmIngotTypeBtTraRepository = pmIngotTypeBtTraRepository;
    }

    @Override
    public Page<PmIngotTypeBt> selectList(PageRequest pageRequest, PmIngotTypeBt pmIngotTypeBt) {
        return PageHelper.doPageAndSort(pageRequest, () -> pmIngotTypeBtRepository.selectList(pmIngotTypeBt));
    }

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

        // 唯一性索引：锭坯型 。
        Map<String, List<PmIngotTypeBt>> furnaceBtMap = pmIngotTypeBtList.stream()
                .collect(Collectors.groupingBy(PmIngotTypeBt::getIngotType));
        for (Map.Entry<String, List<PmIngotTypeBt>> entry : furnaceBtMap.entrySet()) {
            if (entry.getValue().size() > 1) {
                throw new CommonException("pm.ingot_type_bt_001", entry.getKey());
            }
        }

        List<String> ingotTypeList = pmIngotTypeBtList.stream()
                .map(PmIngotTypeBt::getIngotType).collect(Collectors.toList());
        List<Long> idList = pmIngotTypeBtList.stream().filter(item -> item.getPitbId() != null).map(PmIngotTypeBt::getPitbId).collect(Collectors.toList());
        List<PmIngotTypeBt> ingotTypeBtList = pmIngotTypeBtRepository.selectByCondition(Condition.builder(PmIngotTypeBt.class)
                .andWhere(Sqls.custom().andIn(PmIngotTypeBt.FIELD_INGOT_TYPE, ingotTypeList))
                .andWhere(Sqls.custom().andEqualTo(PmIngotTypeBt.FIELD_TENANT_ID, tenantId))
                .andWhere(Sqls.custom().andNotIn(PmIngotTypeBt.FIELD_PITB_ID, idList, true))
                .build());
        if (CollectionUtils.isNotEmpty(ingotTypeBtList)) {
            throw new CommonException("pm.ingot_type_bt_002",ingotTypeBtList.get(0).getIngotType());
        }

        // 获取当前时间及操作人信息
        Date now = new Date();
        String username = DetailsHelper.getUserDetails().getUsername();
        List<PmIngotTypeBtTra> insertPmMoldSpecBtTraList = new ArrayList<>(pmIngotTypeBtList.size());

        // 分离需要插入和更新的列表
        List<PmIngotTypeBt> insertList = pmIngotTypeBtList.stream().filter(line -> line.getPitbId() == null).collect(Collectors.toList());
        List<PmIngotTypeBt> updateList = pmIngotTypeBtList.stream().filter(line -> line.getPitbId() != null).collect(Collectors.toList());

        // 记录历史表
        for (PmIngotTypeBt pmIngotTypeBt : updateList) {
            PmIngotTypeBtTra pmIngotTypeBtTra = new PmIngotTypeBtTra();
            BeanUtils.copyProperties(pmIngotTypeBt, pmIngotTypeBtTra);

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

        }
        // 更新或者新增
        pmIngotTypeBtRepository.batchUpdateByPrimaryKeySelective(updateList);
        pmIngotTypeBtRepository.batchInsertSelective(insertList);

        for (PmIngotTypeBt pmIngotTypeBt : insertList) {
            PmIngotTypeBtTra pmIngotTypeBtTra = new PmIngotTypeBtTra();
            BeanUtils.copyProperties(pmIngotTypeBt, pmIngotTypeBtTra);

            // 设置操作类型为新增（I），并记录操作时间和用户
            pmIngotTypeBtTra.setOperationType("I");
            pmIngotTypeBtTra.setOperationTime(now);
            pmIngotTypeBtTra.setOperationUser(username);
            insertPmMoldSpecBtTraList.add(pmIngotTypeBtTra);

        }
        // 插入保存或者更新记录到对应履历表
        pmIngotTypeBtTraRepository.batchInsertSelective(insertPmMoldSpecBtTraList);
    }

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

            // 获取时间和当前操作人信息
            Date now = new Date();
            String username = DetailsHelper.getUserDetails().getUsername();
            List<PmIngotTypeBtTra> insertPmIngotTypeBtTraList = new ArrayList<>(pmIngotTypeBtList.size());
            for (PmIngotTypeBt pmIngotTypeBt : pmIngotTypeBtList) {
                PmIngotTypeBtTra pmIngotTypeBtTra = new PmIngotTypeBtTra();

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

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

