package com.jwipc.supplier.logic.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.jwipc.aggregation.ModelAggregationService;
import com.jwipc.constant.FlagConst;
import com.jwipc.page.PageUtil;
import com.jwipc.page.PageView;
import com.jwipc.security.LoginUtil;
import com.jwipc.supplier.constant.SupplierPurchaseCategoryReportStatus;
import com.jwipc.supplier.convert.SupplierSqeScoreConvert;
import com.jwipc.supplier.dto.SupplierSqeScoreBaseDTO;
import com.jwipc.supplier.entity.SupplierPurchaseCategory;
import com.jwipc.supplier.entity.SupplierSqeScore;
import com.jwipc.supplier.logic.SupplierSqeScoreLogic;
import com.jwipc.supplier.service.ISupplierPurchaseCategoryService;
import com.jwipc.supplier.service.ISupplierSqeScoreService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;


/**
 * <p> </p>
 *
 * @author BOGON
 * @version 1.0
 * @since JDK 1.8
 */
@Service
@RequiredArgsConstructor
public class SupplierSqeScoreLogicImpl implements SupplierSqeScoreLogic {
    private final ISupplierSqeScoreService supplierSqeScoreService;
    private final SupplierSqeScoreConvert supplierSqeScoreConvert;
    private final ModelAggregationService modelAggregationService;
    private final ISupplierPurchaseCategoryService supplierPurchaseCategoryService;


    @Override
    public PageView list(Long supplierId) {
        final List<SupplierSqeScore> list = supplierSqeScoreService.list(new LambdaQueryWrapper<SupplierSqeScore>()
                .eq(SupplierSqeScore::getSupplierId, supplierId));
        List<SupplierSqeScoreBaseDTO> dtos = supplierSqeScoreConvert.entities2Dtos(list);
        modelAggregationService.processRelationAggregation(dtos);
        return PageUtil.getPV(dtos, dtos.size());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveOrUpdate(List<SupplierSqeScoreBaseDTO> supplierSqeScoreBaseDTOS, Long supplierId,
                             Integer manufacturerFlag)
    {
        List<SupplierSqeScore> supplierSqeScores = supplierSqeScoreConvert.dtos2Entities(supplierSqeScoreBaseDTOS);
        if (CollUtil.isEmpty(supplierSqeScores)) {
            //需要把sqe评分都删除
            supplierSqeScoreService.remove(
                    new LambdaQueryWrapper<SupplierSqeScore>().eq(SupplierSqeScore::getSupplierId, supplierId));
        } else {
            supplierSqeScores.stream().filter(a -> Objects.isNull(a.getId()))
                    .forEach(a -> {
                        a.setCreateTime(LocalDateTime.now());
                        a.setCreateId(LoginUtil.getUserId());
                    });
            final List<SupplierSqeScore> dbList = supplierSqeScoreService.list(
                    new LambdaQueryWrapper<SupplierSqeScore>().eq(SupplierSqeScore::getSupplierId, supplierId));
            //需要匹配，把本次提交的数据id全部拿到，数据库原始数据 id 跟本次提交的数据的id进行匹配，如果数据库有，本次提交没有，就需要删除
            final List<Long> currentIds
                    = supplierSqeScores.stream().map(SupplierSqeScore::getId).toList();
            final List<Long> dbIds = dbList.stream().map(SupplierSqeScore::getId).toList();
            final List<Long> delIds = dbIds.stream().filter(a -> !currentIds.contains(a)).collect(Collectors.toList());
            if (CollUtil.isNotEmpty(delIds)) {
                supplierSqeScoreService.removeBatchByIds(delIds);
            }
            supplierSqeScores.forEach(a -> {
                //需要计算总分
                /**
                 * ($QSA评分$ + $QPA评分$) / 2*0.4 + $采购价格评分$ * 0.2 + $采购交期评分$* 0.2 + $研发评分$* 0.2
                 */
                //如果是制造商按照公式计算
                if (manufacturerFlag == FlagConst.Y.getCode()) {
                    final BigDecimal totalScore = a.getQsaScore().add(a.getQpaScore()).divide(BigDecimal.valueOf(2),
                                    4, RoundingMode.DOWN).multiply(BigDecimal.valueOf(0.4))
                            .add(a.getPurchasePriceScore().multiply(BigDecimal.valueOf(0.2)))
                            .add(a.getPurchaseScore().multiply(BigDecimal.valueOf(0.2))
                                    .add(a.getRdScore().multiply(BigDecimal.valueOf(0.2))));
                    a.setTotalScore(totalScore.setScale(2, RoundingMode.HALF_UP));
                } else {
                    a.setTotalScore(a.getNonManufacturerPurchaseScore());
                }
            });
            supplierSqeScoreService.saveOrUpdateBatch(supplierSqeScores);
            //需要增加判断，如果供应商有品类的认证报告已经上传了，现在也有评分了，就需要把状态改成SQE已处理
            supplierPurchaseCategoryService.update(new LambdaUpdateWrapper<>(SupplierPurchaseCategory.class)
                    .eq(SupplierPurchaseCategory::getSupplierId, supplierId)
                    .eq(SupplierPurchaseCategory::getReportFlag, SupplierPurchaseCategoryReportStatus.UPLOAD.getCode())
                    .set(SupplierPurchaseCategory::getReportFlag, SupplierPurchaseCategoryReportStatus.OK.getCode()));
        }
    }
}