package com.kxs.user.biz.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
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.kxs.common.core.constant.CommonConstants;
import com.kxs.common.core.constant.enums.KindTypeEnum;
import com.kxs.common.mybatis.handler.MonthTableNameHandler;
import com.kxs.common.security.util.SecurityUtils;
import com.kxs.user.api.dto.kxsapp.userAccount.UserAmountVariationListDTO;
import com.kxs.user.api.model.KxsUser;
import com.kxs.user.api.model.KxsUserAmountLog;
import com.kxs.user.api.vo.kxsapp.userAccount.*;
import com.kxs.user.biz.mapper.KxsUserAmountLogMapper;
import com.kxs.user.biz.mapper.KxsUserMapper;
import com.kxs.user.biz.service.KxsUserAmountLogService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 用户余额记录日志表(KxsUserAmountLog)表服务实现类
 *
 * @author 系统
 * @since 2024-01-03 09:39:56
 */
@Service("kxsUserAmountLogService")
@RequiredArgsConstructor
public class KxsUserAmountLogServiceImpl extends ServiceImpl<KxsUserAmountLogMapper, KxsUserAmountLog> implements KxsUserAmountLogService {

    private final KxsUserMapper userMapper;

    @Override
    public IPage<UserAmountVariationListVO> getByPage(Page<UserAmountVariationListVO> page, UserAmountVariationListDTO param) {

        param.setUserId(SecurityUtils.getUser().getId());
        //拼接表名
        String tableName = CommonConstants.KXS_USER_AMOUNT_LOG_PREFIX + param.getTradeMonth();

        return baseMapper.getByPage(page, param, tableName);
    }

    @Override
    public AmountInExpendTotalVO amountInExpendTotal(UserAmountVariationListDTO param) {

        AmountInExpendTotalVO amountInExpendTotalVO = new AmountInExpendTotalVO();

        //每个请求线程维护一个month数据，避免多线程数据冲突
        MonthTableNameHandler.setData(param.getTradeMonth());

        if(StrUtil.isBlank(param.getKind())|| param.getKind().equals(KindTypeEnum.ADD.getType())){
            QueryWrapper<KxsUserAmountLog> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", SecurityUtils.getUser().getId());
            queryWrapper.in(CollUtil.isNotEmpty(param.getBrandIds()),"brand_id", param.getBrandIds());
            queryWrapper.in(CollUtil.isNotEmpty(param.getChangeType()),"variation_type", param.getChangeType());
            queryWrapper.select("IFNULL(SUM(amount),0) AS amount");
            queryWrapper.eq( "kind", KindTypeEnum.ADD.getType());

            //收益
            KxsUserAmountLog add = baseMapper.selectOne(queryWrapper);
            amountInExpendTotalVO.setIncome(add.getAmount());
        }

        if(StrUtil.isBlank(param.getKind()) || param.getKind().equals(KindTypeEnum.SUB.getType())){
            QueryWrapper<KxsUserAmountLog> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", SecurityUtils.getUser().getId());
            queryWrapper.in(CollUtil.isNotEmpty(param.getBrandIds()),"brand_id", param.getBrandIds());
            queryWrapper.in(CollUtil.isNotEmpty(param.getChangeType()),"variation_type", param.getChangeType());
            queryWrapper.select("IFNULL(SUM(amount),0) AS amount");

            queryWrapper.eq("kind", KindTypeEnum.SUB.getType());
            //支出
            KxsUserAmountLog add = baseMapper.selectOne(queryWrapper);
            amountInExpendTotalVO.setExpend(add.getAmount());
        }


        return amountInExpendTotalVO;
    }

    @Override
    public List<VariationTypeListVO> variationTypeList(String kind) {
        return baseMapper.variationTypeList(kind);
    }

    @Override
    public List<VariationListVO>  variationList(String changeTypeId) {
        return baseMapper.variationList(changeTypeId);
    }

    @Override
    public SourceUserVO sourceUser(Integer id, String tradeMonth) {

        SourceUserVO.SourceUserVOBuilder builder = SourceUserVO.builder();
        MonthTableNameHandler.setData(tradeMonth);
        KxsUserAmountLog userAmountLog = baseMapper.selectById(id);
        //删除线程，避免线程污染
        MonthTableNameHandler.removeData();
        if(userAmountLog.getVariationCause().isBlank() || "0".equals(userAmountLog.getVariationCause())){
            return builder.build();
        }
        //来源ID
        int sourceUserId = Integer.parseInt(userAmountLog.getVariationCause());

        KxsUser user = userMapper.selectById(sourceUserId);
        builder.userCode(user.getUserCode());


        return builder.build();
    }
}

