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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jeequan.jeepay.converter.MchInfoConverter;
import com.jeequan.jeepay.core.beans.RequestKitBean;
import com.jeequan.jeepay.core.constants.CS;
import com.jeequan.jeepay.core.entity.MchApplyment;
import com.jeequan.jeepay.core.interfaces.paychannel.IIsvmchApplymentNotifyService;
import com.jeequan.jeepay.core.model.applyment.RyxpayApplymentInfo;
import com.jeequan.jeepay.db.entity.MchModifyApplymentEntity;
import com.jeequan.jeepay.service.impl.MchApplymentService;
import com.jeequan.jeepay.service.impl.MchModifyApplymentService;
import com.jeequan.jeepay.service.impl.MchSubInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.tuple.MutablePair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * 瑞银信通道回调处理只有商户进件回调，没有其他的回调
 */
@Slf4j
@Service("ryxpayIsvmchApplymentNotifyService")
public class RyxpayIsvmchApplymentNotifyService implements IIsvmchApplymentNotifyService {

    @Autowired
    private RequestKitBean requestKitBean;

    @Autowired
    private MchApplymentService mchApplymentService;

    @Autowired
    private MchModifyApplymentService modifyApplymentService;

    @Autowired
    private RyxpayMchApplymentService ryxpayMchApplymentService;

    @Autowired
    private RyxpayIsvmchModifyApplymentService ryxpayIsvmchModifyApplymentService;

    @Autowired
    private MchSubInfoService mchSubInfoService;

    @Autowired
    private MchInfoConverter mchInfoConverter;

    @Override
    public MutablePair<String, Object> parseParams(HttpServletRequest request, String urlApplyId) {
        // 这里只写走回调的情况,
        JSONObject auditResult = requestKitBean.reqParam2JSON();
        String applicationId = auditResult.getString("orderId");

        com.jeequan.jeepay.db.entity.MchApplyment mchApplyment = mchApplymentService.lambdaQuery()
                .eq(com.jeequan.jeepay.db.entity.MchApplyment::getChannelApplyNo, applicationId)
                .one();

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

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

        MchModifyApplymentEntity modifyApplymentEntity = null;

        // 该判定是因为消息回来源不是源自通道方的直接通知，此处是通过rabbitmq的消息转发
        if (mchApplyment == null) {
            String applicationId = auditResult.getString("orderId");

            com.jeequan.jeepay.db.entity.MchApplyment dbMchApplyment = mchApplymentService.lambdaQuery()
                    .eq(com.jeequan.jeepay.db.entity.MchApplyment::getChannelApplyNo, applicationId)
                    .one();

            modifyApplymentEntity = modifyApplymentService.getByOrderId(applicationId, CS.IF_CODE.RYXPAY);

            if (dbMchApplyment == null && modifyApplymentEntity == null) {
                return new MutablePair<>(null, retOk(null));
            }

            if (dbMchApplyment != null) {
                mchApplyment = mchInfoConverter.toModel(dbMchApplyment);
            }
        }

        if (mchApplyment != null) {
            String taskStatus = auditResult.getString("status");
            String remark = auditResult.getString("memo");

            MchApplyment result = new MchApplyment();
            result.setChannelVar1(auditResult.toString());
            result.setApplyId(mchApplyment.getApplyId());
            result.setRemark(remark);

            if ("3".equals(taskStatus)) {
                String onlMerId = auditResult.getString("onlMerId");
                ryxpayMchApplymentService.subMchColl(mchApplyment, auditResult);

                result.setChannelMchNo(onlMerId);
                result.setSuccResParameter(auditResult.toJSONString());
                result.setState(MchApplyment.STATE_SUCCESS);

                return new MutablePair<>(result, retOk(null));
            } else if ("5".equals(taskStatus)) {
                // 待签约
                RyxpayApplymentInfo applymentInfo = JSON.parseObject(mchApplyment.getApplyDetailInfo(), RyxpayApplymentInfo.class);

                String merName;
                if (MchApplyment.MERCHANT_TYPE_PERSONAL == mchApplyment.getMerchantType()) {
                    merName = "商户" + applymentInfo.getIdcardName();
                } else {
                    merName = applymentInfo.getMchFullName();
                }

                try {
                    merName = URLEncoder.encode(merName, "UTF-8");
                } catch (UnsupportedEncodingException ignored) {
                }

                String urlTemplate = "https://rjp.ruiyinxin.com/mims2/ruijiaSign/index.html?merInId=%s&merName=%s";
                String url = String.format(urlTemplate, auditResult.getString("merInId"), merName);

                JSONObject channelVar2 = new JSONObject();
                channelVar2.put("signUrl", url);
                // 待签约状态
                result.setChannelVar1(auditResult.toJSONString());
                result.setChannelVar2(channelVar2.toJSONString());
                result.setState(MchApplyment.STATE_WAIT_SIGN);

                return new MutablePair<>(result, retOk(null));
            } else {
                // 进件失败
                result.setApplyId(mchApplyment.getApplyId());
                result.setChannelVar1(auditResult.toString());
                result.setApplyErrorInfo("[" + remark + "]");
                result.setState(MchApplyment.STATE_REJECT_WAIT_MODIFY);

                return new MutablePair<>(result, retOk(null));
            }
        }

        if (modifyApplymentEntity != null) {
            // 结算信息变更回调
            String status = auditResult.getString("status");
            String memo = auditResult.getString("memo");

            if ("3".equals(status)) {
                modifyApplymentEntity.setState(MchApplyment.STATE_SUCCESS);
                ryxpayIsvmchModifyApplymentService.localModifySettlement(new MutablePair<>(mchInfoConverter.toModel(modifyApplymentEntity), mchApplyment));
            } else {
                modifyApplymentEntity.setState(MchApplyment.STATE_REJECT_WAIT_MODIFY);
                modifyApplymentEntity.setRemark(memo);
                modifyApplymentService.updateById(modifyApplymentEntity);
            }

            return new MutablePair<>(null, retOk(null));
        }

        return new MutablePair<>(null, retOk(null));
    }

    @Override
    public ResponseEntity<?> retOk(Object params) {
        JSONObject result = new JSONObject();
        result.put("code", "0");
        result.put("msg", "通知成功");

        return ResponseEntity.ok(result);
    }
}
