package com.jianshui.invoice.task;

import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.jianshui.common.core.domain.entity.Companyservice;
import com.jianshui.common.utils.StringUtils;
import com.jianshui.common.utils.spring.SpringUtils;
import com.jianshui.invoice.constant.aisino.console.AisinoConsoleConstants;
import com.jianshui.invoice.domain.Invoice;
import com.jianshui.invoice.domain.InvoiceBack;
import com.jianshui.invoice.domain.Redinfo;
import com.jianshui.invoice.domain.dto.ExportVehicleDTO;
import com.jianshui.invoice.domain.dto.HXResponse;
import com.jianshui.invoice.mapper.InvoiceBackMapper;
import com.jianshui.invoice.mapper.InvoiceMapper;
import com.jianshui.invoice.service.IInvoiceApiService;
import com.jianshui.invoice.service.impl.api.AisinoConsoleInvoiceApiZhongQiServiceImpl;
import com.jianshui.system.domain.CompanyserviceProp;
import com.jianshui.system.service.ICompanyservicePropService;
import com.jianshui.system.service.ICompanyserviceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;

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

    @Autowired
    private InvoiceBackMapper invoiceBackMapper;

    @Autowired
    private InvoiceMapper invoiceMapper;

    @Autowired
    private ICompanyserviceService iCompanyserviceService;

    @Autowired
    private ICompanyservicePropService propService;


    /**
    * @author kk
    * @date  9:03
    * @param: [params]
    * @return:
     * 开票回调
    */
    public void bkParams(String params)
    {
        // TODO: 2023/11/9 回调次数处理 
        // 默认1次  定时任务控制，补偿机制
        int j = params == null ? 1:  Integer.parseInt(params) ;

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

        QueryWrapper<InvoiceBack> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", "0").or().eq("status","2").or().eq("status","3");
        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("未配置回调地址");
                    invoiceBack.setUpdateTime(new Date());
                    invoiceBackMapper.updateInvoiceBack(invoiceBack);
                    break;
                }

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

                if (id == null) {
                    log.info("【控制台】发票回调，id为空");
                    invoiceBack.setStatus("3");
                    invoiceBack.setBackMsg("id为空");
                    invoiceBack.setUpdateTime(new Date());
                    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() != null ? invoiceBack.getResultMsg().substring(0,200):"");
                }

                try {

                    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 != null ? message.substring(0, Math.min(message.length(), 200)) : "");
                            invoiceBack.setUpdateTime(new Date());
                            invoiceBackMapper.updateInvoiceBack(invoiceBack);
                        }else if("9999".equals(status)){
                            invoiceBack.setStatus("3");
                            invoiceBack.setBackMsg(message != null ? message.substring(0, Math.min(message.length(), 200)) : "");
                            invoiceBack.setUpdateTime(new Date());
                            invoiceBackMapper.updateInvoiceBack(invoiceBack);
                        }else {
                            invoiceBack.setStatus("3");
                            invoiceBack.setBackMsg(status+message != null ? message.substring(0, Math.min(message.length(), 200)) : "");
                            invoiceBack.setUpdateTime(new Date());
                            invoiceBackMapper.updateInvoiceBack(invoiceBack);
                        }
                        break;
                    }
                } catch (Exception e) {
                    log.info("【控制台】发票回调接口，发送数据异常，id={}", id);
                    invoiceBack.setStatus("2");
                    invoiceBack.setBackMsg("发送数据异常");
                    invoiceBack.setUpdateTime(new Date());
                    invoiceBackMapper.updateInvoiceBack(invoiceBack);
                }
                i++;

            }

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

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


    /**
    * @author kk
    * @date 2023/11/14 9:03
    * @param: []
    * @return:
     * 机动车加密导出-定时任务
    */
    public void exportVehicleInvoice(){
        // 查询配置的nginx地址
        log.info("[重汽机动车加密导出定时任务开始]---");
        CompanyserviceProp companyservicePropQuery = new CompanyserviceProp();
        companyservicePropQuery.setKey("aisino_nginx_url");
        List<CompanyserviceProp> companyservicePropList = propService.selectCompanyservicePropList(companyservicePropQuery);
        log.info("[重汽机动车加密导出定时任务]获取到待发送identity集合，{}",JSONUtil.toJsonStr(companyservicePropList));
        for (CompanyserviceProp companyserviceProp : companyservicePropList) {

            // 参数组装
            Companyservice companyservice = iCompanyserviceService.selectCompanyserviceByCompanyid(companyserviceProp.getCompanyid());

            ExportVehicleDTO exportVehicleDTO = new ExportVehicleDTO();
            exportVehicleDTO.setSavePath(AisinoConsoleConstants.SAVE_PATH);
            exportVehicleDTO.setFPZL("");
            exportVehicleDTO.setKSRQ(DateUtil.today());
            exportVehicleDTO.setJSRQ(DateUtil.today());

            try {
                IInvoiceApiService iInvoiceApiService = new AisinoConsoleInvoiceApiZhongQiServiceImpl();
                HXResponse hxResponse = iInvoiceApiService.exportVehicleInvoice(JSON.parseObject(JSONUtil.toJsonStr(exportVehicleDTO)),companyservice);
                log.info("[重汽机动车加密导出定时任务]返回结果，hxResponse={}，identity={}",hxResponse,companyserviceProp.getCompanyid());
            } catch (Exception e) {
                throw new RuntimeException(e);
            }

        }
        log.info("[重汽机动车加密导出定时任务结束]---");

    }




}
