package com.jeequan.jeepay.pay.mq;

import com.alibaba.fastjson.JSONObject;
import com.jeequan.jeepay.components.mq.model.MchAuditNotifyMQ;
import com.jeequan.jeepay.components.mq.model.MchAuditThirdNotifyMQ;
import com.jeequan.jeepay.components.mq.vender.IMQSender;
import com.jeequan.jeepay.converter.MchInfoConverter;
import com.jeequan.jeepay.core.interfaces.paychannel.IIsvmchApplymentNotifyService;
import com.jeequan.jeepay.core.utils.SpringBeansUtil;
import com.jeequan.jeepay.db.entity.MchApplyment;
import com.jeequan.jeepay.service.impl.MchApplymentService;
import com.jeequan.jeepay.thirdparty.channel.yspay.YspayApplymentApiService;
import com.jeequan.jeepay.thirdparty.channel.yspay.YspayMchApplymentService;
import com.jeequan.jeepay.thirdparty.service.ConfigContextQueryService;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
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.Component;
import org.springframework.util.Assert;

@Data
@NoArgsConstructor
@AllArgsConstructor
@Slf4j
@Component
public class MchAuditNotifyMQReceiver implements MchAuditNotifyMQ.IMQReceiver {

    @Autowired
    private MchApplymentService mchApplymentService;

    @Autowired
    private YspayApplymentApiService yspayApplymentApiService;

    @Autowired
    private YspayMchApplymentService yspayMchApplymentService;

    @Autowired
    private ConfigContextQueryService configContextQueryService;

    @Autowired
    private IMQSender mqSender;

    @Autowired
    private MchInfoConverter infoConverter;

    @Override
    public void receive(MchAuditNotifyMQ.MsgPayload payload) {

        JSONObject notifyJSON = payload.getNotifyData();
        String ifCode = payload.getIfCode();

        IIsvmchApplymentNotifyService notifyService = SpringBeansUtil.getBean(ifCode + "IsvmchApplymentNotifyService", IIsvmchApplymentNotifyService.class);
        Assert.notNull(notifyService, "通知回调服务类缺失");
        MutablePair<com.jeequan.jeepay.core.entity.MchApplyment, ResponseEntity> responseEntityMutablePair = notifyService.doNotify(null, notifyJSON, null);

        com.jeequan.jeepay.core.entity.MchApplyment result = responseEntityMutablePair.getLeft();
        mchApplymentService.updateById(infoConverter.toDbEntity(result));

        if (result.getState() == MchApplyment.STATE_SUCCESS || result.getState() == MchApplyment.STATE_SUCCESS_NEED_SECOND_VERIFY) {
            mchApplymentService.onApplymentSuccess(result.getApplyId());
            mqSender.send(MchAuditThirdNotifyMQ.build(result.getApplyId(), MchAuditThirdNotifyMQ.TYPE_AUDIT));
        }

        log.info("进件通知完成。 applyId={}, parseState = {} =====", result.getApplyId(), result.getState());
    }
}
