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

import com.xisc.pm.app.service.PmIngotCutLenBtService;
import com.xisc.pm.domain.entity.PmIngotCutLenBtTra;
import com.xisc.pm.domain.entity.PmIngotCutLenBt;
import com.xisc.pm.domain.repository.PmIngotCutLenBtTraRepository;
import com.xisc.pm.domain.repository.PmIngotCutLenBtRepository;
import com.xisc.pm.infra.util.Utils;
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;

/**
 * 钢锭切缝量基准表(PmIngotCutLenBt)应用服务
 *
 * @author 蒋雨航 yuhang.jiang02@hand-china.com
 * @since 2024-09-05 15:18:17
 */
@Service
public class PmIngotCutLenBtServiceImpl implements PmIngotCutLenBtService {

    private PmIngotCutLenBtRepository pmIngotCutLenBtRepository;

    private PmIngotCutLenBtTraRepository pmIngotCutLenBtTraRepository;

    public PmIngotCutLenBtServiceImpl(PmIngotCutLenBtRepository pmIngotCutLenBtRepository, PmIngotCutLenBtTraRepository pmIngotCutLenBtTraRepository) {
        this.pmIngotCutLenBtRepository = pmIngotCutLenBtRepository;
        this.pmIngotCutLenBtTraRepository = pmIngotCutLenBtTraRepository;
    }

    @Override
    public Page<PmIngotCutLenBt> selectList(PageRequest pageRequest, PmIngotCutLenBt pmIngotCutLenBt) {
        return PageHelper.doPageAndSort(pageRequest, () -> pmIngotCutLenBtRepository.selectList(pmIngotCutLenBt));
    }

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

        // 新增记录之间校验区间是否交叉
        for (int i = 0; i < pmIngotCutLenBtList.size() - 1; i++) {
            for (int j = i + 1; j < pmIngotCutLenBtList.size(); j++) {
                // 校验钢板厚度区间是否交叉
                boolean plateThickIntervalCheck = Utils.isIntersect(pmIngotCutLenBtList.get(i).getPlateThickFrom(),
                        pmIngotCutLenBtList.get(i).getPlateThickTo(), pmIngotCutLenBtList.get(j).getPlateThickFrom(),
                        pmIngotCutLenBtList.get(j).getPlateThickTo());
                if (plateThickIntervalCheck) {
                    throw new CommonException("pm.cut_place_bt_006", pmIngotCutLenBtList.get(j).getPlateThickFrom(),
                            pmIngotCutLenBtList.get(j).getPlateThickTo());
                }
            }
        }
        // 与数据库记录校验区间是否交叉
        List<Long> idList = pmIngotCutLenBtList.stream().filter(item -> item.getPiclbId() != null).map(PmIngotCutLenBt::getPiclbId).collect(Collectors.toList());
        List<PmIngotCutLenBt> exisPmIgnotCutLenBtList = pmIngotCutLenBtRepository.selectByCondition(Condition.builder(PmIngotCutLenBt.class)
                .andWhere(Sqls.custom().andEqualTo(PmIngotCutLenBt.FIELD_TENANT_ID, tenantId))
                .andWhere(Sqls.custom().andNotIn(PmIngotCutLenBt.FIELD_PICLB_ID, idList, true))
                .build());
        if (CollectionUtils.isNotEmpty(exisPmIgnotCutLenBtList)) {
            for (int i = 0; i < pmIngotCutLenBtList.size(); i++) {
                for (int j = 0; j < exisPmIgnotCutLenBtList.size(); j++) {
                    // 校验钢板厚度区间是否交叉
                    boolean rollThickIntervalCheck = Utils.isIntersect(pmIngotCutLenBtList.get(i).getPlateThickFrom(),
                            pmIngotCutLenBtList.get(i).getPlateThickTo(), exisPmIgnotCutLenBtList.get(j).getPlateThickFrom(),
                            exisPmIgnotCutLenBtList.get(j).getPlateThickTo());
                    if (rollThickIntervalCheck) {
                        throw new CommonException("pm.cut_place_bt_001", exisPmIgnotCutLenBtList.get(j).getPlateThickFrom(),
                                exisPmIgnotCutLenBtList.get(j).getPlateThickTo());
                    }
                }
            }
        }

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

        List<PmIngotCutLenBt> insertList = pmIngotCutLenBtList.stream().filter(line -> line.getPiclbId() == null).collect(Collectors.toList());
        List<PmIngotCutLenBt> updateList = pmIngotCutLenBtList.stream().filter(line -> line.getPiclbId() != null).collect(Collectors.toList());

        // 记录历史表
        for (PmIngotCutLenBt pmIngotCutLenBt : updateList) {
            PmIngotCutLenBtTra pmIngotCutLenBtTra = new PmIngotCutLenBtTra();
            BeanUtils.copyProperties(pmIngotCutLenBt, pmIngotCutLenBtTra);

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

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

        for (PmIngotCutLenBt pmIngotCutLenBt : insertList) {
            PmIngotCutLenBtTra pmIngotCutLenBtTra = new PmIngotCutLenBtTra();
            BeanUtils.copyProperties(pmIngotCutLenBt, pmIngotCutLenBtTra);

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

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

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

            // 获取当前时间和用户账号
            Date now = new Date();
            String username = DetailsHelper.getUserDetails().getUsername();
            List<PmIngotCutLenBtTra> insertPmMoldSpecBtTraList = new ArrayList<>(pmIngotCutLenBtList.size());
            for (PmIngotCutLenBt pmIngotCutLenBt : pmIngotCutLenBtList) {
                PmIngotCutLenBtTra pmIngotCutLenBtTra = new PmIngotCutLenBtTra();

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

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

