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

import com.hzs.common.core.annotation.RepeatSubmitSimple;
import com.hzs.common.core.constant.msg.FinanceMsgConstants;
import com.hzs.common.core.domain.R;
import com.hzs.common.core.enums.*;
import com.hzs.common.core.utils.OssUtil;
import com.hzs.common.core.utils.StringUtils;
import com.hzs.common.core.utils.ThreadUtils;
import com.hzs.common.core.web.controller.BaseController;
import com.hzs.common.core.web.domain.AjaxResult;
import com.hzs.common.domain.member.base.CuMember;
import com.hzs.common.domain.member.ext.CuMemberExt;
import com.hzs.common.domain.system.config.BdTradeConfig;
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.service.ICuMemberAuthenticationService;
import com.hzs.member.account.service.ICuMemberBaseService;
import com.hzs.member.account.vo.CuMemberAuthenticationVO;
import com.hzs.member.base.service.ICuMemberService;
import com.hzs.member.sms.service.IApiAliSmsService;
import com.hzs.third.idcard.IdCardServiceApi;
import com.hzs.third.idcard.dto.IdCardOcrDTO;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;

/**
 * 实名认证 前端控制器
 */
@RestController
@RequestMapping("/api/authentication")
public class ApiCuMemberAuthenticationController extends BaseController {

    @Autowired
    private IApiAliSmsService iApiAliSmsService;
    @Autowired
    private ICuMemberAuthenticationService iCuMemberAuthenticationService;
    @Autowired
    private ICuMemberBaseService iCuMemberBaseService;
    @Autowired
    private ICuMemberService iCuMemberService;

    @DubboReference
    IdCardServiceApi idCardServiceApi;

    /**
     * 调用身份证OCR接口
     *
     * @param authenticationVO 实名认证信息
     * @return AjaxResult
     */
    @PostMapping("/invoke-idCard")
    public AjaxResult invokeIdCard(@RequestBody CuMemberAuthenticationVO authenticationVO) {
        //身份证图片地址
        String idCardUrl = authenticationVO.getIdCardUrl();
        if (StringUtils.isEmpty(idCardUrl)) {
            return AjaxResult.error(FinanceMsgConstants.ID_CARD_URL_NOT_EMPTY);
        }
        R<IdCardOcrDTO> result = idCardServiceApi.invokeIdCardOcr(idCardUrl, EIdCardSide.FACE.getValue());
        if (result.isSuccess()) {
            return AjaxResult.success(result.getData());
        } else {
            // 如果校验失败，需要把上传文件清除掉
            ThreadUtils.threadPoolExecutor.submit(() -> OssUtil.deleteFile(idCardUrl));
        }
        return AjaxResult.error(result.getMsg());
    }


    /**
     * 调用身份证OCR反面接口
     *
     * @param authenticationVO 实名认证信息
     * @return AjaxResult
     */
    @PostMapping("/invoke-idCard-back")
    public AjaxResult invokeIdCardBack(@RequestBody CuMemberAuthenticationVO authenticationVO) {
        //身份证图片地址
        String idCardUrl = authenticationVO.getIdCardBackUrl();
        if (StringUtils.isEmpty(idCardUrl)) {
            return AjaxResult.error(FinanceMsgConstants.ID_CARD_URL_NOT_EMPTY);
        }
        R<IdCardOcrDTO> result = idCardServiceApi.invokeIdCardOcr(idCardUrl, EIdCardSide.BACK.getValue());
        if (result.isSuccess()) {
            //身份证的有效期结束时间
            String endDate = result.getData().getEndDate();
            LocalDate idCardTime = LocalDate.parse(endDate, DateTimeFormatter.ofPattern("yyyyMMdd"));
            if (idCardTime.compareTo(LocalDate.now()) < 0) {
                return AjaxResult.error(FinanceMsgConstants.ID_CARD_EXPIRE);
            }
            return AjaxResult.success();
        } else {
            // 如果校验失败，需要把上传文件清除掉
            ThreadUtils.threadPoolExecutor.submit(() -> OssUtil.deleteFile(idCardUrl));
        }
        return AjaxResult.error(result.getMsg());
    }

    /**
     * 实名认证
     *
     * @param authenticationVO 实名认证信息
     * @return AjaxResult
     */
    @PostMapping("/add")
    @RepeatSubmitSimple
    public AjaxResult saveAuthentication(@RequestBody CuMemberAuthenticationVO authenticationVO) {
        Long pkMember = SecurityUtils.getUserId();
        Integer pkCountry = SecurityUtils.getPkCountry();

        //查询是否已实名
        CuMemberAuthenticationVO queryAuthenticationVO = iCuMemberAuthenticationService.selectCuMemberAuthenticationByPkMember(CuMemberAuthenticationVO.builder().pkMember(pkMember).pkCountry(pkCountry).build());
        if (null != queryAuthenticationVO) {
            return AjaxResult.error(FinanceMsgConstants.MEMBER_REAL_NAME);
        }

        String verificationCode = authenticationVO.getVerificationCode();
        if (StringUtils.isEmpty(verificationCode)) {
            return AjaxResult.error(TransactionUtils.getContent(FinanceMsgConstants.VERIFICATION_CODE_CANNOT_EMPTY));
        }
        //真实姓名
        String accountName = authenticationVO.getAccountName();
        if (StringUtils.isEmpty(accountName)) {
            return AjaxResult.error(TransactionUtils.getContent(FinanceMsgConstants.REAL_NAME_CANNOT_EMPTY));
        }
        //真实姓名与注册的会员姓名不一致
        CuMember member = iCuMemberService.getMember(pkMember);
        if (!member.getMemberName().equals(accountName)) {
            return AjaxResult.error(TransactionUtils.getContent(FinanceMsgConstants.REAL_NAME_MEMBER_NOT_DIFFERENT));
        }

        //支行名称
        String subBankName = authenticationVO.getSubBankName();
        if (StringUtils.isEmpty(subBankName)) {
            return AjaxResult.error(TransactionUtils.getContent(FinanceMsgConstants.OPENING_BRANCH_CANNOT_EMPTY));
        }
        if (null == authenticationVO.getPkProvince()) {
            return AjaxResult.error(TransactionUtils.getContent(FinanceMsgConstants.PROVINCE_CANNOT_EMPTY));
        }
        if (null == authenticationVO.getPkCity()) {
            return AjaxResult.error(TransactionUtils.getContent(FinanceMsgConstants.CITY_CANNOT_EMPTY));
        }
        if (StringUtils.isEmpty(authenticationVO.getAddress())) {
            return AjaxResult.error(TransactionUtils.getContent(FinanceMsgConstants.ADDRESS_CANNOT_EMPTY));
        }
        if (StringUtils.isEmpty(authenticationVO.getIdFront())) {
            return AjaxResult.error(TransactionUtils.getContent(FinanceMsgConstants.ID_FRONT_CANNOT_EMPTY));
        }
        if (StringUtils.isEmpty(authenticationVO.getIdBack())) {
            return AjaxResult.error(TransactionUtils.getContent(FinanceMsgConstants.ID_BACK_CANNOT_EMPTY));
        }

        String message = iApiAliSmsService.checkCode(null, verificationCode, null, pkMember);
        if (null != message) {
            return AjaxResult.error(message);
        }
        authenticationVO.setPkCountry(pkCountry);
        authenticationVO.setPkMember(pkMember);

        return toAjax(iCuMemberAuthenticationService.saveAuthentication(authenticationVO));
    }


    /**
     * 是否需要实名认证
     *
     * @param businessModule 1:提现 2:转账 (来源枚举EBusinessModule)
     * @return AjaxResult
     */
    @GetMapping("/is-auth")
    public AjaxResult isAuth(Integer businessModule) {
        String flag = EYesNo.YES.getValue();
        Long pkMember = SecurityUtils.getUserId();
        Integer pkCountry = SecurityUtils.getPkCountry();
        //查询配置实名认证白名证
        BdTradeWhiteConfig bdTradeWhiteConfig = iCuMemberBaseService.selectConfigWhite(pkMember, pkCountry, businessModule);
        if (null == bdTradeWhiteConfig) {
            //查询配置是否实名认证
            BdTradeConfig bdTradeConfig = iCuMemberBaseService.selectConfigTrade(pkMember, pkCountry, businessModule, EVerificationModule.REAL_NAME);
            //配置后才进行验证
            if (null != bdTradeConfig) {
                //查询是否已实名认证
                CuMemberAuthenticationVO authenticationVO = iCuMemberAuthenticationService.selectCuMemberAuthenticationByPkMember(CuMemberAuthenticationVO.builder().pkMember(pkMember).pkCountry(pkCountry).build());
                flag = null == authenticationVO ? EYesNo.NO.getValue() : EYesNo.YES.getValue();
            }
        }
        return AjaxResult.success().put("flag", flag);
    }


    /**
     * 查看详情
     *
     * @return AjaxResult
     */
    @GetMapping("/detail")
    public AjaxResult showDetail() {
        Long pkMember = SecurityUtils.getUserId();
        Integer pkCountry = SecurityUtils.getPkCountry();
        CuMemberAuthenticationVO authenticationVO = iCuMemberAuthenticationService.selectCuMemberAuthenticationByPkMember(CuMemberAuthenticationVO.builder().pkMember(pkMember).pkCountry(pkCountry).build());
        return AjaxResult.success(authenticationVO);
    }

    /**
     * 协议处理校验实名
     *
     * @return
     */
    @GetMapping("/agreement-real-name")
    public AjaxResult agreementRealName() {
        return AjaxResult.success("", EYesNo.YES.getIntValue());
    }


    /**
     * 是否显示续约
     *
     * @return AjaxResult
     */
    @GetMapping("/is-expire")
    public AjaxResult isExpire() {
        int flag = EYesNo.NO.getIntValue();
        Long pkMember = SecurityUtils.getUserId();

        CuMemberExt member = iCuMemberService.getMemberById(pkMember);
        Integer isRealName = member.getIsRealName();

        //未实名
        if (isRealName.equals(flag)) {
            return AjaxResult.success().put("flag", flag);
        }
        //到期日期
        LocalDate expireDate = member.getExpireDate().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        //到期三个月
        LocalDate beforeMonthDate = expireDate.minusMonths(3);
        LocalDate localDate = LocalDate.now();
        if (localDate.equals(beforeMonthDate) || localDate.isAfter(beforeMonthDate)) {
            flag = EYesNo.YES.getIntValue();
        }
        return AjaxResult.success().put("flag", flag);
    }

    /**
     * 续约
     *
     * @return AjaxResult
     */
    @GetMapping("/renewal_contract")
    public AjaxResult renewalContract() {
        Long pkMember = SecurityUtils.getUserId();
        Integer pkCountry = SecurityUtils.getPkCountry();
        //查询是否已实名
        CuMemberAuthenticationVO queryAuthenticationVO = iCuMemberAuthenticationService.selectCuMemberAuthenticationByPkMember(CuMemberAuthenticationVO.builder().pkMember(pkMember).pkCountry(pkCountry).build());
        if (null == queryAuthenticationVO) {
            return AjaxResult.error(FinanceMsgConstants.MEMBER_NOT_REAL_NAME);
        }
        return toAjax(iCuMemberAuthenticationService.memberRenewalContract(pkMember));
    }


}
