package com.sqx.modules.pay.controller.app;


import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.sqx.common.annotation.Debounce;
import com.sqx.common.utils.PageUtils;
import com.sqx.common.utils.RedisUtils;
import com.sqx.common.utils.Result;
import com.sqx.modules.app.annotation.Login;
import com.sqx.modules.app.service.UserMoneyDetailsService;
import com.sqx.modules.common.entity.CommonInfo;
import com.sqx.modules.common.service.CommonInfoService;
import com.sqx.modules.pay.entity.CashOut;
import com.sqx.modules.pay.service.CashOutService;
import com.sqx.modules.pay.service.PayDetailsService;
import com.sqx.modules.redisService.RedisService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Calendar;
import java.util.Date;

/**
 * @author fang
 * @date 2020/5/15
 */
@Slf4j
@RestController
@Api(value = "提现", tags = {"提现"})
@RequestMapping(value = "/app/cash")
public class AppCashController {
    private final CommonInfoService commonInfoService;
    private final RedisService redisService;
    /**
     * 提现记录
     */
    @Autowired
    private CashOutService cashOutService;
    @Autowired
    private PayDetailsService payDetailsService;
    @Autowired
    private UserMoneyDetailsService userMoneyDetailsService;
    @Resource
    private RedisUtils redisUtils;


    public AppCashController(CommonInfoService commonInfoService, RedisService redisService) {
        this.commonInfoService = commonInfoService;
        this.redisService = redisService;
    }


    @Login
    @GetMapping(value = "/cashMoney")
    @ApiOperation("发起提现 余额 金币")
    public Result cashMoney(@RequestAttribute("userId") Long userId, Double money) {
        return cashOutService.cashMoney(userId, money);
    }

    @Login
    @GetMapping("/canCash")
    public Result canCash(@RequestAttribute("userId") Long userId) {
        CommonInfo info = commonInfoService.findOne(928);
        if ("0".equals(info.getValue())) {
            return Result.success().put("data", true);
        }
        return Result.success().put("data", redisService.isCanCash(userId));
    }

    @Login
    @GetMapping(value = "/withdraw")
    @Debounce(interval = 3000, value = "#userId")
    @ApiOperation("发起提现 余额 金钱")
    public Result withdraw(@RequestAttribute("userId") Long userId, Double amount) {
        String intervalKey = StrUtil.format("user:withdraw:interval:limit:user:{}", userId);
        String lockKey = StrUtil.format("user:withdraw:interval:limit:user:lock:{}", userId);
        if (redisUtils.hasKey(lockKey)) {
            return Result.error("提现请求处理中，请等待！");
        }
        if (redisUtils.hasKey(intervalKey)) {
            return Result.error("提现请求过于频繁，请稍后再试！");
        }
        boolean canCash = redisService.isCanCash(userId);
        if (!canCash) {
            CommonInfo info = commonInfoService.findOne(928);
            if ("1".equals(info.getValue())) {
                redisUtils.delete(lockKey);
                return Result.error("您未观看激励广告，清先观看");
            }
        }
        redisUtils.set(intervalKey, true, 30);

        Calendar calendar = Calendar.getInstance();
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        if (hour < 8 || hour > 18) {
            return Result.error("提现时间为每天8:00-18:00");
        }

        double money = Double.parseDouble(commonInfoService.findOne(929).getValue());
        Double v = cashOutService.queryUserTodayCashAmount(userId);
        if (v == null) {
            v = 0.0d;
        }
        if ((v + amount) >= money) {
            return Result.error("今日提现金额已达上限");
        }
        Result ret = Result.error();
        try {
            ret = cashOutService.withdraw(userId, amount, null, false);
            int code = Convert.toInt(ret.get("code"), -1);
            if (code == 0) {
                redisUtils.set(intervalKey, true, 60 * 3);
            }
        } catch (Exception e) {
            log.error("提现异常", e);
        } finally {
            redisUtils.delete(lockKey);
        }
        return ret;
    }

    @Login
    @RequestMapping(value = "/selectUserRechargeByUserId", method = RequestMethod.GET)
    @ApiOperation("查询某个用户充值信息列表")
    @ResponseBody
    public Result selectUserRechargeByUserId(int page, int limit, String startTime, String endTime, @RequestAttribute("userId") Long userId, Integer state) {
        return Result.success().put("data", payDetailsService.selectPayDetails(page, limit, startTime, endTime, userId, state, null, null));
    }

    @Login
    @RequestMapping(value = "/selectPayDetails", method = RequestMethod.GET)
    @ApiOperation("查询提现记录列表")
    @ResponseBody
    public Result selectHelpProfit(int page, int limit, @RequestAttribute("userId") Long userId) {
        CashOut cashOut = new CashOut();
        cashOut.setUserId(userId);
        PageUtils pageUtils = cashOutService.selectCashOutList(page, limit, cashOut, true);
        return Result.success().put("data", pageUtils);
    }

    @Login
    @ApiOperation("钱包明细")
    @GetMapping("/queryUserMoneyDetails")
    public Result queryUserMoneyDetails(Integer page, Integer limit, @RequestAttribute("userId") Long userId, Integer classify, Integer type, Integer moneyType) {
        return userMoneyDetailsService.queryUserMoneyDetails(page, limit, null, userId, classify, type, moneyType, 0);
    }


}
