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

import com.jeequan.jeepay.components.mq.vender.IMQSender;
import com.jeequan.jeepay.converter.MchInfoConverter;
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.lklspay.LklspayMchApiService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component("lklspayAuditReceiver")
public class LklspayAuditReceiver implements IsvAuditReceiver {

    @Autowired
    private LklspayMchApiService lklspayMchApiService;

    @Autowired
    private MchInfoConverter infoConverter;

    @Autowired
    private MchApplymentService mchApplymentService;

    @Autowired
    private IMQSender mqSender;

    @Override
    public void consume(MchApplyment mchApplyment) {
        log.info("拉卡拉拓客进件业务开始, 商户号为{}", mchApplyment.getApplyId());

        MchApplyment result = new MchApplyment();

        com.jeequan.jeepay.core.entity.MchApplyment uploadImgResult;
        // 获取详细参数
        try {
            // 上传图片, 并返回图片的ID等数据
            uploadImgResult = lklspayMchApiService.uploadImg(infoConverter.toModel(mchApplyment));
            // 参数保存
            infoConverter.cp(mchApplyment, uploadImgResult);
            // 提交资料
            result = infoConverter.toDbEntity(lklspayMchApiService.submitMchInfo(uploadImgResult));
            //
            result.setApplyId(mchApplyment.getApplyId());
            result.setState(MchApplyment.STATE_AUDITING);
            result.setRemainStep((byte) 0);

            mchApplymentService.updateById(result);

        } catch (Exception e) {
            log.info("进件异常", e);
            result.setApplyId(mchApplyment.getApplyId());
            result.setState(MchApplyment.STATE_REJECT_WAIT_MODIFY);
            result.setApplyErrorInfo("[" + e.getMessage() + "]");
            mchApplymentService.updateById(result);
        }
    }
}
