
package com.tmerclub.cloud.payment.controller.supplier;

import cn.hutool.core.util.StrUtil;
import com.tmerclub.cloud.api.payment.allinpay.member.resp.BindCard;
import com.tmerclub.cloud.api.payment.allinpay.member.resp.CompanyInfo;
import com.tmerclub.cloud.api.payment.dto.BindCompanyAccountDTO;
import com.tmerclub.cloud.api.payment.dto.SetCompanyInfoDTO;
import com.tmerclub.cloud.api.payment.dto.UpdateCompanyInfoDTO;
import com.tmerclub.cloud.common.constant.AllinpayConstant;
import com.tmerclub.cloud.common.exception.LuckException;
import com.tmerclub.cloud.common.response.ServerResponseEntity;
import com.tmerclub.cloud.common.security.AuthUserContext;
import com.tmerclub.cloud.payment.allinpay.constant.AllinpayNoticeUrl;
import com.tmerclub.cloud.payment.allinpay.member.constant.AuditStatus;
import com.tmerclub.cloud.payment.allinpay.member.constant.VerificationCodeType;
import com.tmerclub.cloud.payment.dto.*;
import com.tmerclub.cloud.payment.dto.*;
import com.tmerclub.cloud.payment.service.AllinpayCompanyService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author lanhai
 */
@Tag(name = "通联支付-企业会员接口(供应商端)")
@RestController("supplier-allinpay-company")
@RequestMapping("/s/applySupplier/allinpay/company")
public class AllinpayCompanyController {

    @Autowired
    private AllinpayCompanyService allinpayCompanyService;

    @Value("${application.domainUrl}")
    private String domainUrl;

    @GetMapping("/getCompanyInfo")
    @Operation(summary = "获取企业信息", description = "获取企业信息")
    public ServerResponseEntity<CompanyInfo> getCompanyInfo() {
        String bizUserId = getBizUserId();
        CompanyInfo companyInfo = allinpayCompanyService.getCompanyInfo(bizUserId);
        return ServerResponseEntity.success(companyInfo);
    }

    @PostMapping("/sendVerificationCode")
    @Operation(summary = "发送短信验证码", description = "发送短信验证码")
    public ServerResponseEntity<Void> sendVerificationCode(@RequestBody VerificationCodeDTO verificationCodeDTO) {
        String bizUserId = getBizUserId();
        CompanyInfo companyInfo = allinpayCompanyService.getCompanyInfo(bizUserId);
        if (Objects.equals(verificationCodeDTO.getVerificationCodeType(), VerificationCodeType.BIND_PHONE.value())) {
            // 绑定手机号的前提是还没有绑定过
            if (Objects.nonNull(companyInfo.getPhone())) {
                throw new LuckException("当前账户已经绑定过手机号码，请刷新页面");
            }
        } else if (Objects.equals(verificationCodeDTO.getVerificationCodeType(), VerificationCodeType.UNBIND_PHONE.value())) {
            // 解绑手机号的前提是有绑定过手机号
            if (Objects.isNull(companyInfo.getPhone())) {
                throw new LuckException("当前账户还没绑定手机号码，请刷新页面");
            }
        }
        allinpayCompanyService.sendVerificationCode(bizUserId, verificationCodeDTO);
        return ServerResponseEntity.success();
    }

    @PostMapping("/bindPhone")
    @Operation(summary = "绑定手机", description = "绑定手机")
    public ServerResponseEntity<Void> bindPhone(@RequestBody VerificationCodeDTO verificationCodeDTO) {
        String bizUserId = getBizUserId();
        if (StrUtil.isBlank(verificationCodeDTO.getVerificationCode())) {
            throw new LuckException("验证码不能为空");
        }
        // 绑定手机号的前提是还没有绑定过
        CompanyInfo companyInfo = allinpayCompanyService.getCompanyInfo(bizUserId);
        if (Objects.nonNull(companyInfo.getPhone())) {
            throw new LuckException("当前账户已经绑定过手机号码，请刷新页面");
        }
        allinpayCompanyService.bindPhone(bizUserId, verificationCodeDTO);
        allinpayCompanyService.deleteCache(bizUserId);
        return ServerResponseEntity.success();
    }

    @PutMapping("/unbindPhone")
    @Operation(summary = "解绑手机", description = "解绑手机")
    public ServerResponseEntity<Void> unbindPhone(@RequestBody VerificationCodeDTO verificationCodeDTO) {
        String bizUserId = getBizUserId();
        // 解绑手机后，用户无法创建订单
        CompanyInfo companyInfo = allinpayCompanyService.getCompanyInfo(bizUserId);
        // 解绑手机号的前提是有绑定过手机号
        if (Objects.isNull(companyInfo.getPhone())) {
            throw new LuckException("当前账户还没绑定手机号码，请刷新页面");
        }
        if (!Objects.equals(companyInfo.getPhone(), verificationCodeDTO.getPhone())) {
            throw new LuckException("解绑手机与当前绑定手机不一致");
        }
        allinpayCompanyService.unbindPhone(bizUserId, verificationCodeDTO);
        allinpayCompanyService.deleteCache(bizUserId);
        return ServerResponseEntity.success();
    }

    @PostMapping("/setCompanyInfo")
    @Operation(summary = "设置企业信息--该接口前端不调用", description = "设置企业信息--该接口前端不调用")
    public ServerResponseEntity<Void> setCompanyInfo(@RequestBody SetCompanyInfoDTO setCompanyInfoDTO) {
        String bizUserId = getBizUserId();
        String backUrl = domainUrl + AllinpayNoticeUrl.SET_COMPANY_INFO;
        allinpayCompanyService.setCompanyInfo(bizUserId, backUrl, setCompanyInfoDTO);
        allinpayCompanyService.deleteCache(bizUserId);
        return ServerResponseEntity.success();
    }

    @PutMapping("/updateCompanyInfo")
    @Operation(summary = "企业会员信息修改--该接口前端不调用", description = "企业会员信息修改--该接口前端不调用")
    public ServerResponseEntity<Void> updateCompanyInfo(@RequestBody UpdateCompanyInfoDTO updateCompanyInfoDTO) {
        String bizUserId = getBizUserId();
        // 会员要通过审核
        CompanyInfo companyInfo = allinpayCompanyService.getCompanyInfo(bizUserId);
        if (Objects.isNull(companyInfo) || !Objects.equals(companyInfo.getStatus(), AuditStatus.SUCCESS.getCode())) {
            throw new LuckException("企业会员尚未通过审核，无法修改信息");
        }
        String backUrl = domainUrl + AllinpayNoticeUrl.UPDATE_COMPANY_INFO;
        allinpayCompanyService.updateCompanyInfo(bizUserId, backUrl, updateCompanyInfoDTO);
        allinpayCompanyService.deleteCache(bizUserId);
        return ServerResponseEntity.success();
    }

    @PostMapping("/applyBindBankCard")
    @Operation(summary = "请求绑定银行卡", description = "请求绑定银行卡-法人")
    public ServerResponseEntity<Void> applyBindBankCard(@RequestBody ApplyBankCardDTO applyBankCardDTO) {
        String bizUserId = getBizUserId();
        CompanyInfo companyInfo = allinpayCompanyService.getCompanyInfo(bizUserId);
        allinpayCompanyService.applyBindBankCard(bizUserId, applyBankCardDTO, companyInfo.getLegalName());
        allinpayCompanyService.deleteCache(bizUserId);
        return ServerResponseEntity.success();
    }

    @PutMapping("/bindBankCard")
    @Operation(summary = "确认绑定银行卡--当前绑卡方式为8，该接口不调用", description = "确认绑定银行卡-法人")
    public ServerResponseEntity<Void> bindBankCard(@RequestBody BindBankCardDTO bindBankCardDTO) {
        String bizUserId = getBizUserId();
        CompanyInfo companyInfo = allinpayCompanyService.getCompanyInfo(bizUserId);
        allinpayCompanyService.bindBankCard(bizUserId, bindBankCardDTO, companyInfo.getLegalName());
        allinpayCompanyService.deleteCache(bizUserId);
        return ServerResponseEntity.success();
    }

    @PutMapping("/unbindBankCard")
    @Operation(summary = "解绑银行卡", description = "解绑银行卡-法人")
    public ServerResponseEntity<Void> unbindBankCard(@RequestBody UnbindBankCardDTO unbindBankCardDTO) {
        String bizUserId = getBizUserId();
        allinpayCompanyService.unbindBankCard(bizUserId, unbindBankCardDTO);
        allinpayCompanyService.deleteCache(bizUserId);
        return ServerResponseEntity.success();
    }

    @GetMapping("/queryBankCard")
    @Operation(summary = "查询银行卡", description = "查询银行卡")
    @Parameter(name = "cardNo", description = "银行卡号(不传则查询全部银行卡)")
    public ServerResponseEntity<List<BindCard>> queryBankCard(@RequestParam(value = "cardNo", required = false) String cardNo) {
        String bizUserId = getBizUserId();
        List<BindCard> bindCards = allinpayCompanyService.queryBankCard(bizUserId, cardNo)
                .stream().filter(card -> Objects.equals(card.getBindState(), 1)).collect(Collectors.toList());
        return ServerResponseEntity.success(bindCards);
    }

    @PostMapping("/bindCompanyAccount")
    @Operation(summary = "企业会员绑定对公户", description = "企业会员绑定对公户")
    public ServerResponseEntity<Void> bindCompanyAccount(@RequestBody BindCompanyAccountDTO bindCompanyAccountDTO) {
        String bizUserId = getBizUserId();
        CompanyInfo companyInfo = allinpayCompanyService.getCompanyInfo(bizUserId);
        allinpayCompanyService.bindCompanyAccount(bizUserId, bindCompanyAccountDTO, companyInfo.getCompanyName());
        allinpayCompanyService.deleteCache(bizUserId);
        return ServerResponseEntity.success();
    }

    @PostMapping("/signAcctProtocol")
    @Operation(summary = "账户提现协议签约", description = "账户提现协议签约")
    public ServerResponseEntity<String> signAcctProtocol(@RequestBody SignAcctProtocolDTO signAcctProtocolDTO) {
        String bizUserId = getBizUserId();
        String backUrl = domainUrl + AllinpayNoticeUrl.SIGN_ACCT_PROTOCOL;
        String url = allinpayCompanyService.signAcctProtocol(bizUserId, backUrl, signAcctProtocolDTO);
        allinpayCompanyService.deleteCache(bizUserId);
        return ServerResponseEntity.success(url);
    }

    @GetMapping("/signContractQuery")
    @Operation(summary = "账户协议签约查询", description = "账户协议签约查询")
    public ServerResponseEntity<String> signContractQuery(SignAcctProtocolDTO signAcctProtocolDTO) {
        String bizUserId = getBizUserId();
        String url = allinpayCompanyService.signContractQuery(bizUserId, signAcctProtocolDTO);
        return ServerResponseEntity.success(url);
    }

    private static String getBizUserId() {
        Long tenantId = AuthUserContext.get().getTenantId();
        return AllinpayConstant.SUPPLIER + tenantId;
    }
}
