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

import com.xisc.pm.app.service.PmIngotYieldBtService;
import com.xisc.pm.domain.entity.PmIngotYieldBt;
import com.xisc.pm.domain.entity.PmIngotYieldBtTra;
import com.xisc.pm.domain.repository.PmIngotYieldBtRepository;
import com.xisc.pm.domain.repository.PmIngotYieldBtTraRepository;
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.stream.Collectors;

/**
 * 钢锭收得率基准表(PmIngotYieldBt)应用服务
 *
 * @author 蒋雨航 yuhang.jiang02@hand-china.com
 * @since 2024-09-05 15:20:30
 */
@Service
public class PmIngotYieldBtServiceImpl implements PmIngotYieldBtService {

    private PmIngotYieldBtRepository pmIngotYieldBtRepository;

    private PmIngotYieldBtTraRepository pmIngotYieldBtTraRepository;

    public PmIngotYieldBtServiceImpl(PmIngotYieldBtRepository pmIngotYieldBtRepository, PmIngotYieldBtTraRepository pmIngotYieldBtTraRepository) {
        this.pmIngotYieldBtRepository = pmIngotYieldBtRepository;
        this.pmIngotYieldBtTraRepository = pmIngotYieldBtTraRepository;
    }

    @Override
    public Page<PmIngotYieldBt> selectList(PageRequest pageRequest, PmIngotYieldBt pmIngotYieldBt) {
        return PageHelper.doPageAndSort(pageRequest, () -> pmIngotYieldBtRepository.selectList(pmIngotYieldBt));
    }

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

        // 校验数据唯一性
        List<String> ingotTypeList = pmIngotYieldBtList.stream().map(PmIngotYieldBt::getIngotType).distinct().collect(Collectors.toList());
        if (ingotTypeList.size() < pmIngotYieldBtList.size()) {
            throw new CommonException("pm.ingot_yield_bt_001");
        }
        List<PmIngotYieldBt> existIngotYieldBtList = pmIngotYieldBtRepository.selectByCondition(Condition.builder(PmIngotYieldBt.class)
                .andWhere(Sqls.custom().andIn(PmIngotYieldBt.FIELD_INGOT_TYPE, ingotTypeList))
                .andWhere(Sqls.custom().andEqualTo(PmIngotYieldBt.FIELD_TENANT_ID, tenantId)).build());
        if (CollectionUtils.isNotEmpty(existIngotYieldBtList)) {
            throw new CommonException("pm.ingot_yield_bt_002", existIngotYieldBtList.get(0).getIngotType());
        }

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

        List<PmIngotYieldBt> insertList = pmIngotYieldBtList.stream().filter(line -> line.getPiybId() == null).collect(Collectors.toList());
        List<PmIngotYieldBt> updateList = pmIngotYieldBtList.stream().filter(line -> line.getPiybId() != null).collect(Collectors.toList());

        // 记录历史表
        for (PmIngotYieldBt pmIgnotYieldBt : updateList) {
            PmIngotYieldBtTra pmIngotYieldBtTra = new PmIngotYieldBtTra();
            BeanUtils.copyProperties(pmIgnotYieldBt, pmIngotYieldBtTra);

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

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

        for (PmIngotYieldBt pmIgnotYieldBt : insertList) {
            PmIngotYieldBtTra pmIngotYieldBtTra = new PmIngotYieldBtTra();
            BeanUtils.copyProperties(pmIgnotYieldBt, pmIngotYieldBtTra);

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

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

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

            // 获取时间和当前操作人信息
            Date now = new Date();
            String username = DetailsHelper.getUserDetails().getUsername();
            List<PmIngotYieldBtTra> insertPmMoldSpecBtTraList = new ArrayList<>(pmIngotYieldBtList.size());
            for (PmIngotYieldBt pmIngotYieldBt : pmIngotYieldBtList) {
                PmIngotYieldBtTra pmIngotYieldBtTra = new PmIngotYieldBtTra();

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

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

