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

import com.xisc.pm.app.service.PmPdConstBtService;
import com.xisc.pm.domain.entity.PmPdConstBt;
import com.xisc.pm.domain.entity.PmPdConstBtTra;
import com.xisc.pm.domain.repository.PmPdConstBtRepository;
import com.xisc.pm.domain.repository.PmPdConstBtTraRepository;
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;

/**
 * 组板常数基准表(PmPdConstBt)应用服务
 *
 * @author 纪文桃 wentao.ji01@hand-china.com
 * @since 2024-07-24 09:08:21
 */
@Service
public class PmPdConstBtServiceImpl implements PmPdConstBtService {

    private PmPdConstBtRepository pmPdConstBtRepository;

    private PmPdConstBtTraRepository pmPdConstBtTraRepository;

    public PmPdConstBtServiceImpl(PmPdConstBtRepository pmPdConstBtRepository, PmPdConstBtTraRepository pmPdConstBtTraRepository) {
        this.pmPdConstBtRepository = pmPdConstBtRepository;
        this.pmPdConstBtTraRepository = pmPdConstBtTraRepository;
    }

    @Override
    public Page<PmPdConstBt> selectList(PageRequest pageRequest, PmPdConstBt pmPdConstBt) {
        return PageHelper.doPageAndSort(pageRequest, () -> pmPdConstBtRepository.selectList(pmPdConstBt));
    }

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

        // 校验唯一性：产线号
        Map<String, List<PmPdConstBt>> pdconstBtMap = pmPdConstBtList.stream().collect(Collectors.groupingBy(PmPdConstBt::getRollLineNo));
        for (Map.Entry<String, List<PmPdConstBt> > entry : pdconstBtMap.entrySet()) {
            if (entry.getValue().size() > 1) {
                throw new CommonException("pm.pd_const_bt_001",entry.getKey());
            }
        }

        // 与数据库记录校验
        List<String> rollLineList = pmPdConstBtList.stream().map(PmPdConstBt::getRollLineNo).collect(Collectors.toList());
        List<Long> idList = pmPdConstBtList.stream().filter(item -> item.getPpcbId() != null).map(PmPdConstBt::getPpcbId).collect(Collectors.toList());
        List<PmPdConstBt> existPmPdConstBtList = pmPdConstBtRepository.selectByCondition(Condition.builder(PmPdConstBt.class)
                .andWhere(Sqls.custom().andIn(PmPdConstBt.FIELD_ROLL_LINE_NO, rollLineList))
                .andWhere(Sqls.custom().andEqualTo(PmPdConstBt.FIELD_TENANT_ID, tenantId))
                .andWhere(Sqls.custom().andNotIn(PmPdConstBt.FIELD_PPCB_ID, idList, true))
                .build());
        if (CollectionUtils.isNotEmpty(existPmPdConstBtList)) {
            throw new CommonException("pm.pd_const_bt_002",existPmPdConstBtList.get(0).getRollLineNo());
        }


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

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

        // 记录历史表
        for (PmPdConstBt pmPdConstBt : updateList) {
            PmPdConstBtTra pmPdConstBtTra = new PmPdConstBtTra();
            BeanUtils.copyProperties(pmPdConstBt, pmPdConstBtTra);

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

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

        for (PmPdConstBt pmPdConstBt : insertList) {
            PmPdConstBtTra pmPdConstBtTra = new PmPdConstBtTra();
            BeanUtils.copyProperties(pmPdConstBt, pmPdConstBtTra);

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

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

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

            // 获取时间和当前操作人信息
            Date now = new Date();
            String username = DetailsHelper.getUserDetails().getUsername();
            List<PmPdConstBtTra> insertPmMoldSpecBtTraList = new ArrayList<>(pmPdConstBtList.size());
            for (PmPdConstBt pmPdConstBt : pmPdConstBtList) {
                PmPdConstBtTra pmPdConstBtTra = new PmPdConstBtTra();

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

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

