package com.jeequan.jeepay.thirdparty.channel.kqpay;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.jeequan.jeepay.core.beans.RequestKitBean;
import com.jeequan.jeepay.core.entity.MchApplyment;
import com.jeequan.jeepay.core.exception.BizException;
import com.jeequan.jeepay.core.interfaces.paychannel.IIsvmchApplymentNotifyService;
import com.jeequan.jeepay.core.model.params.kqpay.KqpayIsvParams;
import com.jeequan.jeepay.db.entity.PayInterfaceConfig;
import com.jeequan.jeepay.service.impl.MchApplymentService;
import com.jeequan.jeepay.service.impl.PayInterfaceConfigService;
import com.jeequan.jeepay.thirdparty.service.ConfigContextQueryService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.tuple.MutablePair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Slf4j
@Service("kqpayIsvmchApplymentNotifyService")
public class KqpayIsvmchApplymentNotifyService implements IIsvmchApplymentNotifyService {

    @Autowired
    private KqpayMchApplymentService kqpayMchApplymentService;

    @Autowired
    private PayInterfaceConfigService payInterfaceConfigService;

    @Autowired @Lazy
    private MchApplymentService mchApplymentService;

    @Autowired
    protected RequestKitBean requestKitBean;

    @Autowired
    private ConfigContextQueryService configContextQueryService;

    @Override
    public ResponseEntity<?> retOk(Object params) {
        JSONObject reqParamJSON = requestKitBean.getReqParamJSON();
        String s = KqpayKit.resSuccess((reqParamJSON));
        return ResponseEntity.ok(JSON.parseObject(s));
    }

    @Override
    public MutablePair<String, Object> parseParams(HttpServletRequest request, String urlApplyId) {

        JSONObject reqParamJSON = requestKitBean.getReqParamJSON();
        String url = "https://reg.shouyinbeipay.com/auditCallback/kq";
        HttpResponse execute = null;
        try {
            execute = HttpRequest.post(url)
                    .body(reqParamJSON.toJSONString())
                    .execute();
            if (execute.isOk()) {
                log.info("回调给{}成功", url);
            } else {
                log.info("回调给{}异常", url);
            }
        } catch (Exception e) {
            log.info("回调给{}异常", url);
            if (execute != null) {
                execute.close();
            }
        }



        String orderId = reqParamJSON.getJSONObject("head").getString("externalRefNumber");
        com.jeequan.jeepay.db.entity.MchApplyment mchApplyment = mchApplymentService.getByOrderId(orderId);

        String memberCode = reqParamJSON.getJSONObject("head").getString("memberCode");

        QueryWrapper<PayInterfaceConfig> qWrapper = Wrappers.query();
        qWrapper.eq("if_params->>'$.memberCode'", memberCode);
        qWrapper.eq("if_code", "kqpay");

        List<PayInterfaceConfig> list = payInterfaceConfigService.list(qWrapper);

        if (list.isEmpty()) {
            throw new BizException("没找到配置信息");
        }

        KqpayIsvParams isvParams = JSON.parseObject(list.get(0).getIfParams(), KqpayIsvParams.class);

        log.info("快钱回调: {}", reqParamJSON);

        KqpayKit.checkResultNotify(reqParamJSON, isvParams);

        return new MutablePair<>(mchApplyment.getApplyId(), reqParamJSON);
    }

    @Override
    public MutablePair<MchApplyment, ResponseEntity> doNotify(HttpServletRequest request, Object params, MchApplyment mchApplyment) {
        MchApplyment resultMch = new MchApplyment();

        JSONObject bizParam = ((JSONObject) params).getJSONObject("requestBody");
        String status = bizParam.getString("status");

        JSONObject openResult = bizParam.getJSONObject("openResult");

        JSONObject param = new JSONObject();
        param.put("isReceived", "1");

        ResponseEntity<JSONObject> ok = ResponseEntity.ok(param);

        String comments = bizParam.getString("comments");
        resultMch.setApplyErrorInfo(comments);
        if ("REJECTED".equals(status)) {
            resultMch.setState(MchApplyment.STATE_REJECT_WAIT_MODIFY);
            return new MutablePair<>(resultMch, ok);
        }

        if ("FINISHED".equals(status)) {
            resultMch.setChannelMchNo(bizParam.getString("subMerchantId"));
            resultMch.setSuccResParameter(bizParam.toString());
            // 收集子商户信息
            kqpayMchApplymentService.subMchColl(mchApplyment, bizParam);
            return new MutablePair<>(resultMch, ok);
        }

        if ("TO_BE_SIGNED".equals(status) ) {
            KqpayIsvParams isvParams = (KqpayIsvParams) configContextQueryService.queryIsvParams(mchApplyment);

            int allowSignResult = kqpayMchApplymentService.isAllowSign(mchApplyment);
            if (allowSignResult == 2) {
                resultMch.setState(MchApplyment.STATE_WAIT_SIGN);
                return new MutablePair<>(resultMch, ok);
            }

            if (allowSignResult == 1) {
                kqpayMchApplymentService.signApply(mchApplyment);
                resultMch = kqpayMchApplymentService.query(mchApplyment);
                return new MutablePair<>(resultMch, ok);
            }
        }

        if ("TO_BE_REAUDITED".equals(status)) {
            if (openResult != null) {
                resultMch.setChannelMchNo(openResult.getString("subMerchantId"));
                resultMch.setSuccResParameter(openResult.toString());
                kqpayMchApplymentService.subMchColl(mchApplyment, openResult);
            }
            resultMch.setState(MchApplyment.STATE_SUCCESS_NEED_SECOND_VERIFY);

            return new MutablePair<>(resultMch, ok);
        }

        return new MutablePair<>(mchApplyment, ok);
    }
}
