package com.jeequan.jeepay.pay.mq.channel.zftpay;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.domain.AntMerchantExpandIndirectZftCreateModel;
import com.alipay.api.request.AntMerchantExpandIndirectZftCreateRequest;
import com.alipay.api.response.AntMerchantExpandIndirectZftCreateResponse;
import com.jeequan.jeepay.converter.MchInfoConverter;
import com.jeequan.jeepay.core.model.params.zftpay.ZftpayIsvParams;
import com.jeequan.jeepay.db.entity.MchApplyment;
import com.jeequan.jeepay.pay.mq.channel.IsvAuditReceiver;
import com.jeequan.jeepay.service.impl.MchApplymentService;
import com.jeequan.jeepay.thirdparty.channel.zftpay.ZftpayKit;
import com.jeequan.jeepay.thirdparty.channel.zftpay.ZftpayMchApplymentService;
import com.jeequan.jeepay.thirdparty.service.ConfigContextQueryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * TODO
 *
 * @author deng
 * @since 2024/4/7
 */
@Slf4j
@Component("zftpayAuditReceiver")
public class ZftAuditReceiver implements IsvAuditReceiver {

    @Autowired
    private ZftpayMchApplymentService applymentService;

    @Autowired
    private MchInfoConverter mchInfoConverter;

    @Autowired
    private ConfigContextQueryService configContextQueryService;
    @Autowired
    private MchApplymentService mchApplymentService;

    @Override
    public void consume(MchApplyment mchApplyment) {
        log.info("直付通进件请求开始, 商户号:{}", mchApplyment.getApplyId());
        MchApplyment result = new MchApplyment();
        result.setApplyId(mchApplyment.getApplyId());

        com.jeequan.jeepay.core.entity.MchApplyment model = mchInfoConverter.toModel(mchApplyment);

        ZftpayIsvParams isvParams = (ZftpayIsvParams) configContextQueryService.queryIsvParams(model);

        try {
            AntMerchantExpandIndirectZftCreateModel applymentParams = applymentService.getApplymentParams(model);
            AntMerchantExpandIndirectZftCreateRequest request = new AntMerchantExpandIndirectZftCreateRequest();
            request.setBizModel(applymentParams);
            AntMerchantExpandIndirectZftCreateResponse response = ZftpayKit.req(isvParams, request);

            String orderId = response.getOrderId();
            result.setChannelVar1(JSONObject.toJSONString(response));
            result.setChannelApplyNo(orderId);
            result.setState(com.jeequan.jeepay.core.entity.MchApplyment.STATE_AUDITING);
            result.setRemainStep((byte) 0);
            mchApplymentService.updateById(result);
        } catch (Exception e) {
            log.error("直付通请求异常", e);

            result.setRemainStep((byte) 0);
            result.setState(com.jeequan.jeepay.core.entity.MchApplyment.STATE_REJECT_WAIT_MODIFY);
            result.setApplyErrorInfo("[" + e.getMessage() + "]");
            mchApplymentService.updateById(result);
        }

    }
}
