package com.ruoyi.cai.service.impl;

import cn.hutool.core.util.NumberUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.cai.domain.*;
import com.ruoyi.cai.dto.admin.UnionCountDTO;
import com.ruoyi.cai.dto.admin.vo.UnionAdminVo;
import com.ruoyi.cai.enums.SystemConfigEnum;
import com.ruoyi.cai.manager.SystemConfigManager;
import com.ruoyi.cai.mapper.UnionMapper;
import com.ruoyi.cai.mapper.UserInfoMapper;
import com.ruoyi.cai.service.*;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.exception.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 工会列表Service业务层处理
 *
 * @author 77
 * @date 2023-12-22
 */
@Service
public class UnionServiceImpl extends ServiceImpl<UnionMapper, Union> implements UnionService {

    @Autowired
    private UnionUserService unionUserService;
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private UserService userService;
    @Autowired
    private SystemConfigManager systemConfigManager;

    @Override
    public Page<UnionAdminVo> pageAdmin(PageQuery pageQuery, UnionAdminVo bo) {
        Page<UnionAdminVo> page = baseMapper.pageAdmin(pageQuery.build(), bo);
        List<UnionAdminVo> records = page.getRecords();
        if(CollectionUtils.isEmpty(records)){
            return page;
        }
        List<Long> unionIds = records.stream().map(Union::getId).collect(Collectors.toList());
        List<UnionCountDTO> dtos = unionUserService.countByUnionIds(unionIds);
        if(dtos == null){
            return page;
        }
        Map<Long, UnionCountDTO> countMap = dtos.stream().collect(Collectors.toMap(UnionCountDTO::getUnionId, Function.identity()));
        for (UnionAdminVo record : records) {
            UnionCountDTO dto = countMap.get(record.getId());
            if(dto != null){
                record.setAllNum(dto.getAllNum());
                record.setAnchorNum(dto.getAnchorNum());
            }
        }
        return page;
    }

    @Override
    public Union getByUserId(Long userId) {
        return this.getOne(Wrappers.lambdaQuery(Union.class).eq(Union::getUserId,userId).last("limit 1"));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean dissolve(Long id) {
        Union union = this.getById(id);
        if(union == null){
            throw new ServiceException("工会不存在");
        }
        boolean b = this.removeById(id);
        if(!b){
            throw new ServiceException("工会不存在");
        }
        unionUserService.remove(Wrappers.lambdaQuery(UnionUser.class).eq(UnionUser::getUnionId,id));
        userInfoService.update(Wrappers.lambdaUpdate(UserInfo.class)
                .eq(UserInfo::getUserId,union.getUserId())
                .set(UserInfo::getVideoIncomeRate,systemConfigManager.getSystemConfigOfBigDecimal(SystemConfigEnum.DEFAULT_VIDEO_INCOME_RATE))
                .set(UserInfo::getGiftIncomeRate,systemConfigManager.getSystemConfigOfBigDecimal(SystemConfigEnum.DEFAULT_GIFT_INCOME_RATE))
                .set(UserInfo::getGuardIncomeRate,systemConfigManager.getSystemConfigOfBigDecimal(SystemConfigEnum.DEFAULT_GUARD_INCOME_RATE))
                .set(UserInfo::getPayIncomeRate,systemConfigManager.getSystemConfigOfBigDecimal(SystemConfigEnum.DEFAULT_PAY_INCOME_RATE)));
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public synchronized boolean saveUnion(String usercode) {
        User user = userService.getByUserCode(usercode);
        if(user == null){
            throw new ServiceException("用户不存在");
        }
        boolean update = userService.update(Wrappers.lambdaUpdate(User.class).eq(User::getId, user.getId())
                .eq(User::getIsUnion, 0)
                .set(User::getIsUnion, 1));
        if(!update){
            throw new ServiceException("新建工会失败，工会已存在");
        }
        Union union = new Union();
        union.setUserId(user.getId());
        union.setName("工会"+user.getUsercode());
        union.setEnableRate(true);
        this.save(union);
        BigDecimal guardIncomeRate = systemConfigManager.getSystemConfigOfBigDecimal(SystemConfigEnum.DEFAULT_GUARD_INCOME_RATE);
        BigDecimal giftIncomeRate = systemConfigManager.getSystemConfigOfBigDecimal(SystemConfigEnum.DEFAULT_GIFT_INCOME_RATE);
        BigDecimal videoIncomeRate = systemConfigManager.getSystemConfigOfBigDecimal(SystemConfigEnum.DEFAULT_VIDEO_INCOME_RATE);
        BigDecimal unionOneIncomeRate = systemConfigManager.getSystemConfigOfBigDecimal(SystemConfigEnum.DEFAULT_UNION_ONE_INCOME_RATE);
        // 将会长的比例充值成最新的
        userInfoService.update(Wrappers.lambdaUpdate(UserInfo.class)
                .eq(UserInfo::getUserId,user.getId())
                .set(UserInfo::getGiftIncomeRate, NumberUtil.add(giftIncomeRate,unionOneIncomeRate))
                .set(UserInfo::getGuardIncomeRate, NumberUtil.add(guardIncomeRate,unionOneIncomeRate))
                .set(UserInfo::getVideoIncomeRate, NumberUtil.add(videoIncomeRate,unionOneIncomeRate)));
        return true;
    }

    @Resource
    private UserInfoMapper userInfoMapper;
}
