package com.ruoyi.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.annotations.UserLoginToken;
import com.ruoyi.code.PublicCommon;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.controller.req.WithApplyReq;
import com.ruoyi.controller.req.WithdrawalRecordPageReq;
import com.ruoyi.enums.process.ProcessResultEnums;
import com.ruoyi.frequency.auth.entity.Auth;
import com.ruoyi.frequency.auth.service.AuthService;
import com.ruoyi.frequency.bankcard.service.BankCardService;
import com.ruoyi.frequency.customer.service.UserService;
import com.ruoyi.frequency.highendauth.entity.HighendAuth;
import com.ruoyi.frequency.highendauth.service.HighendAuthService;
import com.ruoyi.frequency.klkaccount.entity.KlkAccount;
import com.ruoyi.frequency.klkaccount.mapper.KlkAccountMapper;
import com.ruoyi.frequency.withdrawalconfig.entity.WithdrawalConfig;
import com.ruoyi.frequency.withdrawalconfig.service.WithdrawalConfigService;
import com.ruoyi.frequency.withdrawalrecord.service.WithdrawalRecordService;
import com.ruoyi.response.ResponseData;
import com.ruoyi.vo.BodyIdReq;
import com.ruoyi.vo.RyController;
import com.ruoyi.vo.UserVo;
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.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;


/**
 * 提现相关
 *
 * @author liwenlong
 */
@Slf4j
@RestController
@RequestMapping("/api/withdrawal")
@Api(tags = "提现相关")
public class ApiWithdrawalController extends RyController {


    @Autowired
    private WithdrawalRecordService withdrawalRecordService;

    @Autowired
    private WithdrawalConfigService withdrawalConfigService;


    /**
     * 查询提现配置信息
     *
     * @return
     */
    @UserLoginToken
    @RequestMapping(value = "/withdrawalConfig", method = RequestMethod.POST)
    @ApiOperation(value = "查询提现配置信息")
    public ResponseData withdrawalConfig() {

        WithdrawalConfig withdrawalConfig = withdrawalConfigService.getOne(new QueryWrapper<WithdrawalConfig>().lambda()
                .eq(WithdrawalConfig::getUserType, getUserVo().getUserType())
                .eq(WithdrawalConfig::getDelFlag, PublicCommon.启用));
        return ResponseData.success(withdrawalConfig);
    }


    @Autowired
    private AuthService authService;

    @Autowired
    private HighendAuthService highendAuthService;

    @Autowired
    private UserService userService;

    @Autowired
    private BankCardService bankCardService;


    /**
     * 申请提现
     *
     * @param req
     * @return
     */
    @UserLoginToken
    @RequestMapping(value = "/apply", method = RequestMethod.POST)
    @ApiOperation(value = "申请提现")
    public ResponseData apply(@RequestBody @Valid WithApplyReq req) {


        UserVo userVo = getUserVo();

        // 判断当前用户能否提现
        KlkAccount klkAccount = checkCanApply(userVo);

        userService.storeByEnterprise(userVo);

        req.setBank(klkAccount.getAcctOpenBankName());
        req.setBankCard(klkAccount.getAcctNo());
        req.setFullName(klkAccount.getAcctName());

        return withdrawalRecordService.apply(req, userVo);
    }

    @Autowired
    private KlkAccountMapper klkAccountMapper;

    private KlkAccount checkCanApply(UserVo userVo) {
        KlkAccount klkAccount = klkAccountMapper.selectOne(new LambdaQueryWrapper<KlkAccount>()
                .eq(KlkAccount::getDelFlag, PublicCommon.启用)
                .eq(KlkAccount::getUserId, userVo.getUserId())
                .eq(KlkAccount::getUserType, userVo.getUserType()));
        if (klkAccount == null) {
            throw new ServiceException("对不起，您未绑定银行卡，无法提现");
        }
        if (klkAccount.getBindStatus() == 1) {
            throw new ServiceException("对不起，您未绑定银行卡，无法提现");
        }
        if (klkAccount.getBindStatus() == 2) {
            throw new ServiceException("对不起，您绑定的银行卡正在审核中，无法提现");
        }
        if (klkAccount.getBindStatus() == 4) {
            throw new ServiceException("对不起，您绑定的银行卡审核失败，请重新绑定");
        }
        return klkAccount;
    }

    /**
     * 提现记录
     *
     * @param req
     * @return
     */
    @UserLoginToken
    @RequestMapping(value = "/withdrawalRecordPage", method = RequestMethod.POST)
    @ApiOperation(value = "提现记录")
    public ResponseData withdrawalRecordPage(@RequestBody @Valid WithdrawalRecordPageReq req) {
        return withdrawalRecordService.withdrawalRecordPage(req, getUserVo());
    }


    /**
     * 提现记录详情
     *
     * @return
     */
    @UserLoginToken
    @RequestMapping(value = "/detail", method = RequestMethod.POST)
    @ApiOperation(value = "提现记录详情")
    public ResponseData detail(@RequestBody @Valid BodyIdReq req) {
        return withdrawalRecordService.getDetail(req.getId());
    }


    /**
     * 银行账号
     *
     * @return
     */
    @UserLoginToken
    @RequestMapping(value = "/bankAccount", method = RequestMethod.POST)
    @ApiOperation(value = "银行账号")
    public ResponseData bankAccount() {

        UserVo userVo = getUserVo();

        userService.storeByEnterprise(userVo);

        WithApplyReq req = new WithApplyReq();

        //判断认证状态
        HighendAuth highendAuth = highendAuthService.getOne(new QueryWrapper<HighendAuth>().lambda()
                .eq(HighendAuth::getStoreId, userVo.getUserId())
                .eq(HighendAuth::getStatus, 3)
                .eq(HighendAuth::getDelFlag, PublicCommon.启用));
        if (highendAuth == null) {
            //获取银行账号
            Auth auth = authService.getOne(new QueryWrapper<Auth>().lambda()
                    .eq(Auth::getStoreId, userVo.getUserId())
                    .eq(Auth::getResult, ProcessResultEnums.APPROVED.getCode())
                    .eq(Auth::getDelFlag, PublicCommon.启用));
            if (auth == null) {
                return ResponseData.error("请先进行平台认证或高端认证");
            }

            req.setBank(auth.getBank());
            req.setSubbranch(auth.getSubbranch());
            req.setBankCard(auth.getBankCard());
        } else {
            req.setBank(highendAuth.getBank());
            req.setSubbranch(highendAuth.getSubbranch());
            req.setBankCard(highendAuth.getBankCard());
        }
        return ResponseData.success(req);
    }
}


