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

import com.xisc.pm.app.service.PmSdivSpecLimitBtService;
import com.xisc.pm.domain.entity.PmSdivSpecLimitBt;
import com.xisc.pm.domain.entity.PmSdivSpecLimitBtTra;
import com.xisc.pm.domain.repository.PmSdivSpecLimitBtRepository;
import com.xisc.pm.domain.repository.PmSdivSpecLimitBtTraRepository;
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;

/**
 * 剖分组板设备规格限制表(PmSdivSpecLimitBt)应用服务
 *
 * @author 纪文桃 wentao.ji01@hand-china.com
 * @since 2024-07-25 08:34:17
 */
@Service
public class PmSdivSpecLimitBtServiceImpl implements PmSdivSpecLimitBtService {

    private PmSdivSpecLimitBtRepository pmSdivSpecLimitBtRepository;

    private PmSdivSpecLimitBtTraRepository pmSdivSpecLimitBtTraRepository;

    public PmSdivSpecLimitBtServiceImpl(PmSdivSpecLimitBtRepository pmSdivSpecLimitBtRepository, PmSdivSpecLimitBtTraRepository pmSdivSpecLimitBtTraRepository) {
        this.pmSdivSpecLimitBtRepository = pmSdivSpecLimitBtRepository;
        this.pmSdivSpecLimitBtTraRepository = pmSdivSpecLimitBtTraRepository;
    }

    @Override
    public Page<PmSdivSpecLimitBt> selectList(PageRequest pageRequest, PmSdivSpecLimitBt pmSdivSpecLimitBt) {
        return PageHelper.doPageAndSort(pageRequest, () -> pmSdivSpecLimitBtRepository.selectList(pmSdivSpecLimitBt));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveData(Long tenantId, List<PmSdivSpecLimitBt> pmSdivSpecLimitBtList) {
        // 检查数据列表是否为空，如果为空则直接返回
        if (CollectionUtils.isEmpty(pmSdivSpecLimitBtList)) {
            return ;
        }
        // 	唯一性索引：轧制产线号。
        Map<String, List<PmSdivSpecLimitBt>> pmSdivSpecLimitBtMap = pmSdivSpecLimitBtList.stream()
                .collect(Collectors.groupingBy(PmSdivSpecLimitBt::getRollLineNo));
        for (Map.Entry<String, List<PmSdivSpecLimitBt>> entry : pmSdivSpecLimitBtMap.entrySet()) {
           if (entry.getValue().size() > 1) {
               throw new CommonException("pm.sdiv_spec_limit_bt_001", entry.getValue().get(0).getRollLineNo());
           }
        }

        List<String> rollineNoList = pmSdivSpecLimitBtList.stream().map(PmSdivSpecLimitBt::getRollLineNo).collect(Collectors.toList());
        List<Long> idList = pmSdivSpecLimitBtList.stream().filter(item -> item.getPsslbId() != null).map(PmSdivSpecLimitBt::getPsslbId).collect(Collectors.toList());
        List<PmSdivSpecLimitBt> sdivSpecLimitBtList = pmSdivSpecLimitBtRepository.selectByCondition(Condition.builder(PmSdivSpecLimitBt.class)
                .andWhere(Sqls.custom().andIn(PmSdivSpecLimitBt.FIELD_ROLL_LINE_NO, rollineNoList))
                .andWhere(Sqls.custom().andEqualTo(PmSdivSpecLimitBt.FIELD_TENANT_ID, tenantId))
                .andWhere(Sqls.custom().andNotIn(PmSdivSpecLimitBt.FIELD_PSSLB_ID, idList, true))
                .build());
        if (CollectionUtils.isNotEmpty(sdivSpecLimitBtList)) {
            throw new CommonException("pm.sdiv_spec_limit_bt_002", sdivSpecLimitBtList.get(0).getRollLineNo());
        }
        // 获取当前时间及操作人信息
        Date now = new Date();
        String username = DetailsHelper.getUserDetails().getUsername();
        List<PmSdivSpecLimitBtTra> insertPmSdivSpecLimitBtTraList = new ArrayList<>(pmSdivSpecLimitBtList.size());

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

        // 记录历史表
        for (PmSdivSpecLimitBt pmSdivSpecLimitBt : updateList) {
            PmSdivSpecLimitBtTra pmSdivSpecLimitBtTra = new PmSdivSpecLimitBtTra();
            BeanUtils.copyProperties(pmSdivSpecLimitBt, pmSdivSpecLimitBtTra);

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

        }
        // 更新或者新增
        pmSdivSpecLimitBtRepository.batchUpdateByPrimaryKey(updateList);
        pmSdivSpecLimitBtRepository.batchInsertSelective(insertList);

        for (PmSdivSpecLimitBt pmSdivSpecLimitBt : insertList) {
            PmSdivSpecLimitBtTra pmSdivSpecLimitBtTra = new PmSdivSpecLimitBtTra();
            BeanUtils.copyProperties(pmSdivSpecLimitBt, pmSdivSpecLimitBtTra);

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

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

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

            // 获取时间和当前操作人信息
            Date now = new Date();
            String username = DetailsHelper.getUserDetails().getUsername();
            List<PmSdivSpecLimitBtTra> insertPmSdivSpecLimitBtTraList = new ArrayList<>(pmSdivSpecLimitBtList.size());
            for (PmSdivSpecLimitBt pmSdivSpecLimitBt : pmSdivSpecLimitBtList) {
                PmSdivSpecLimitBtTra pmSdivSpecLimitBtTra = new PmSdivSpecLimitBtTra();

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

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

