package com.ruoyi.applet.contoller;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.model.domain.AppUsers;
import com.ruoyi.model.domain.AppletAmountLog;
import com.ruoyi.model.domain.AppletConfig;
import com.ruoyi.model.service.IAppUsersService;
import com.ruoyi.model.service.IAppletAmountLogService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

@Api(description = "小程序-金额相关接口")
@RestController
@RequestMapping("/applet/amount")
public class ApiAppletAmountController {
    //金额流水信息
    @Autowired
    private IAppletAmountLogService appletAmountLogService;
    @Autowired
    private IAppUsersService appUsersService;



    @ApiOperation("小程序-金额流水信息列表数据查询")
    @GetMapping("/amountLogList")
    public AjaxResult amountLogList(AppletAmountLog appletAmountLog){
        List<AppletAmountLog> amountLogList = appletAmountLogService.selectAppletAmountLogList(appletAmountLog);
        return AjaxResult.success("金额流水信息列表数据",amountLogList);
    }

    @ApiOperation("小程序-充值")
    @PostMapping("/cashIn")
    public AjaxResult cashIn(AppletAmountLog appletAmountLog){
        return AjaxResult.success("充值接口暂未处理");
    }

    @ApiOperation("小程序-提现")
    @PostMapping("/cashOut")
    @Transactional // 简单事务管理
    public AjaxResult cashOut(@RequestBody AppletAmountLog appletAmountLog) {
        // 基础校验
        if (appletAmountLog.getUserId() == null) {
            return AjaxResult.error("用户ID不能为空");
        }
        if (appletAmountLog.getAmount() == null ||
                appletAmountLog.getAmount().compareTo(BigDecimal.ZERO) <= 0) {
            return AjaxResult.error("提现金额必须大于0");
        }

        // 查询用户余额
        AppUsers user = appUsersService.selectAppUsersByUserId(appletAmountLog.getUserId());
        if (user == null) {
            return AjaxResult.error("用户不存在");
        }

        // 检查余额是否足够
        if (user.getPrice().compareTo(appletAmountLog.getAmount()) < 0) {
            return AjaxResult.error("余额不足");
        }

        try {
            // 扣减余额（直接更新）
            user.setPrice(user.getPrice().subtract(appletAmountLog.getAmount()));
            appUsersService.updateAppUsers(user);

            // 记录日志
            appletAmountLog.setUserId(user.getUserId());
//            appletAmountLog.setCreateTime(LocalDateTime.now());
            appletAmountLogService.insertAppletAmountLog(appletAmountLog);

            return AjaxResult.success("提现成功");
        } catch (Exception e) {
            return AjaxResult.error("提现处理失败");
        }
    }

}
