package com.jianshui.invoice.consumer;

import com.alibaba.fastjson.JSONObject;
import com.jianshui.common.core.domain.AjaxResult;
import com.jianshui.common.core.domain.entity.Companyservice;
import com.jianshui.common.core.redis.RedisCache;
import com.jianshui.invoice.domain.BillInfo;
import com.jianshui.invoice.domain.Invoice;
import com.jianshui.invoice.domain.Redinfo;
import com.jianshui.invoice.factory.IInvoiceResponseFactory;
import com.jianshui.invoice.mapper.BillInfoMapper;
import com.jianshui.invoice.service.IInvoiceResponseService;
import com.jianshui.queue.consumer.RedisQueueConsumer;
import com.jianshui.queue.dto.RedisQueueMessage;
import com.jianshui.queue.utils.RedisQueueUtil;
import com.jianshui.system.service.ICompanyserviceService;
import com.jianshui.system.service.IServiceManageService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Description 发票作废 回调消费者
 * @Author 巩权林
 * @Date 2022-04-19 17:45
 **/
@Slf4j
@Component(value = "invoice_redinfo_callback_consumer")
public class InvoiceRedInfoCallbackConsumer implements RedisQueueConsumer {

    @Autowired
    private BillInfoMapper billInfoMapper;

    @Autowired
    private ICompanyserviceService iCompanyserviceService;

    @Autowired
    private IInvoiceResponseFactory invoiceResponseFactory;

    @Autowired
    private IServiceManageService serviceManageService;

    @Autowired
    private RedisCache redisCache;


    @Override
    public String getQueueName() {
        return "invoice_redinfo_callback_consumer";
    }

    /**
     * 开始消费
     *
     * @param redisQueueMessage
     */
    @SneakyThrows
    @Override
    public void consume(RedisQueueMessage redisQueueMessage) {
        // 获取原始消息
        Object data1 = redisQueueMessage.getData();
        Redinfo data = ((JSONObject) data1).toJavaObject(Redinfo.class);
        if (!StringUtils.equals(data.getClass().getName(), "com.jianshui.invoice.domain.Redinfo")) {
            log.error("【销项消费者】【红字信息表申请回调】消息类型非Invoice，异常。原始数据{}", JSONObject.toJSONString(data));
            return;
        }

        // 获取原始billInfo
        Redinfo invoice = (Redinfo) data;
        BillInfo billInfo = billInfoMapper.selectBillInfoById(invoice.getBillInfoId());
        // 如果发票不存在
        // if (billInfo == null) {
        //     log.error("【销项消费者】【红字信息表申请回调】billinfo不存在，异常。原始数据{}", JSONObject.toJSONString(data));
        // }

        Companyservice companyservice = iCompanyserviceService.selectCompanyserviceByCompanyid(invoice.getCompanyId());

        // 查询发票serviceKey
        String responseAdapterKey = serviceManageService.getResponseAdapterKey("invoice", companyservice.getCompanyid());
        IInvoiceResponseService responseService = invoiceResponseFactory.getService(responseAdapterKey);
        AjaxResult result = responseService.callback(billInfo, null, invoice, companyservice, "add_redinfo");
        if (result.isError()) {
            // 判断一下是否需要重新进入队列
            if (result.getCode() == 501) {
                String keys = "invoice_redinfo_callback_consumer" + companyservice.getCompanyid() + "_" + billInfo.getSystemOrderno();
                Integer queryTimes = redisCache.getCacheObject(keys);
                // 查询重试次数超过20次，就不查了
                if (queryTimes != null && queryTimes > 20) {
                    log.error("【销项消费者】【红字信息表申请回调】回调接口始终失败，不再回调：{}", JSONObject.toJSONString(billInfo));
                    redisCache.deleteObject(keys);
                    return;
                }
                if (queryTimes == null) {
                    queryTimes = 0;
                }
                queryTimes += 1;
                redisCache.setCacheObject(keys, queryTimes);
                log.info("【销项消费者】【红字信息表申请回调】回调接口失败，重新投入队列");
                RedisQueueUtil.build().setData(invoice).onQueue("invoice_redinfo_callback_consumer").retry(0).dispatch();
                return;
            }

            log.info("【销项消费者】【红字信息表申请回调】回调接口失败");
            return;
        }

        log.info("【销项消费者】【红字信息表申请回调】回调接口成功");
    }

    @Override
    public void error(RedisQueueMessage redisQueueMessage) {

    }
}
