package com.ghy.web.controller.worker;

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.controller.BaseController;
import com.ghy.common.core.domain.AjaxResult;
import com.ghy.common.utils.AdapayUtils;
import com.ghy.common.utils.ExceptionUtil;
import com.ghy.payment.service.AdapayService;
import com.ghy.worker.domain.Worker;
import com.ghy.worker.domain.WorkerBank;
import com.ghy.worker.domain.WorkerCertification;
import com.ghy.worker.request.WorkerBindBankCardRequest;
import com.ghy.worker.service.IWorkerCertificationService;
import com.ghy.worker.service.WorkerBankService;
import com.ghy.worker.service.WorkerService;
import com.huifu.adapay.core.exception.BaseAdaPayException;
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 clunt
 * 师傅银行卡绑定
 */
@Controller
@RequestMapping("/worker/bank")
public class WorkerBankController extends BaseController {

    @Resource
    private WorkerBankService workerBankService;
    @Resource
    private AdapayService adapayService;
    @Resource
    private IWorkerCertificationService workerCertificationService;
    @Resource
    private WorkerService workerService;

    /**
     * 个人账户绑定银行卡接口
     */
    @PostMapping("bind")
    @ResponseBody
    public AjaxResult bindBankCard(@RequestBody @Valid WorkerBindBankCardRequest request) throws BaseAdaPayException {
        // 判断师傅是否已经审核通过，未通过审核不能绑定银行卡
        WorkerCertification workerCertification = workerCertificationService.selectByWorkerId(request.getWorkerId());
        if (workerCertification != null && workerCertification.getStatus() == 2) {
            return AjaxResult.error("师傅未通过审核，不能绑定银行卡");
        }
        Set<Merchant> merchants = AdapayConfig.getMerchants();
        String phone = request.getPhone();
        phone = StringUtils.trimAllWhitespace(phone);
        for (Merchant merchant : merchants) {
            String memberId = AdapayUtils.getWorkerMemberId(request.getWorkerId(), merchant.getDeptId());

            // 需要先检查一次memberId是否已存在，如果已存在则只需要绑卡即可
            Map<String, Object> member = adapayService.queryMember(merchant.getDeptId(), memberId);
            if (AdapayStatusEnum.succeeded.code.equals(member.get("status")) && memberId.equals(member.get("member_id"))) {
                logger.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"))) {
                    logger.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"))) {
                    logger.info("用户[memberId={}]结算账户已存在 跳过", memberId);
                    continue;
                } else {
                    logger.error("创建结算账户失败[{}]", JSON.toJSONString(result2));
                    return AjaxResult.error("个人信息与银行卡不匹配或不支持信用卡绑定");
                }
            }

            WorkerBank workerBank = new WorkerBank();
            workerBank.setSettleAccountId(result2.getString("id"));
            workerBank.setWorkerId(request.getWorkerId());
            workerBank.setName(request.getName());
            workerBank.setCertId(request.getCertId());
            workerBank.setBankNum(request.getBankNum());
            workerBank.setPhone(phone);
            workerBank.setDeptId(merchant.getDeptId());
            workerBank.setAdapayMemberId(memberId);
            workerBank.setSettleAccount(1);
            workerBankService.insertWorkerBank(workerBank);

        }
        // 绑卡成功 更新师傅为可用状态
        Worker worker = new Worker();
        worker.setWorkerId(request.getWorkerId());
        worker.setStatus(0);
        workerService.updateWorker(worker);
        return AjaxResult.success("绑定银行卡成功");
    }

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

    @PostMapping("/getByWorkerId")
    @ResponseBody
    public AjaxResult getByWorkerId(@RequestBody WorkerBindBankCardRequest request) {
        try {
            if(request.getDeptId() == null){
                request.setDeptId(101L);
            }
            return AjaxResult.success(workerBankService.getByWorkerId(request.getWorkerId(), request.getDeptId()));
        } catch (Exception e) {

            return AjaxResult.error(ExceptionUtil.getExceptionMessage(e));
        }
    }


}
