package com.ghy.web.controller.customer;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ghy.common.adapay.AdapayConfig;
import com.ghy.common.adapay.model.AdapayStatusEnum;
import com.ghy.common.adapay.model.Merchant;
import com.ghy.common.core.domain.AjaxResult;
import com.ghy.common.utils.AdapayUtils;
import com.ghy.common.utils.ExceptionUtil;
import com.ghy.common.utils.spring.SpringUtils;
import com.ghy.customer.domain.CustomerBank;
import com.ghy.customer.request.BindBankCardRequest;
import com.ghy.customer.service.CustomerBankService;
import com.ghy.payment.service.AdapayService;
import com.huifu.adapay.core.exception.BaseAdaPayException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.Map;
import java.util.Set;

/**
 * @author HH 2022/5/20
 */
@Slf4j
@RestController
@RequestMapping("/customer/bankcard")
public class CustomerBankController {

    @Resource
    private CustomerBankService customerBankService;
    @Resource
    private AdapayService adapayService;

    /**
     * 个人账户绑定银行卡接口
     */
    @PostMapping("bind")
    @ResponseBody
    private AjaxResult bindBankCard(@RequestBody @Valid BindBankCardRequest request) throws BaseAdaPayException {
        Set<Merchant> merchants = AdapayConfig.getMerchants();
        String phone = request.getPhone();
        phone = StringUtils.trimAllWhitespace(phone);
        for (Merchant merchant : merchants) {
            String memberId = AdapayUtils.getCustomerMemberId(request.getCustomerId(), merchant.getDeptId());

            if(adapayService == null){
                adapayService = SpringUtils.getBean(AdapayService.class);
            }
            if(customerBankService == null){
                customerBankService = SpringUtils.getBean(CustomerBankService.class);
            }
            // 需要先检查一次memberId是否已存在，如果已存在则只需要绑卡即可
            Map<String, Object> member = adapayService.queryMember(merchant.getDeptId(), memberId);
            if (AdapayStatusEnum.succeeded.code.equals(member.get("status")) && memberId.equals(member.get("member_id"))) {
                log.info("用户[memberId={}]已存在 跳过实名直接绑卡", memberId);
            } else {
                // 先在Adapay创建实名用户
                Map<String, Object> result1 = adapayService.createMember(merchant.getDeptId(), memberId, phone,
                        request.getName(), request.getCertId());
                if (!AdapayStatusEnum.succeeded.code.equals(result1.get("status"))) {
                    log.error("实名认证失败[{}]", JSON.toJSONString(result1));
                    return AjaxResult.error("个人信息不正确");
                }
            }

            // 开始创建结算账户
            JSONObject result2 = adapayService.createSettleAccount(merchant.getDeptId(), memberId, request.getBankNum(), request.getName(),
                    "2", request.getCertId(), phone, null, null, null);
            if (!AdapayStatusEnum.succeeded.code.equals(result2.get("status"))) {
                if ("account_exists".equals(result2.get("error_code"))) {
                    log.info("用户[memberId={}]结算账户已存在 跳过", memberId);
                } else {
                    log.error("创建结算账户失败[{}]", JSON.toJSONString(result2));
                    return AjaxResult.error("个人信息与银行卡不匹配");
                }
            }

            CustomerBank customerBank = new CustomerBank();
            customerBank.setCustomerId(request.getCustomerId());
            customerBank.setName(request.getName());
            customerBank.setCertId(request.getCertId());
            customerBank.setBankNum(request.getBankNum());
            customerBank.setPhone(phone);
            customerBank.setDeptId(merchant.getDeptId());
            customerBank.setAdapayMemberId(memberId);
            customerBank.setSettleAccount(1);
            customerBank.setSettleAccountId(result2.getString("id"));
            customerBankService.insertCustomerBank(customerBank);


        }
        return AjaxResult.success();
    }

    @PutMapping("update")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult updateBankCard(@RequestBody @Valid BindBankCardRequest request) throws BaseAdaPayException {
        Set<Merchant> merchants = AdapayConfig.getMerchants();
        for (Merchant merchant : merchants) {
            String memberId = AdapayUtils.getCustomerMemberId(request.getCustomerId(), merchant.getDeptId());
            CustomerBank customerBank = customerBankService.getByMemberId(memberId);
            if (customerBank != null) {
                if (request.getBankNum().equals(customerBank.getBankNum())) {
                    // 这个银行卡号已经绑定过了
                    continue;
                }
                boolean equalsName = request.getName().equals(customerBank.getName());
                boolean equalsCertId = request.getCertId().equals(customerBank.getCertId());
                // 必须与原来的开户名和身份证一致
                Assert.isTrue(equalsName && equalsCertId, "银行卡与实名信息不符");
                JSONObject deleteResponse = adapayService.deleteSettleAccount(merchant.getDeptId(), memberId, customerBank.getSettleAccountId());
                boolean deleteResult = AdapayStatusEnum.succeeded.code.equals(deleteResponse.getString("status"));
                Assert.isTrue(deleteResult, "解绑银行卡失败: " + deleteResponse.getString("error_msg"));
            } else {
                customerBank = new CustomerBank();
                customerBank.setAdapayMemberId(memberId);
                customerBank.setCustomerId(request.getCustomerId());
                customerBank.setName(request.getName());
                customerBank.setCertId(request.getCertId());
                customerBank.setDeptId(merchant.getDeptId());
                customerBank.setSettleAccount(1);
                customerBank.setSettleAccountId("");
                customerBankService.insertCustomerBank(customerBank);
            }
            // 绑定新卡
            JSONObject createResponse = adapayService.createSettleAccount(merchant.getDeptId(), memberId, request.getBankNum(), request.getName(),
                    "2", request.getCertId(), request.getPhone(), null, null, null);
            boolean createResult = AdapayStatusEnum.succeeded.code.equals(createResponse.get("status"));
            Assert.isTrue(createResult, "绑定银行卡失败: " + createResponse.getString("error_msg"));
            // 更新数据库中的手机号和银行卡号
            customerBank.setPhone(request.getPhone());
            customerBank.setBankNum(request.getBankNum());
            customerBank.setSettleAccountId(createResponse.getString("id"));
            customerBankService.updateByMemberId(customerBank);
        }
        return AjaxResult.success("绑定银行卡成功");
    }

    @PostMapping("getByCustomerId")
    @ResponseBody
    public AjaxResult getByCustomerId(@RequestBody BindBankCardRequest request) {
        try {
            return AjaxResult.success(customerBankService.selectByCustomerId(request.getCustomerId()));
        } catch (Exception e) {
            log.error(e.getMessage());
            return AjaxResult.error(ExceptionUtil.getExceptionMessage(e));
        }
    }

}





















