package com.vote.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.vctgo.common.core.text.Convert;
import com.vctgo.common.core.utils.ServletUtils;
import com.vctgo.common.mybatisplus.constant.MybatisPageConstants;
import com.vote.system.domain.VoteRule;
import com.vote.system.domain.VoteScoringItem;
import com.vote.system.domain.dto.VoteScoringItemDto;
import com.vote.system.mapper.VoteRuleMapper;
import com.vote.system.mapper.VoteScoringItemMapper;
import com.vote.system.service.VoteRuleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.Date;
import java.util.List;

import static com.vote.system.util.ConstantUtils.IS_DELETED_0;

/**
 * @author MacBook
 * @description 针对表【vote_rule(规则表)】的数据库操作Service实现
 * @createDate 2024-08-06 15:38:50
 */
@Service
public class VoteRuleServiceImpl extends ServiceImpl<VoteRuleMapper, VoteRule>
        implements VoteRuleService {

    @Autowired
    private VoteRuleMapper voteRuleMapper;

    @Autowired
    private VoteScoringItemMapper voteScoringItemMapper;

    @Override
    public IPage<VoteRule> selectRulePage(VoteRule voteRule) {
        Page mpPage = new Page(Convert.toLong(ServletUtils.getParameterToInt(MybatisPageConstants.PAGE_NUM), 1L)
                , Convert.toLong(ServletUtils.getParameterToInt(MybatisPageConstants.PAGE_SIZE), 10L));
        LambdaQueryWrapper<VoteRule> wrapper = new LambdaQueryWrapper<>();
        if (voteRule.getKeyword() != null && !voteRule.getKeyword().trim().isEmpty()) {
            wrapper.like(VoteRule::getName, voteRule.getKeyword());
        }
        wrapper.eq(VoteRule::getIsDeleted, IS_DELETED_0);
        wrapper.orderByDesc(VoteRule::getUpdateTime);
        return voteRuleMapper.selectPage(mpPage, wrapper);
    }

    @Override
    public VoteScoringItemDto selectByRuleId(Integer ruleId) {
        VoteScoringItemDto itemDto = new VoteScoringItemDto();
        LambdaQueryWrapper<VoteScoringItem> wrapper = new LambdaQueryWrapper<>();
        VoteRule voteRule = voteRuleMapper.selectById(ruleId);
        if (voteRule.getRuleId() != null) {
            wrapper.eq(VoteScoringItem::getRuleId, voteRule.getRuleId());
        }
        List<VoteScoringItem> voteScoringItems = voteScoringItemMapper.selectList(wrapper);
        itemDto.setItems(voteScoringItems);
        itemDto.setName(voteRule.getName());
        // 计算评分项总分数
        double score = voteScoringItems.stream()
                .mapToDouble(VoteScoringItem::getScore)
                .sum();
        itemDto.setAggregate(score);
        return itemDto;
    }


    @Override
    @Transactional
    public int updateRule(VoteRule voteRule) {
        // 参数校验：ruleId 不能为空
        if (voteRule.getRuleId() == null) {
            throw new IllegalArgumentException("规则Id不能为空");
        }
        // 获取现有规则
        VoteRule existingRule = voteRuleMapper.selectById(voteRule.getRuleId());
        if (existingRule.getName().equals(voteRule.getName())) {
            throw new IllegalArgumentException("规则Id不能为空");
        }
        // 校验是否尝试修改评分项数量或总分值
        if (!existingRule.getTotal().equals(voteRule.getTotal())) {
            throw new IllegalArgumentException("不允许修改评分项数量");
        }
        if (existingRule.getAggregate() != voteRule.getAggregate()) {
            throw new IllegalArgumentException("不允许修改总分值");
        }
        extracted(voteRule);
        // 更新数据库中的记录
        return voteRuleMapper.updateById(existingRule);

    }

    /**
     * 添加
     *
     * @param voteRule
     * @return
     */
    @Override
    @Transactional
    public Long insertRule(VoteRule voteRule) {
        voteRule.setAggregate(0.0);
        voteRule.setTotal(0);
        voteRule.setIsDeleted("0");
        voteRule.setCreatTime(new Date());
        voteRule.setUpdateTime(new Date());

        extracted(voteRule);
        voteRuleMapper.insert(voteRule);
        return voteRule.getRuleId();
    }

    private void extracted(VoteRule voteRule) {
        LambdaQueryWrapper<VoteRule> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(VoteRule::getName, voteRule.getName().trim());
        List<VoteRule> voteRules = voteRuleMapper.selectList(wrapper);
        if (voteRules.size() > 0) {
            throw new RuntimeException("存在重复规则表单，添加失败");

        }
    }

    /**
     * 删除
     *
     * @param ruleId
     * @return
     */
    @Override
    public int deleteRuleByRuleIds(Integer ruleId) {
        // 查询该规则下是否存在子项
        LambdaQueryWrapper<VoteScoringItem> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(VoteScoringItem::getRuleId, ruleId);
        voteScoringItemMapper.delete(queryWrapper);
        return voteRuleMapper.deleteById(ruleId);
    }

    /**
     * 下拉框回显
     *
     * @param searchValue
     * @return
     */
    @Override
    public List<VoteRule> selectSearch(String searchValue) {
        LambdaQueryWrapper<VoteRule> wrapper = new LambdaQueryWrapper<>();
        if (searchValue == null || searchValue.isEmpty()) {
            wrapper.orderByDesc(VoteRule::getUpdateTime);
        } else {
            wrapper.like(VoteRule::getName, searchValue);
        }
        List<VoteRule> voteRules = voteRuleMapper.selectList(wrapper);
        return voteRules.size() > 20 ? voteRules.subList(0, 20) : voteRules;
    }


}




