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.AmountLogChangeTypesEnum;
import com.kxs.common.core.constant.enums.KindTypeEnum;
import com.kxs.common.core.util.R;
import com.kxs.user.api.model.KxsUserAmount;
import com.kxs.common.core.constant.enums.UserAdvanceStatusEnum;
import com.kxs.user.api.model.KxsUserAmountLog;
import com.kxs.user.biz.mapper.KxsUserAdvanceMapper;
import com.kxs.user.api.model.KxsUserAdvance;
import com.kxs.user.biz.mapper.KxsUserAmountMapper;
import com.kxs.user.biz.service.KxsUserAdvanceService;
import com.kxs.user.biz.service.KxsUserAmountLogService;
import com.kxs.user.biz.service.KxsUserAmountService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

/**
 * 客小爽用户预扣款表(KxsUserAdvance)表服务实现类
 *
 * @author 系统
 * @since 2024-01-03 09:39:56
 */
@Service("kxsUserAdvanceService")
@RequiredArgsConstructor
public class KxsUserAdvanceServiceImpl extends ServiceImpl<KxsUserAdvanceMapper, KxsUserAdvance> implements KxsUserAdvanceService {

    private final KxsUserAmountMapper kxsUserAmountMapper;

    private final KxsUserAmountService kxsUserAmountService;

    @Override
    public R returnAdvance(Integer advanceId) {

        KxsUserAdvance advance = baseMapper.selectById(advanceId);
        //撤回预扣款
        advance.setStatus(UserAdvanceStatusEnum.ADVANCE_CANCEL.getType());
        baseMapper.updateById(advance);
        //创客余额返还
//        KxsUserAmount userAmount = kxsUserAmountMapper.selectOne(Wrappers.<KxsUserAmount>lambdaQuery().eq(KxsUserAmount::getUserId, advance.getUserId()));
//        userAmount.setAmount(NumberUtil.add(userAmount.getAmount(),advance.getAmount()));
//        kxsUserAmountMapper.updateById(userAmount);
        //创客余额返还 增加日志
        KxsUserAmountLog userAmountLog = new KxsUserAmountLog();
        userAmountLog.setUserId(advance.getUserId());
        userAmountLog.setKind(KindTypeEnum.ADD.getType());
        userAmountLog.setVariationType(AmountLogChangeTypesEnum.INCREASED_LABOR.getType());
        userAmountLog.setRemark("预发机预扣款返还");
        userAmountLog.setVariationCause("预发机预扣款返还");
        userAmountLog.setAmount(advance.getAmount());
        kxsUserAmountService.userAmountChange(userAmountLog);
        return R.ok();
    }
}

