package com.ruoyi.applet.contoller;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.ruoyi.applet.transfer.TransferToUser;
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 lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;

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


    @ApiOperation("小程序-金额流水信息列表数据查询")
    @GetMapping("/amountLogList")
    public AjaxResult amountLogList(AppletAmountLog appletAmountLog){
        List<AppletAmountLog> amountLogList = appletAmountLogService
                .lambdaQuery()
                .orderByDesc(AppletAmountLog::getCreateTime)
                .eq(AppletAmountLog::getUserId, appletAmountLog.getUserId())
                .eq(appletAmountLog.getType() != null, AppletAmountLog::getType, appletAmountLog.getType())
                .eq(appletAmountLog.getMoneyType() != null, AppletAmountLog::getMoneyType, appletAmountLog.getMoneyType())
                .list();
        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");
        }
        if (StringUtils.isEmpty(appletAmountLog.getNameValue())) {
            return AjaxResult.error("姓名不能为空");
        }

        // 查询用户余额
        AppUsers user = appUsersService.selectAppUsersByUserId(appletAmountLog.getUserId());

        if (user == null) {
            return AjaxResult.error("用户不存在");
        }

        // 检查余额是否足够
        if(appletAmountLog.getMoneyType() == 0){
            if (user.getMoney().compareTo(appletAmountLog.getAmount()) < 0) {
                return AjaxResult.error("合伙人余额不足");
            }
        }else if (appletAmountLog.getMoneyType() == 1){
            if (user.getPrice().compareTo(appletAmountLog.getAmount()) < 0) {
                return AjaxResult.error("伴宠师余额不足");
            }
        }else if (appletAmountLog.getMoneyType() == 2){
            if (user.getBaoPrice().compareTo(appletAmountLog.getAmount()) < 0) {
                return AjaxResult.error("保证金余额不足");
            }
        }



        try {
            // 记录日志
            AppletAmountLog moneyLog = new AppletAmountLog();
            moneyLog.setUserId(user.getUserId());
            if(appletAmountLog.getMoneyType() == 0){
                moneyLog.setTitle("合伙人钱包提现");
            }else if (appletAmountLog.getMoneyType() == 1){
                moneyLog.setTitle("伴宠师钱包提现");
            }else if (appletAmountLog.getMoneyType() == 2){
                moneyLog.setTitle("保证金退回");
            }

            moneyLog.setAmount(appletAmountLog.getAmount());
            moneyLog.setType(1); //支出
            moneyLog.setState(0); //未到账
            moneyLog.setCreateTime(LocalDateTime.now());
            moneyLog.setMoneyType(appletAmountLog.getMoneyType());//钱包类型
            moneyLog.setNameValue(appletAmountLog.getNameValue());
            moneyLog.setAuditStatus(0);//待审核状态

            appletAmountLogService.save(moneyLog);

            // 扣减余额（直接更新）
            if(appletAmountLog.getMoneyType() == 0){
                user.setMoney(user.getMoney().subtract(appletAmountLog.getAmount()));
            }else if (appletAmountLog.getMoneyType() == 1){
                user.setPrice(user.getPrice().subtract(appletAmountLog.getAmount()));
            }else if (appletAmountLog.getMoneyType() == 2){
                user.setBaoPrice(user.getBaoPrice().add(appletAmountLog.getAmount()));
            }

            appUsersService.updateAppUsers(user);

//            HashMap<String, Object> result = new HashMap<>();
//
//            result.put("response", response);
//            result.put("id", moneyLog.getId());

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



    @ApiOperation("小程序-提现成功")
    @PostMapping("/withdrawalSuccessful")
    public AjaxResult withdrawalSuccessful(String id){

        AppletAmountLog byId = appletAmountLogService.getById(id);

        byId.setState(1);

        appletAmountLogService.updateById(byId);

        return AjaxResult.success();
    }

}
