package cn.iocoder.foodnexus.module.operations.service.scoringweight;

import cn.iocoder.foodnexus.framework.common.enums.UserSystemEnum;
import cn.iocoder.foodnexus.framework.common.util.CommonUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import jakarta.validation.Valid;
import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import java.math.BigDecimal;
import java.util.*;
import cn.iocoder.foodnexus.module.operations.controller.admin.scoringweight.vo.*;
import cn.iocoder.foodnexus.module.operations.dal.dataobject.scoringweight.ScoringWeightDO;
import cn.iocoder.foodnexus.framework.common.pojo.PageResult;
import cn.iocoder.foodnexus.framework.common.util.object.BeanUtils;

import cn.iocoder.foodnexus.module.operations.dal.mysql.scoringweight.ScoringWeightMapper;

import static cn.iocoder.foodnexus.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.foodnexus.framework.common.util.collection.CollectionUtils.convertList;
import static cn.iocoder.foodnexus.module.operations.enums.ErrorCodeConstants.*;

/**
 * 评分权重 Service 实现类
 *
 * @author 超级管理员
 */
@Service
@Validated
public class ScoringWeightServiceImpl implements ScoringWeightService {

    @Resource
    private ScoringWeightMapper scoringWeightMapper;

    @Override
    public Long createScoringWeight(ScoringWeightSaveReqVO createReqVO) {
        // 插入
        ScoringWeightDO scoringWeight = BeanUtils.toBean(createReqVO, ScoringWeightDO.class);
        scoringWeightMapper.insert(scoringWeight);

        // 返回
        return scoringWeight.getId();
    }

    @Override
    public void updateScoringWeight(@Valid ScoringWeightUpateReqVO updateReqVO) {
        // 校验存在
        validateScoringWeightExists(updateReqVO.getId());
        // 更新
        ScoringWeightDO updateObj = BeanUtils.toBean(updateReqVO, ScoringWeightDO.class);
        scoringWeightMapper.updateById(updateObj);
    }

    @Override
    public void deleteScoringWeight(Long id) {
        // 校验存在
        validateScoringWeightExists(id);
        // 删除
        scoringWeightMapper.deleteById(id);
    }

    @Override
        public void deleteScoringWeightListByIds(List<Long> ids) {
        // 删除
        scoringWeightMapper.deleteByIds(ids);
        }


    private void validateScoringWeightExists(Long id) {
        if (scoringWeightMapper.selectById(id) == null) {
            throw exception(SCORING_WEIGHT_NOT_EXISTS);
        }
    }

    @Override
    public ScoringWeightDO getScoringWeight(Long id) {
        return scoringWeightMapper.selectById(id);
    }

    @Override
    public PageResult<ScoringWeightDO> getScoringWeightPage(ScoringWeightPageReqVO pageReqVO) {
        return scoringWeightMapper.selectPage(pageReqVO);
    }

    @Override
    public List<ScoringWeightDO> queryByUserSystem(UserSystemEnum userSystemEnum) {
        return scoringWeightMapper.selectList(Wrappers.<ScoringWeightDO>lambdaQuery()
                .eq(ScoringWeightDO::getIsDisplay, Boolean.TRUE)
                .eq(ScoringWeightDO::getUserSystem, userSystemEnum.getKey())
                .orderByAsc(ScoringWeightDO::getSort));
    }

    /**
     * 设置权重
     *
     * @param reqVO
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void edit(ScoringWeightEditReqVO reqVO) {
        Long allCount = scoringWeightMapper.selectCount();
        if (reqVO.getEditItems().size() != allCount) {
            throw exception(SCORING_WEIGHT_LIST_ERROR);
        }
        double sum = reqVO.getEditItems().stream().mapToDouble(item ->
                item.getWeightRatio().doubleValue()).sum();
        if (sum != 100) {
            throw exception(SCORING_WEIGHT_WEIGHTRATIO_ERROR);
        }

        List<ScoringWeightDO> allData = scoringWeightMapper.selectList();
        Map<Long, BigDecimal> itemMap = CommonUtil.listConvertMap(reqVO.getEditItems(), ScoringWeightEditReqVO.EditItems::getId, ScoringWeightEditReqVO.EditItems::getWeightRatio);

        List<ScoringWeightDO> scoringWeightDOS = CommonUtil.listConvert(allData, data -> {
            ScoringWeightDO scoringWeightDO = new ScoringWeightDO();
            scoringWeightDO.setId(data.getId());
            scoringWeightDO.setWeightRatio(itemMap.getOrDefault(data.getId(), BigDecimal.ZERO));
            return scoringWeightDO;
        });
        scoringWeightMapper.updateBatch(scoringWeightDOS);
    }

    @Override
    public List<ScoringWeightDO> listAll() {
        return scoringWeightMapper.selectList(Wrappers.<ScoringWeightDO>lambdaQuery()
                .eq(ScoringWeightDO::getWebDisplay, Boolean.TRUE)
                .orderByAsc(ScoringWeightDO::getSort));
    }

}