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

import com.xisc.boot.common.feign.pojo.MtUserInfo;
import com.xisc.boot.common.sys.UserClient;
import com.xisc.pm.app.service.PmProdLineCoarseSocreService;
import com.xisc.pm.domain.entity.PmProdLineCoarseSocre;
import com.xisc.pm.domain.repository.PmProdLineCoarseSocreRepository;
import com.xisc.pm.domain.vo.PmProdLineCoarseSocreVO;
import com.xisc.pm.infra.mapper.PmProdLineCoarseSocreMapper;
import com.xisc.pm.infra.util.Utils;
import io.choerodon.core.domain.Page;
import io.choerodon.core.exception.CommonException;
import io.choerodon.mybatis.pagehelper.PageHelper;
import io.choerodon.mybatis.pagehelper.domain.PageRequest;
import org.apache.commons.collections.CollectionUtils;
import org.apache.logging.log4j.util.Strings;
import org.hzero.mybatis.domian.Condition;
import org.hzero.mybatis.util.Sqls;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 产线粗分表(PmProdLineCoarseSocre)应用服务
 *
 * @author 纪文桃 wentao.ji01@hand-china.com
 * @since 2024-10-11 09:06:10
 */
@Service
public class PmProdLineCoarseSocreServiceImpl implements PmProdLineCoarseSocreService {
    @Autowired
    private PmProdLineCoarseSocreRepository pmProdLineCoarseSocreRepository;

    @Autowired
    private UserClient userClient;

    @Autowired
    private PmProdLineCoarseSocreMapper pmProdLineCoarseSocreMapper;

    @Override
    public Page<PmProdLineCoarseSocre> selectList(PageRequest pageRequest, PmProdLineCoarseSocre pmProdLineCoarseSocre) {
        // 构建查询条件
        Condition.Builder builder = Condition.builder(PmProdLineCoarseSocre.class)
                .andWhere(Sqls.custom().andEqualTo(PmProdLineCoarseSocre.FIELD_TM_ROLL_PL, pmProdLineCoarseSocre.getTmRollPl(), true))
                .andWhere(Sqls.custom().andLessThanOrEqualTo(PmProdLineCoarseSocre.FIELD_LENGTH_FROM, pmProdLineCoarseSocre.getLengthFrom(), true)
                          .andLessThanOrEqualTo(PmProdLineCoarseSocre.FIELD_LENGTH_FROM, pmProdLineCoarseSocre.getLengthTo(), true)
                        .andGreaterThanOrEqualTo(PmProdLineCoarseSocre.FIELD_LENGTH_TO, pmProdLineCoarseSocre.getLengthFrom(), true)
                       .andGreaterThanOrEqualTo(PmProdLineCoarseSocre.FIELD_LENGTH_TO, pmProdLineCoarseSocre.getLengthTo(), true))
                .andWhere(Sqls.custom().andLessThanOrEqualTo(PmProdLineCoarseSocre.FIELD_THICK_FROM, pmProdLineCoarseSocre.getThickFrom(), true)
                        .andLessThanOrEqualTo(PmProdLineCoarseSocre.FIELD_THICK_FROM, pmProdLineCoarseSocre.getThickTo(), true)
                         .andGreaterThanOrEqualTo(PmProdLineCoarseSocre.FIELD_THICK_TO, pmProdLineCoarseSocre.getThickFrom(), true)
                        .andGreaterThanOrEqualTo(PmProdLineCoarseSocre.FIELD_THICK_TO, pmProdLineCoarseSocre.getThickTo(), true))
                .andWhere(Sqls.custom().andLessThanOrEqualTo(PmProdLineCoarseSocre.FIELD_WID_FROM, pmProdLineCoarseSocre.getWidFrom(), true)
                        .andLessThanOrEqualTo(PmProdLineCoarseSocre.FIELD_WID_FROM, pmProdLineCoarseSocre.getWidTo(), true)
                        .andGreaterThanOrEqualTo(PmProdLineCoarseSocre.FIELD_WID_TO, pmProdLineCoarseSocre.getWidFrom(), true)
                       .andGreaterThanOrEqualTo(PmProdLineCoarseSocre.FIELD_WID_TO, pmProdLineCoarseSocre.getWidTo(), true))
                .andWhere(Sqls.custom().andEqualTo(PmProdLineCoarseSocre.FIELD_TM_ROLL_PL, pmProdLineCoarseSocre.getTmRollPl(), true))
                .andWhere(Sqls.custom().andEqualTo(PmProdLineCoarseSocre.FIELD_TENANT_ID, pmProdLineCoarseSocre.getTenantId()));
        Page<PmProdLineCoarseSocre> page = PageHelper.doPageAndSort(pageRequest, () -> pmProdLineCoarseSocreRepository.selectByCondition(builder.build()));
        // 未查询到则返回
        if (CollectionUtils.isEmpty(page.getContent())) {
            return new Page<>();
        }

        List<String> tmRollPlList = page.getContent().stream().map(PmProdLineCoarseSocre::getTmRollPl).distinct()
                .collect(Collectors.toList());

        // 获取轧制产线号对应的合同重量
       List<PmProdLineCoarseSocreVO> pmProdLineCoarseSocreVOList = pmProdLineCoarseSocreMapper.selectOrderWtByTmRollPl(tmRollPlList, pmProdLineCoarseSocre.getTenantId());

        // 初始化一个用户ID列表，用于存储生产线路的创建人和最后更新人的用户ID
        List<Long> userIds = new ArrayList<>(16);
        // 添加创建人的用户ID到用户ID列表中
        userIds.addAll(page.getContent().stream().map(PmProdLineCoarseSocre::getCreatedBy).distinct().collect(Collectors.toList()));
        // 添加最后更新人的用户ID到用户ID列表中
        userIds.addAll(page.getContent().stream().map(PmProdLineCoarseSocre::getLastUpdatedBy).distinct().collect(Collectors.toList()));

        // 调用userClient的userInfoBatchGet方法，批量获取用户信息
        Map<Long, MtUserInfo> mtUserInfoMap = userClient.userInfoBatchGet(pmProdLineCoarseSocre.getTenantId(), userIds);

        for (PmProdLineCoarseSocre prodLineCoarseSocre : page.getContent()) {
            // 用户信息
            if (!mtUserInfoMap.isEmpty() && mtUserInfoMap.containsKey(prodLineCoarseSocre.getCreatedBy())) {
                MtUserInfo mtUserInfo = mtUserInfoMap.get(prodLineCoarseSocre.getCreatedBy());
                prodLineCoarseSocre.setCreatedByName(Strings.concat(mtUserInfo.getLoginName(), mtUserInfo.getRealName()));
            }
            if (!mtUserInfoMap.isEmpty() && mtUserInfoMap.containsKey(prodLineCoarseSocre.getLastUpdatedBy())) {
                MtUserInfo updateUserInfo = mtUserInfoMap.get(prodLineCoarseSocre.getLastUpdatedBy());
                prodLineCoarseSocre.setLastUpdatedByName(Strings.concat(updateUserInfo.getLoginName(), updateUserInfo.getRealName()));
            }

            if (CollectionUtils.isEmpty(pmProdLineCoarseSocreVOList)) {
                continue;
            }

            // 计算总计合同重量
            BigDecimal orderWt = pmProdLineCoarseSocreVOList.stream().filter(item -> item.getTmRollPl().equals(prodLineCoarseSocre.getTmRollPl()) &&
                            item.getThickFrom().equals(prodLineCoarseSocre.getThickFrom()) &&
                            item.getThickTo().equals(prodLineCoarseSocre.getThickTo()) &&
                            item.getWidFrom().equals(prodLineCoarseSocre.getWidFrom()) &&
                            item.getWidTo().equals(prodLineCoarseSocre.getWidTo()) &&
                            item.getLengthFrom().equals(prodLineCoarseSocre.getLengthFrom()) &&
                            item.getLengthTo().equals(prodLineCoarseSocre.getLengthTo())).map(PmProdLineCoarseSocreVO::getOrderWt)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            if (orderWt.compareTo(BigDecimal.ZERO) != 0) {
                prodLineCoarseSocre.setTotalOrderNoWt(orderWt);
            }
        }
        return page;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveData(List<PmProdLineCoarseSocre> pmProdLineCoarseSocreList) {
        // 新增记录之间判断是否交叉
        Map<String, List<PmProdLineCoarseSocre>> coarseScoreMap = pmProdLineCoarseSocreList.stream()
                .collect(Collectors.groupingBy(PmProdLineCoarseSocre::getTmRollPl));
        for (Map.Entry<String, List<PmProdLineCoarseSocre>> entry : coarseScoreMap.entrySet()) {
            List<PmProdLineCoarseSocre> coarseScoreList = entry.getValue();
            for (int i = 0; i < coarseScoreList.size() - 1; i++) {
                for (int j = i + 1; j < coarseScoreList.size(); j++) {
                    // 校验长度规格区间是否交叉
                    boolean lengthIntervalCheck = Utils.isIntersect(coarseScoreList.get(i).getLengthFrom(), coarseScoreList.get(i).getLengthTo(),
                            coarseScoreList.get(j).getLengthFrom(), coarseScoreList.get(j).getLengthTo());
                    if (lengthIntervalCheck) {
                        throw new CommonException("pm.prod_line_coarse_socre_003",coarseScoreList.get(i).getTmRollPl(), coarseScoreList.get(i).getLengthFrom(), coarseScoreList.get(i).getLengthTo(),
                                coarseScoreList.get(j).getLengthFrom(), coarseScoreList.get(j).getLengthTo());
                    }

                    // 校验厚度规格区间是否交叉
                    boolean thickIntervalCheck = Utils.isIntersect(coarseScoreList.get(i).getThickFrom(), coarseScoreList.get(i).getThickTo(),
                            coarseScoreList.get(j).getThickFrom(), coarseScoreList.get(j).getThickTo());
                    if (thickIntervalCheck) {
                        throw new CommonException("pm.prod_line_coarse_socre_001",coarseScoreList.get(i).getTmRollPl(), coarseScoreList.get(i).getThickFrom(), coarseScoreList.get(i).getThickTo(),
                                coarseScoreList.get(j).getThickFrom(), coarseScoreList.get(j).getThickTo());
                    }

                    // 校验宽度规格区间是否交叉
                    boolean widIntervalCheck = Utils.isIntersect(coarseScoreList.get(i).getWidFrom(), coarseScoreList.get(i).getWidTo(),
                            coarseScoreList.get(j).getWidFrom(), coarseScoreList.get(j).getWidTo());
                    if (widIntervalCheck) {
                        throw new CommonException("pm.prod_line_coarse_socre_002",coarseScoreList.get(i).getTmRollPl(), coarseScoreList.get(i).getWidFrom(), coarseScoreList.get(i).getWidTo(),
                                coarseScoreList.get(j).getWidFrom(), coarseScoreList.get(j).getWidTo());
                    }
                }
            }
        }

        // 与数据库的记录校验
        List<String> tmRollPlList = pmProdLineCoarseSocreList.stream().map(PmProdLineCoarseSocre::getTmRollPl).
                distinct().collect(Collectors.toList());
        List<Long> idList = pmProdLineCoarseSocreList.stream().filter(item->item.getProdLineCoarseId() != null).map(PmProdLineCoarseSocre::getProdLineCoarseId).collect(Collectors.toList());
        List<PmProdLineCoarseSocre> prodLineCoarseSocreList = pmProdLineCoarseSocreRepository.selectByCondition(Condition.builder(PmProdLineCoarseSocre.class)
                .andWhere(Sqls.custom().andIn(PmProdLineCoarseSocre.FIELD_TM_ROLL_PL, tmRollPlList))
                .andWhere(Sqls.custom().andEqualTo(PmProdLineCoarseSocre.FIELD_TENANT_ID, pmProdLineCoarseSocreList.get(0).getTenantId()))
                .andWhere(Sqls.custom().andNotIn(PmProdLineCoarseSocre.FIELD_PROD_LINE_COARSE_ID, idList, true))
                .build());
        if (CollectionUtils.isNotEmpty(prodLineCoarseSocreList)) {
            Map<String, List<PmProdLineCoarseSocre>> prodLineCoarseSocreMap = prodLineCoarseSocreList.stream()
                    .collect(Collectors.groupingBy(PmProdLineCoarseSocre::getTmRollPl));
            for (PmProdLineCoarseSocre pmProdLineCoarseSocre : pmProdLineCoarseSocreList) {
                if (prodLineCoarseSocreMap.containsKey(pmProdLineCoarseSocre.getTmRollPl())) {
                    for (PmProdLineCoarseSocre prodLineCoarseSocre : prodLineCoarseSocreMap.get(pmProdLineCoarseSocre.getTmRollPl())) {
                        // 校验长度规格区间是否交叉
                        boolean lengthIntervalCheck = Utils.isIntersect(pmProdLineCoarseSocre.getLengthFrom(), pmProdLineCoarseSocre.getLengthTo(),
                                prodLineCoarseSocre.getLengthFrom(), prodLineCoarseSocre.getLengthTo());
                        if (lengthIntervalCheck) {
                            throw new CommonException("pm.prod_line_coarse_socre_003",pmProdLineCoarseSocre.getTmRollPl(), pmProdLineCoarseSocre.getLengthFrom(), pmProdLineCoarseSocre.getLengthTo(),
                                    prodLineCoarseSocre.getLengthFrom(), prodLineCoarseSocre.getLengthTo());
                        }

                        // 校验厚度规格区间是否交叉
                        boolean thickIntervalCheck = Utils.isIntersect(pmProdLineCoarseSocre.getThickFrom(), pmProdLineCoarseSocre.getThickTo(),
                                prodLineCoarseSocre.getThickFrom(), prodLineCoarseSocre.getThickTo());
                        if (thickIntervalCheck) {
                            throw new CommonException("pm.prod_line_coarse_socre_001", pmProdLineCoarseSocre.getTmRollPl(), pmProdLineCoarseSocre.getThickFrom(), pmProdLineCoarseSocre.getThickTo(),
                                    prodLineCoarseSocre.getThickFrom(), prodLineCoarseSocre.getThickTo());
                        }

                        // 校验宽度规格区间是否交叉
                        boolean widIntervalCheck = Utils.isIntersect(pmProdLineCoarseSocre.getWidFrom(), pmProdLineCoarseSocre.getWidTo(),
                                prodLineCoarseSocre.getWidFrom(), prodLineCoarseSocre.getWidTo());
                        if (widIntervalCheck) {
                            throw new CommonException("pm.prod_line_coarse_socre_002", pmProdLineCoarseSocre.getTmRollPl(), pmProdLineCoarseSocre.getWidFrom(), pmProdLineCoarseSocre.getWidTo(),
                                    prodLineCoarseSocre.getWidFrom(), prodLineCoarseSocre.getWidTo());
                        }

                    }
                }
            }
        }

        // 更新或者保存
        List<PmProdLineCoarseSocre> insertList = pmProdLineCoarseSocreList.stream().filter(line -> line.getProdLineCoarseId() == null).collect(Collectors.toList());
        List<PmProdLineCoarseSocre> updateList = pmProdLineCoarseSocreList.stream().filter(line -> line.getProdLineCoarseId() != null).collect(Collectors.toList());
        pmProdLineCoarseSocreRepository.batchInsertSelective(insertList);
        pmProdLineCoarseSocreRepository.batchUpdateByPrimaryKeySelective(updateList);
    }
}

