package com.hzs.member.account.controller.api;

import cn.hutool.core.collection.CollUtil;
import com.hzs.common.core.annotation.RepeatSubmitSimple;
import com.hzs.common.core.constant.CountryConstants;
import com.hzs.common.core.constant.msg.FinanceMsgConstants;
import com.hzs.common.core.domain.R;
import com.hzs.common.core.enums.EBusinessModule;
import com.hzs.common.core.enums.EYesNo;
import com.hzs.common.core.utils.StringUtils;
import com.hzs.common.core.web.controller.BaseController;
import com.hzs.common.core.web.domain.AjaxResult;
import com.hzs.common.domain.member.account.CuMemberBank;
import com.hzs.common.domain.system.config.BdTradeWhiteConfig;
import com.hzs.common.security.utils.SecurityUtils;
import com.hzs.common.util.TransactionUtils;
import com.hzs.member.account.dto.CuMemberBankParam;
import com.hzs.member.account.service.ICuMemberBankService;
import com.hzs.member.account.service.ICuMemberBaseService;
import com.hzs.member.account.service.ICuMemberWithdrawService;
import com.hzs.member.account.vo.CuMemberBankVO;
import com.hzs.member.sms.service.IApiAliSmsService;
import com.hzs.third.bankcard.IBankCardServiceApi;
import com.hzs.third.bankcard.dto.BankCardParam;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 会员银行卡 前端控制器
 */
@RestController
@RequestMapping("/api/bank")
public class ApiCuMemberBankController extends BaseController {

    @Autowired
    private ICuMemberBankService cuMemberBankService;
    @Autowired
    private ICuMemberBaseService iCuMemberBaseService;
    @Autowired
    private ICuMemberWithdrawService cuMemberWithdrawService;
    @Autowired
    private IApiAliSmsService iApiAliSmsService;

    @DubboReference
    IBankCardServiceApi bankCardServiceApi;


    /**
     * 是否绑定银行卡
     *
     * @return AjaxResult
     */
    @GetMapping("/is-bind")
    public AjaxResult isBindBank() {
        Long pkMember = SecurityUtils.getUserId();
        Integer pkCountry = SecurityUtils.getPkCountry();
        CuMemberBankVO cuMemberBank = cuMemberBankService.isBindBank(pkMember, pkCountry);
        String flag = null == cuMemberBank.getDefaultCard() ? EYesNo.NO.getValue() : EYesNo.YES.getValue();
        return AjaxResult.success().put("flag", flag);
    }

    /**
     * 解绑银行卡
     *
     * @return AjaxResult
     */
    @GetMapping("/unbind-bank")
    public AjaxResult unbindBank(Long pkId) {
        Assert.notNull(pkId, TransactionUtils.getContent(FinanceMsgConstants.BANK_CARD_CANNOT_EMPTY));
        Integer pkCountry = SecurityUtils.getPkCountry();
        Long pkMember = SecurityUtils.getUserId();
        //查询默认银行卡
        CuMemberBankVO cuMemberBankVO = cuMemberBankService.selectCuMemberBankById(pkId);
        //解绑默认银行卡需校验是否有进行的提现
        if (null != cuMemberBankVO) {
            List<Long> pkIds = cuMemberWithdrawService.selectWithdrawMember(pkCountry, pkMember);
            if (CollUtil.isNotEmpty(pkIds)) {
                return AjaxResult.error(TransactionUtils.getContent(FinanceMsgConstants.WITHDRAWAL_APPROVAL));
            }

        }
        return AjaxResult.success(cuMemberBankService.unbindBank(pkId, pkMember));
    }


    /**
     * 校验开户名
     *
     * @param accountName 开户名
     * @return AjaxResult
     */
    @GetMapping("/check-account-name")
    public AjaxResult checkAccountName(String accountName) {
        Assert.notNull(accountName, TransactionUtils.getContent(FinanceMsgConstants.ACCOUNT_NAME_CANNOT_EMPTY));
        String memberCode = SecurityUtils.getMemberCode();
        String flag = memberCode.equals(accountName) ? EYesNo.YES.getValue() : EYesNo.NO.getValue();
        return AjaxResult.success().put("flag", flag);
    }

    /**
     * 银行卡四要素验证
     *
     * @param memberBankParam 银行卡信息
     * @return AjaxResult
     */
    @PostMapping("/verify-bank-card")
    public AjaxResult verifyBankCard(@RequestBody CuMemberBankParam memberBankParam) {
        BankCardParam bankCard = BankCardParam.builder().name(memberBankParam.getAccountName())
                .idCard(memberBankParam.getIdCard()).mobile(memberBankParam.getPhone())
                .bankCard(StringUtils.deleteWhitespace(memberBankParam.getCardNumber())).build();
        R result = bankCardServiceApi.verifyBankCard(bankCard);
        return result.isSuccess() ? AjaxResult.success() : AjaxResult.error(result.getMsg());

    }


    /**
     * 绑定银行卡
     *
     * @param cuMemberBankParam 银行卡入参
     * @return AjaxResult
     */
    @PostMapping("/add")
    @RepeatSubmitSimple
    public AjaxResult addBankInfo(@RequestBody CuMemberBankParam cuMemberBankParam) {
        Integer pkCountry = SecurityUtils.getPkCountry();
        Long pkMember = SecurityUtils.getUserId();
        //是否配置提现白名单
        String configWhite = getConfigWhite(pkCountry, pkMember);
        //海外不校验验证码、四要素 国内配置了提现白名单不校验
        if (pkCountry.equals(CountryConstants.CHINA_COUNTRY) && configWhite.equals(EYesNo.NO.getValue())) {
            String verificationCode = cuMemberBankParam.getVerificationCode();
            if (StringUtils.isEmpty(verificationCode)) {
                return AjaxResult.error(TransactionUtils.getContent(FinanceMsgConstants.VERIFICATION_CODE_CANNOT_EMPTY));
            }
            //支行名称
            String subBankName = cuMemberBankParam.getSubBankName();
            if (StringUtils.isEmpty(subBankName)) {
                return AjaxResult.error(TransactionUtils.getContent(FinanceMsgConstants.OPENING_BRANCH_CANNOT_EMPTY));
            }
            //银行卡号去空格
            String cardNumber = cuMemberBankParam.getCardNumber();
            cuMemberBankParam.setCardNumber(StringUtils.deleteWhitespace(cardNumber));

            String message = iApiAliSmsService.checkCode(cuMemberBankParam.getPhone(), verificationCode, null, pkMember);
            if (null != message) {
                return AjaxResult.error(message);
            }
        }
        cuMemberBankParam.setPkCountry(pkCountry);
        cuMemberBankParam.setPkMember(pkMember);
        return toAjax(cuMemberBankService.saveMemberBank(cuMemberBankParam));
    }


    @GetMapping("/list")
    public AjaxResult getBankCardList() {
        Long pkMember = SecurityUtils.getUserId();
        Integer pkCountry = SecurityUtils.getPkCountry();
        return AjaxResult.success(cuMemberBankService.selectBankCardByPkMember(pkMember, pkCountry));
    }

    @GetMapping("/default-bank")
    public AjaxResult getDefaultBankCard() {
        Long pkMember = SecurityUtils.getUserId();
        Integer pkCountry = SecurityUtils.getPkCountry();
        return AjaxResult.success(cuMemberBankService.isBindBank(pkMember, pkCountry));
    }

    /**
     * 修改默认银行卡
     *
     * @param pkId ID
     * @return AjaxResult
     */
    @GetMapping("/update-default")
    public AjaxResult updateDefault(Long pkId) {
        Long pkMember = SecurityUtils.getUserId();
        Integer pkCountry = SecurityUtils.getPkCountry();
        //查询银行卡
        CuMemberBank cuMemberBank = cuMemberBankService.getById(pkId);
        //解绑默认银行卡需校验是否有进行的提现
        if (null != cuMemberBank) {
            List<Long> pkIds = cuMemberWithdrawService.selectWithdrawMember(pkCountry, pkMember);
            if (CollUtil.isNotEmpty(pkIds)) {
                return AjaxResult.error(TransactionUtils.getContent(FinanceMsgConstants.WITHDRAWAL_APPROVAL));
            }
        }
        return toAjax(cuMemberBankService.updateDefault(pkId, pkMember, pkCountry));
    }


    /**
     * 查询是否设置提现白名单
     *
     * @return AjaxResult
     */
    @GetMapping("/is-white-list")
    public AjaxResult isWhiteList() {
        String flag = getConfigWhite(SecurityUtils.getPkCountry(), SecurityUtils.getUserId());
        return AjaxResult.success().put("flag", flag);
    }

    /**
     * 查询提现白名单配置
     *
     * @param pkCountry 国家ID
     * @param pkMember  会员ID
     * @return String
     */
    private String getConfigWhite(Integer pkCountry, Long pkMember) {
        BdTradeWhiteConfig bdTradeWhiteConfig = iCuMemberBaseService.selectConfigWhite(pkMember, pkCountry, EBusinessModule.WITHDRAWAL.getValue());
        return null == bdTradeWhiteConfig ? EYesNo.NO.getValue() : EYesNo.YES.getValue();
    }

}
