package com.mcwl.myInvitation.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mcwl.common.core.redis.RedisCache;
import com.mcwl.myInvitation.domain.CommissionRatio;
import com.mcwl.myInvitation.domain.vo.CommissionRatioVo;
import com.mcwl.myInvitation.mapper.CommissionRatioMapper;
import com.mcwl.myInvitation.service.CommissionRatioService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;


@Service
@RequiredArgsConstructor
public class CommissionRatioServiceImpl extends ServiceImpl<CommissionRatioMapper, CommissionRatio> implements CommissionRatioService {


    private final RedisCache redisCache;

    @Override
    public List<CommissionRatioVo> ratioList() {
        List<CommissionRatio> list = baseMapper.selectList(null);
        if (list == null || list.isEmpty()) {
            return Collections.emptyList();
        }
        List<CommissionRatioVo> vos = new ArrayList<>();
        for (CommissionRatio commissionRatio : list) {
            CommissionRatioVo vo = getCommissionRatioVo(commissionRatio);
            vos.add(vo);
        }
        return vos;
    }

    @Override
    public CommissionRatioVo updateRatio(Long id, Double ratio) {
        CommissionRatio commissionRatio = baseMapper.selectById(id);
        if (Objects.isNull(commissionRatio)) {
            return null;
        }
        commissionRatio.setRatio(ratio);
        baseMapper.updateById(commissionRatio);

        redisCache.deleteObject("CommissionRationInviterUser");
        redisCache.deleteObject("CommissionRationMerchant");
        redisCache.deleteObject("CommissionRationCommunity");
        redisCache.deleteObject("CommissionRationFetch");

        return this.getCommissionRatioVo(commissionRatio);
    }

    @Override
    public CommissionRatioVo detail(Long id) {
        CommissionRatio commissionRatio = baseMapper.selectById(id);
        if (Objects.isNull(commissionRatio)) {
            return null;
        }
        return this.getCommissionRatioVo(commissionRatio);
    }


    private CommissionRatioVo getCommissionRatioVo(CommissionRatio commissionRatio) {
        CommissionRatioVo vo = new CommissionRatioVo();
        BeanUtil.copyProperties(commissionRatio, vo);
        vo.setRatioName(commissionRatio.getDescription());
        return vo;
    }


}
