package com.ghy.web.controller.worker;

import com.alibaba.fastjson.JSON;
import com.ghy.common.adapay.AdapayConfig;
import com.ghy.payment.service.AdapayService;
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.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 lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
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
    private AjaxResult bindBankCard(@RequestBody WorkerBindBankCardRequest request) throws BaseAdaPayException {
        Set<Merchant> merchants = AdapayConfig.getMerchants();
        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, request.getPhone(),
                        request.getName(), request.getCertId());
                if (!AdapayStatusEnum.succeeded.code.equals(result1.get("status"))) {
                    logger.error("实名认证失败[{}]", JSON.toJSONString(result1));
                    return AjaxResult.error("个人信息不正确");
                }
            }

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

            WorkerBank workerBank = new WorkerBank();
            workerBank.setWorkerId(request.getWorkerId());
            workerBank.setName(request.getName());
            workerBank.setCertId(request.getCertId());
            workerBank.setBankNum(request.getBankNum());
            workerBank.setPhone(request.getPhone());
            workerBank.setDeptId(merchant.getDeptId());
            workerBank.setAdapayMemberId(memberId);
            workerBank.setSettleAccount(1);
            workerBankService.insertWorkerBank(workerBank);

        }
        // 判断师傅是否已经审核过，审核过，就更新师傅状态为可用
        WorkerCertification workerCertification = workerCertificationService.selectByWorkerId(request.getWorkerId());
        if (workerCertification != null &&workerCertification.getStatus() == 1){
            // 更新师傅为可用
            Worker worker = new Worker();
            worker.setWorkerId(request.getWorkerId());
            worker.setStatus(0);
            workerService.updateWorker(worker);
        }
        return AjaxResult.success("绑定银行卡成功");
    }

    @PostMapping("/getByWorkerId")
    @ResponseBody
    public AjaxResult getByWorkerId(@RequestBody WorkerBindBankCardRequest request){
        try {
            return AjaxResult.success(workerBankService.getByWorkerId(request.getWorkerId()));
        }catch (Exception e){

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


}
