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

import cn.hutool.core.util.NumberUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kxs.common.core.constant.enums.KindTypeEnum;
import com.kxs.common.core.util.R;
import com.kxs.common.security.util.SecurityUtils;
import com.kxs.user.api.dto.kxsapp.userAccount.WithdrawDepositDTO;
import com.kxs.user.api.model.KxsUserAmountLog;
import com.kxs.user.api.vo.kxsapp.userAccount.MyAccountVO;
import com.kxs.user.biz.mapper.KxsUserAmountMapper;
import com.kxs.user.api.model.KxsUserAmount;
import com.kxs.user.biz.service.KxsUserAmountLogService;
import com.kxs.user.biz.service.KxsUserAmountService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Objects;

/**
 * 用户账户表(KxsUserAmount)表服务实现类
 *
 * @author 系统
 * @since 2023-12-11 23:33:30
 */
@Service("kxsUserAmountService")
@RequiredArgsConstructor
public class KxsUserAmountServiceImpl extends ServiceImpl<KxsUserAmountMapper, KxsUserAmount> implements KxsUserAmountService {

    private final KxsUserAmountLogService kxsUserAmountLogService;
    @Override
    public MyAccountVO myAccount() {

        KxsUserAmount userAmount = this.getOne(Wrappers.<KxsUserAmount>lambdaQuery()
                .eq(KxsUserAmount::getUserId, SecurityUtils.getUser().getId()));

        MyAccountVO myAccountVO = new MyAccountVO();
        BeanUtils.copyProperties(userAmount, myAccountVO);

        //余额减去预扣款金额
        myAccountVO.setUseAmount(NumberUtil.sub(userAmount.getAmount(), userAmount.getAdvanceAmount()));

        return myAccountVO;
    }

    @Override
    public R userAmountChange(KxsUserAmountLog userAmountLog) {

        KxsUserAmount userAmount = this.getOne(Wrappers.<KxsUserAmount>lambdaQuery()
                .eq(KxsUserAmount::getUserId, userAmountLog.getUserId()));

        userAmountLog.setBeforeAmount(userAmount.getAmount());
        BigDecimal afterAmount;
        //增加余额
        if (Objects.equals(userAmountLog.getKind(), KindTypeEnum.ADD.getType())) {
            afterAmount = NumberUtil.add(userAmount.getAmount(), userAmountLog.getAmount());
        }else{
            afterAmount = NumberUtil.sub(userAmount.getAmount(), userAmountLog.getAmount());
        }
        userAmountLog.setAfterAmount(afterAmount);
        userAmount.setAmount(NumberUtil.add(afterAmount));
        kxsUserAmountLogService.save(userAmountLog);

        this.updateById(userAmount);


        return R.ok(Boolean.FALSE);
    }












}

