package com.jianshui.invoice.task;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.jianshui.common.utils.StringUtils;
import com.jianshui.common.utils.spring.SpringUtils;
import com.jianshui.invoice.domain.Invoice;
import com.jianshui.invoice.domain.InvoiceBack;
import com.jianshui.invoice.domain.Redinfo;
import com.jianshui.invoice.mapper.InvoiceBackMapper;
import com.jianshui.invoice.mapper.InvoiceMapper;
import com.jianshui.system.domain.CompanyserviceProp;
import com.jianshui.system.service.ICompanyservicePropService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 定时任务-发票推送
 * 
 * @author 简税平台
 */
@Component("invoiceBackTask")
@Slf4j
public class InvoiceBackTask
{

    @Autowired
    private InvoiceBackMapper invoiceBackMapper;

    @Autowired
    private InvoiceMapper invoiceMapper;


    public void bkParams(String params)
    {
        // 默认10次
        int j = params == null ? 10:  Integer.parseInt(params) ;

        log.info("[重汽回调定时任务开始执行]---{}次",params);

        QueryWrapper<InvoiceBack> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", "0").or().eq("status","2");
        List<InvoiceBack> invoiceBackList = invoiceBackMapper.selectList(queryWrapper);

        for (InvoiceBack invoiceBack : invoiceBackList) {

            int i = 0;

            while (i < j){

                String id = invoiceBack.getSystemOrderno();
                String identity = invoiceBack.getIdentity();

                ICompanyservicePropService companyserviceProp = SpringUtils.getBean(ICompanyservicePropService.class);
                CompanyserviceProp secretIdProp = companyserviceProp.selectPropByKey(Long.valueOf(identity), "aisino_callback_url");

                if(secretIdProp == null || secretIdProp.getValue()==null || "".equals(secretIdProp.getValue())){
                    log.info("【控制台】发票回调，未配置回调地址{}"+identity);
                    invoiceBack.setStatus("3");
                    invoiceBack.setBackMsg("未配置回调地址");
                    invoiceBackMapper.updateInvoiceBack(invoiceBack);
                    break;
                }

                String callBackUrl = secretIdProp.getValue();
                log.info("【控制台】发票回调，回调地址{}",callBackUrl);

                if (id == null) {
                    log.info("【控制台】发票回调，id为空");
                    invoiceBack.setStatus("3");
                    invoiceBack.setBackMsg("id为空");
                    invoiceBackMapper.updateInvoiceBack(invoiceBack);
                    break;
                }

                Invoice invoice = invoiceMapper.selectByOutTradeOrderno(Long.valueOf(identity),id,"0");
                if (invoice == null) {
                    log.info("【控制台】发票信息未查询到，id={}", id);
                    invoice = new Invoice();
                    invoice.setOutTradeOrderno(invoiceBack.getSystemOrderno());
                    invoice.setState(22);
                    invoice.setMessage(invoiceBack.getResultMsg());
                }

                try {
                    /*cn.hutool.json.JSONObject jsonResult = new cn.hutool.json.JSONObject();
                    jsonResult.set("status",invoiceBack.getResultCode());
                    jsonResult.set("message",invoiceBack.getResultMsg());
                    jsonResult.set("data",invoice);*/

                    log.info("【控制台】发票回调接口，发送数据开始，id={},orderno={},callBackUrl={},param={}", id,invoice.getOutTradeOrderno(),callBackUrl,JSONUtil.toJsonStr(invoice));
                    String result = HttpUtil.post(callBackUrl, JSONUtil.toJsonStr(invoice));
                    log.info("【控制台】发票回调接口，发送数据结束，id={},接口返回信息={}", id, result);
                    JSONObject jsonObject = JSONUtil.parseObj(result);
                    if(jsonObject != null){
                        String status = jsonObject.get("status") != null ? jsonObject.get("status").toString():"";
                        String message = jsonObject.get("message")!= null ? jsonObject.get("message").toString():"";

                        if("0000".equals(status)){
                            invoiceBack.setStatus("1");
                            invoiceBack.setBackMsg(message);
                            invoiceBackMapper.updateInvoiceBack(invoiceBack);
                        }else if("9999".equals(status)){
                            invoiceBack.setStatus("3");
                            invoiceBack.setBackMsg(message);
                            invoiceBackMapper.updateInvoiceBack(invoiceBack);
                        }else {
                            invoiceBack.setStatus("3");
                            invoiceBack.setBackMsg(status+message);
                            invoiceBackMapper.updateInvoiceBack(invoiceBack);
                        }
                        break;
                    }
                } catch (Exception e) {
                    log.info("【控制台】发票回调接口，发送数据异常，id={}", id);
                    invoiceBack.setStatus("2");
                    invoiceBack.setBackMsg("发送数据异常");
                    invoiceBackMapper.updateInvoiceBack(invoiceBack);
                }
                i++;

            }

            // 一直没结果
            if(i == j){
                invoiceBack.setStatus("3");
                invoiceBack.setBackMsg("调用次数上限一直失败！");
                invoiceBackMapper.updateInvoiceBack(invoiceBack);
            }

        }
        log.info("[重汽回调定时任务执行结束]---");
    }









}
