package com.jianshui.invoice.utils.aisino.console;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.codec.Base64;
import cn.hutool.core.net.URLDecoder;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jianshui.common.core.domain.AjaxResult;
import com.jianshui.common.core.domain.entity.Companyservice;
import com.jianshui.common.core.domain.entity.CompanyserviceDetail;
import com.jianshui.common.exception.jianshui.JianshuiServiceException;
import com.jianshui.invoice.constant.aisino.console.AisinoConsoleConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * 总部控制台工具类
 *
 * @author dxk
 * @date 2022年06月27日 16:03
 */
@Slf4j
public class AisinoConsoleUtil {


    /**
     * 总部-控制台：发送报文
     *
     * @param SID
     * @param SIDParam
     * @param companyservice
     * @return com.jianshui.common.core.domain.AjaxResult
     * @author dxk
     * @date 2022/6/27 16:51
     */
    public static AjaxResult sendRequest(Integer SID, JSON SIDParam, Companyservice companyservice) throws UnsupportedEncodingException {

        //校验金税盘是否开启，未开启的话调用SID=12打开金税盘 k:这里有没有必要每次都检查金税盘状态？
        //1.查询金税盘状态

       /* JSONObject jsonObject = new JSONObject();
        jsonObject.put("SIDParam","<?xml version=\"1.0\" encoding=\"GBK\"?><FPXT_COM_INPUT><ID>0400</ID><DATA></DATA></FPXT_COM _INPUT>");

        String gtp = jsonObject.toJSONString();
        AjaxResult ajaxResult = null;
        try {
            ajaxResult = sendAisinoConsole(AisinoConsoleConstants.QUERY_GTP_STSTUS,JSONUtil.parse(gtp),companyservice);
        }catch (Exception e){
            e.printStackTrace();
            log.error("【销项】【总部控制台】查询金税盘状态 调用失败");
        }
        if(ajaxResult.isError()){
            return ajaxResult;
        }
        cn.hutool.json.JSONObject resultJSON = JSONUtil.parseObj(ajaxResult.get("data"));
        String retcode = resultJSON.get("retcode") != null ? resultJSON.get("retcode").toString() : "";
        if("1".equals(retcode)){
            //2.如果金税盘未开启，打开金税盘
            try {
                JSONObject gtpTemp = new JSONObject();
                gtpTemp.put("web",0);
                gtp = JSONUtil.toJsonStr(gtpTemp);
                ajaxResult = sendAisinoConsole(AisinoConsoleConstants.START_INVOICE_SERVICE,JSONUtil.parse(gtp),companyservice);
            }catch (Exception e){
                e.printStackTrace();
                log.error("【销项】【总部控制台】打开金税盘 调用失败");
            }
            if(ajaxResult.isError()){
                return ajaxResult;
            }
        }*/

        AjaxResult ajaxResult = null;
        //调用实际发送的方法
        try{
            ajaxResult = sendAisinoConsole(SID,SIDParam,companyservice);
            return ajaxResult;
        }catch (Exception e){
            e.printStackTrace();
            log.error("【销项】【总部控制台】调用失败");
        }

        return AjaxResult.error("请求失败！");
    }

    /**
     * 请求总部控制台
     * @author dxk
     * @date 2022/6/29 17:43
     * @param SID
     * @param SIDParam
     * @param companyservice
     * @return com.jianshui.common.core.domain.AjaxResult
     */
    public static AjaxResult sendAisinoConsole(Integer SID, JSON SIDParam, Companyservice companyservice) throws UnsupportedEncodingException {
        //参数校验
        if (SID == null) {
            throw new JianshuiServiceException("未获取到请求接口，请联系管理员！");
        }
        if (BeanUtil.isEmpty(SIDParam)) {
            throw new JianshuiServiceException("未获取到请求参数，请联系管理员！");
        }
        if (BeanUtil.isEmpty(companyservice)) {
            throw new JianshuiServiceException("未获取到企业信息，请联系管理员！");
        }

        //JSON明文BASE64加密，字符集GB2312，替换+为-
        String param = Base64.encode(JSONUtil.toJsonStr(SIDParam),"GB2312").replace("+", "_");
        //获取请求地址
        List<CompanyserviceDetail> companyserviceDetailList = companyservice.getCompanyserviceDetailList();
        if(CollectionUtils.isEmpty(companyserviceDetailList)){
            throw new JianshuiServiceException("请求地址未配置，请联系管理员！");
        }
        String clientIp = companyserviceDetailList.get(0).getClientIp();
        //拼接请求地址
        String requestUrl = clientIp + "?SID=" + SID + "&SIDParam=" + param;
        try {

            log.info("【总部控制台工具类】请求报文：{}，原始报文：{},SID:{}", param, JSONUtil.toJsonStr(SIDParam), SID);
            String result = HttpUtil.get(requestUrl);
            log.info("【总部控制台工具类】请求返回原始报文：" + result);

            //{“retcode”: “1”, “retmsg”:“XXX”}，返回异常信息 retcode=-1），返回报文统一封装成 {“ENCMSG”:“加密串”}。
            if (StrUtil.isEmpty(result)) {
                throw new JianshuiServiceException("未获取到接口返回信息！");
            }

            //返回报文解密
            result = JSONUtil.parse(result).getByPath("ENCMSG") != null ? JSONUtil.parse(result).getByPath("ENCMSG").toString() : "-1";
            if ("-1".equals(result)) {
                throw new JianshuiServiceException("未获取到接口返回信息！");
            }
            String decodeResult = Base64.decodeStr(result.replace("_", "+"),"GB2312");
            log.info("【总部控制台工具类】请求返回解密报文：" + decodeResult);

            JSON resultJSON = JSONUtil.parse(decodeResult);
            return AjaxResult.success(resultJSON);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("【销项】【总部控制台】调用失败，调用url=" + requestUrl);
        }
        return AjaxResult.error("请求失败！");
    }


    // TODO-dxk: 2023/2/27 xml格式报文。

    /**
     * 总部-控制台：发送报文
     *
     * @param SID
     * @param SIDParam
     * @param companyservice
     * @return com.jianshui.common.core.domain.AjaxResult
     * @author dxk
     * @date 2022/6/27 16:51
     */
    public static AjaxResult sendRequest(Integer SID, String SIDParam, Companyservice companyservice) throws UnsupportedEncodingException {

        AjaxResult ajaxResult = null;
        //调用实际发送的方法
        try{
            ajaxResult = sendAisinoConsole(SID,SIDParam,companyservice);
            return ajaxResult;
        }catch (Exception e){
            e.printStackTrace();
            log.error("【销项】【总部控制台】调用失败");
        }

        return AjaxResult.error("请求失败！");
    }

    /**
     * 请求总部控制台
     * @author dxk
     * @date 2022/6/29 17:43
     * @param SID
     * @param SIDParam
     * @param companyservice
     * @return com.jianshui.common.core.domain.AjaxResult
     */
    public static AjaxResult sendAisinoConsole(Integer SID, String SIDParam, Companyservice companyservice) throws UnsupportedEncodingException {
        //参数校验
        if (SID == null) {
            throw new JianshuiServiceException("未获取到请求接口，请联系管理员！");
        }
        if (BeanUtil.isEmpty(SIDParam)) {
            throw new JianshuiServiceException("未获取到请求参数，请联系管理员！");
        }
        if (BeanUtil.isEmpty(companyservice)) {
            throw new JianshuiServiceException("未获取到企业信息，请联系管理员！");
        }


        //JSON明文BASE64加密，字符集GB2312，替换+为-
        String param = Base64.encode(SIDParam,"GB2312").replace("+", "_");

        param = "<?xml version=\"1.0\" encoding=\"GBK\"?>\n" +
                "<FPXT_COM_INPUT>\n" +
                "<ID>"+SID+"</ID>\n" +
                "<DATA>"+param+"</DATA>\n" +
                "</FPXT_COM_INPUT>\n";

        //获取请求地址
        List<CompanyserviceDetail> companyserviceDetailList = companyservice.getCompanyserviceDetailList();
        if(CollectionUtils.isEmpty(companyserviceDetailList)){
            throw new JianshuiServiceException("请求地址未配置，请联系管理员！");
        }
        String clientIp = companyserviceDetailList.get(0).getClientIp();
        //拼接请求地址

        param = "<?xml version=\"1.0\" encoding=\"GBK\"?><FPXT_COM_INPUT><ID>129</ID><DATA>PEZQWFQ_CiAgICA8SU5QVVQ_CiAgICAgICAgPFJlZEludlJlcUJpbGw_PHJlcW5zcnNiaD45MTEzMDkzMDY3ODUxMTU1WFk8L3JlcW5zcnNiaD48ZmpoPjEyMzwvZmpoPjxqc3BiaD42NjEwMjQ2NDMwNjg8L2pzcGJoPjxvdXRUcmFkZU9yZGVybm8_NjYxMDI0NjQzMDY4MjMwMjE4MTAzNTI0PC9vdXRUcmFkZU9yZGVybm8_PHJlZEluZm9UeXBlPjA8L3JlZEluZm9UeXBlPjxvcmlnaW5GcGRtPjM3MDAyMjIxMzA8L29yaWdpbkZwZG0_PG9yaWdpbkZwaG0_MTA0MDUxNzI8L29yaWdpbkZwaG0_PGJpbGxJbnB1dFRpbWU_MjAyMi0xMS0xMTwvYmlsbElucHV0VGltZT48dGF4VHlwZT4xPC90YXhUeXBlPjxtdWx0VGF4UmF0ZT4wPC9tdWx0VGF4UmF0ZT48RGF0ZT4yMDIyLTExLTExPC9EYXRlPjxidXllck5hbWU_utOxsdbQsaa3qMC8udy8/tbG1OzT0M/euavLvjwvYnV5ZXJOYW1lPjxidXllclRheG51bT45MTEzMDkzMDY3ODUxMTU1WFk8L2J1eWVyVGF4bnVtPjxzZWxsZXJOYW1lPrq90MWy4srUxvPStTwvc2VsbGVyTmFtZT48c2VsbGVyVGF4bnVtPjM3MDEwMzk5OTk5OTAzMDwvc2VsbGVyVGF4bnVtPjxBbW91bnQ_LTE5NTQ1MS4zMjwvQW1vdW50Pjx0YXhyYXRlPjAuMDM8L3RheHJhdGU_PHRheD4tMTI3MDQuMzQ8L3RheD48YXBwbHlSZW1hcms_MDAwMDAwMDEwMDwvYXBwbHlSZW1hcms_PGJtYmJoPjIzMjMyMzI8L2JtYmJoPjxTTEJaPjA8L1NMQlo_PFJlZEludlJlcUJpbGxNeD48R29vZHNNeD48Z29vZE5hbWU_xtXMvLDlUTIzNUI8L2dvb2ROYW1lPjxzcGVjPjQwKjIyMDAqTDwvc3BlYz48cHJpY2U_MzYxOS40NjkwMjY1NTwvcHJpY2U_PG51bT4tMjc8L251bT48dGF4ZnJlZWFtdD4tOTc3MjUuNjY8L3RheGZyZWVhbXQ_PHRheHJhdGU_MC4xMzwvdGF4cmF0ZT48dGF4Pi0xMjcwNC4zNDwvdGF4Pjx3aXRoVGF4RmxhZz5OPC93aXRoVGF4RmxhZz48c3BibT4xMDgwMjA3MDc8L3NwYm0_PHloemNicz4wPC95aHpjYnM_IDwvR29vZHNNeD4gICAgICAgICAgICA8L1JlZEludlJlcUJpbGxNeD4KICAgICAgICA8L1JlZEludlJlcUJpbGw_CiAgICA8L0lOUFVUPgo8L0ZQWFQ_</DATA></FPXT_COM_INPUT>";

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("param",param);
        String aa = JSONUtil.toJsonStr(jsonObject);

        String requestUrl = clientIp + "?SID=33&SIDParam=" +  Base64.encode(aa,"GB2312").replace("+", "_");
        requestUrl = requestUrl.replaceAll("\r|\n","");
        try {

            log.info("【总部控制台工具类】请求报文：{}，原始报文：{},SID:{}", param, JSONUtil.toJsonStr(SIDParam), SID);
            String result = HttpUtil.get(requestUrl);
            log.info("【总部控制台工具类】请求返回原始报文：" + result);

            //{“retcode”: “1”, “retmsg”:“XXX”}，返回异常信息 retcode=-1），返回报文统一封装成 {“ENCMSG”:“加密串”}。
            if (StrUtil.isEmpty(result)) {
                throw new JianshuiServiceException("未获取到接口返回信息！");
            }

            //返回报文解密
            result = JSONUtil.parse(result).getByPath("ENCMSG") != null ? JSONUtil.parse(result).getByPath("ENCMSG").toString() : "-1";
            if ("-1".equals(result)) {
                throw new JianshuiServiceException("未获取到接口返回信息！");
            }
            String decodeResult = Base64.decodeStr(result.replace("_", "+"),"GB2312");
            log.info("【总部控制台工具类】请求返回解密报文：" + decodeResult);

            JSON resultJSON = JSONUtil.xmlToJson(decodeResult);
            return AjaxResult.success(resultJSON);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("【销项】【总部控制台】调用失败，调用url=" + requestUrl);
        }
        return AjaxResult.error("请求失败！");
    }






















}
