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

import com.xisc.pm.app.service.PmAxisBrdTrimBtService;
import com.xisc.pm.domain.entity.PmAxisBrdTrimBt;
import com.xisc.pm.domain.entity.PmAxisBrdTrimBtTra;
import com.xisc.pm.domain.repository.PmAxisBrdTrimBtRepository;
import com.xisc.pm.domain.repository.PmAxisBrdTrimBtTraRepository;
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.beans.factory.annotation.Autowired;
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.function.Function;
import java.util.stream.Collectors;

/**
 * 纵轧展宽宽度余量基准表(PmAxisBrdTrimBt)应用服务
 *
 * @author 纪文桃 wentao.ji01@hand-china.com
 * @since 2024-09-23 09:16:11
 */
@Service
public class PmAxisBrdTrimBtServiceImpl implements PmAxisBrdTrimBtService {
    @Autowired
    private PmAxisBrdTrimBtRepository pmAxisBrdTrimBtRepository;

    @Autowired
    private PmAxisBrdTrimBtTraRepository pmAxisBrdTrimBtTraRepository;

    @Override
    public Page<PmAxisBrdTrimBt> selectList(PageRequest pageRequest, PmAxisBrdTrimBt pmAxisBrdTrimBt) {
        return PageHelper.doPageAndSort(pageRequest, () -> pmAxisBrdTrimBtRepository.selectList(pmAxisBrdTrimBt));
    }

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

        // 校验新增更新的数据之间是否重复 -唯一性索引：轧制产线号、切边标记
        Map<String, List<PmAxisBrdTrimBt>> pmAxisBrdTrimBtMap = pmAxisBrdTrimBtList.stream().collect(Collectors.groupingBy(item ->
                item.getRollLineNo() + "-" + item.getWithSideFlag()));
        for (Map.Entry<String, List<PmAxisBrdTrimBt>> entry : pmAxisBrdTrimBtMap.entrySet()) {
            if (entry.getValue().size() > 1) {
                throw new CommonException("pm.axis_brd_trim_bt_001", entry.getValue().get(0).getRollLineNo(),
                        entry.getValue().get(0).getWithSideFlag());
            }
        }

        // 获取字段集合，查询数据库该范围内数据
        List<String> rollLineNoList = pmAxisBrdTrimBtList.stream().map(PmAxisBrdTrimBt::getRollLineNo).distinct().collect(Collectors.toList());
        List<String> withSideFlagList = pmAxisBrdTrimBtList.stream().map(PmAxisBrdTrimBt::getWithSideFlag).distinct().collect(Collectors.toList());
        List<Long> idList = pmAxisBrdTrimBtList.stream().filter(item -> item.getPabtbId() != null).map(PmAxisBrdTrimBt::getPabtbId).collect(Collectors.toList());
        List<PmAxisBrdTrimBt> existPmAxisBrdTrimBtList = pmAxisBrdTrimBtRepository.selectByCondition(Condition.builder(PmAxisBrdTrimBt.class)
                .andWhere(Sqls.custom().andEqualTo(PmAxisBrdTrimBt.FIELD_TENANT_ID, tenantId))
                .andWhere(Sqls.custom().andIn(PmAxisBrdTrimBt.FIELD_ROLL_LINE_NO, rollLineNoList))
                .andWhere(Sqls.custom().andIn(PmAxisBrdTrimBt.FIELD_WITH_SIDE_FLAG, withSideFlagList))
                .andWhere(Sqls.custom().andNotIn(PmAxisBrdTrimBt.FIELD_PABTB_ID, idList, true))
                .build());

        // 与数据库数据之间是否重复
        if (CollectionUtils.isNotEmpty(existPmAxisBrdTrimBtList)) {
            // 根据四个字段校验唯一性
            Map<String, PmAxisBrdTrimBt> existPmAxisBrdTrimBtMap = existPmAxisBrdTrimBtList.stream().collect(Collectors.toMap(item ->
                    item.getRollLineNo() + "-" + item.getWithSideFlag(), Function.identity()));
            for (PmAxisBrdTrimBt pmAxisBrdTrimBt : pmAxisBrdTrimBtList) {
                String key = pmAxisBrdTrimBt.getRollLineNo() + "-" + pmAxisBrdTrimBt.getWithSideFlag();
                if (existPmAxisBrdTrimBtMap.containsKey(key)) {
                    throw new CommonException("pm.axis_brd_trim_bt_001", pmAxisBrdTrimBt.getRollLineNo(), pmAxisBrdTrimBt.getWithSideFlag());
                }
            }
        }


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

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

        // 记录历史表
        for (PmAxisBrdTrimBt pmAxisBrdTrimBt : updateList) {
            PmAxisBrdTrimBtTra pmAxisBrdTrimBtTra = new PmAxisBrdTrimBtTra();
            BeanUtils.copyProperties(pmAxisBrdTrimBt, pmAxisBrdTrimBtTra);

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

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

        for (PmAxisBrdTrimBt pmAxisBrdTrimBt : insertList) {
            PmAxisBrdTrimBtTra pmAxisBrdTrimBtTra = new PmAxisBrdTrimBtTra();
            BeanUtils.copyProperties(pmAxisBrdTrimBt, pmAxisBrdTrimBtTra);

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

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

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

            // 获取时间和当前操作人信息
            Date now = new Date();
            String username = DetailsHelper.getUserDetails().getUsername();
            List<PmAxisBrdTrimBtTra> insertPmAxisBrdTrimBtTraList = new ArrayList<>(pmAxisBrdTrimBtList.size());
            for (PmAxisBrdTrimBt pmAxisBrdTrimBt : pmAxisBrdTrimBtList) {
                PmAxisBrdTrimBtTra pmAxisBrdTrimBtTra = new PmAxisBrdTrimBtTra();

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

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

