package com.hc.web.config.util;

import com.alibaba.fastjson.JSON;
import com.hc.business.model.ClassConfig;
import com.hc.business.model.UserInvoices;
import com.hc.business.model.invoice.InvoiceDetail;
import com.hc.business.model.invoice.InvoiceOrder;
import com.hc.business.model.invoice.InvoiceOrderCancel;
import com.hc.business.model.invoice.InvoiceQuery;
import com.hc.core.utils.redis.RedisUtil;
import com.hc.core.utils.tool.TimerUtil;
import nuonuo.open.sdk.NNOpenSDK;

import java.util.*;

public class InvoiceHelper {
    //https://sandbox.nuonuocs.cn/open/v1/services
    //https://sdk.nuonuo.com/open/v1/services
//    诺税通SAAS沙箱
//            APPKey SD56531018
//    APPSecret SD3C429B318C485E
//    税号：339901999999142
//    全电票传分机号：8889
//    其他发票 传
//    分机号：0
//    终端号：1
//    机器编号：111111111111
//            *特殊：可测专票冲红，全电冲红流程


//***********************************************************************************************************
    private final String _url = "https://sdk.nuonuo.com/open/v1/services";
    //回调地址
    private final String _callBackUrl ="http://jxjy.cfefe.com/new/api/invoice/scan";
    //private final String _callBackUrl = "http://zgkjxh.cfefe.com/new/api/invoice/scan";
    private final String _appKey = "14150184";//""SD56531018"; //_appKey
    private final String _appSecret = "05EAEF86D43D4A5E";//""SD3C429B318C485E"; //_appSecret
    private final String _salerTaxNum = "91110108MA007JDQ2B";//销方税号339901999999142
    private final String _machineCode = "";//机器编码661608212536
    private final String _terminalNumber = ""; //终端号1
    private final String _extensionNumber = "";//分机号0
    private final String _salerTel = "010-88580482";//销方电话
    private final String _salerAddress = "北京市海淀区阜成路甲28号14层1410";//销方地址
    private final String _clerk = "崔雄";//开票人
//***********************************************************************************************************

    //***********************************************************************************************************
//    private final String _url = "https://sandbox.nuonuocs.cn/open/v1/services";
//    //private final String _callBackUrl = "http://zgkjxh.cfefe.com/new/api/invoice/scan";
//    //private final String _callBackUrl = "http://ymnets.natapp1.cc/new/api/invoice/scan";
//
//    private final String _callBackUrl = "http://javaapi.56go.wang:8072/jxjy-web-0.0.1-SNAPSHOT/new/api/invoice/scan";
//    private final String _appKey = "SD56531018";//""SD56531018"; //_appKey
//    private final String _appSecret = "SD3C429B318C485E";//""SD3C429B318C485E"; //_appSecret
//    private final String _salerTaxNum = "339901999999142";//销方税号339901999999142
//    private final String _machineCode = "";//机器编码661608212536
//    private final String _terminalNumber = ""; //终端号1
//    private final String _extensionNumber = "";//分机号0
//    private final String _salerTel = "010-88580482";//销方电话
//    private final String _salerAddress = "北京市海淀区阜成路甲28号14层1410";//销方地址
//    private final String _clerk = "崔雄";//开票人
    //***********************************************************************************************************


    private final RedisUtil redisUtil;

    public InvoiceHelper(RedisUtil redisUtil) {
        this.redisUtil = redisUtil;
    }

    public String requestAPI(String p_method, String p_content) {
        try {
            NNOpenSDK sdk = NNOpenSDK.getIntance();
            String taxnum = _salerTaxNum;//ISV下授权商户税号，自用型应用置""即可
            String appKey = _appKey;
            String appSecret = _appSecret;
            String method = p_method;//API方法名
            String token = getToken();//访问令牌
            String content = p_content;//API私有请求参数
            String url = _url; //SDK请求地址
            String senid = UUID.randomUUID().toString().replace("-", ""); // 唯一标识，由企业自己生成32位随机码
            String json = sdk.sendPostSyncRequest(url, senid, appKey, appSecret, token, taxnum, method, content); // 请求API
            return json;
        } catch (Exception ex) {
            return "";
        }
    }

    public String getToken() {
        return "0ee5690af42bb070daff400zfqk9qkws";
//        try {
//            String json = NNOpenSDK.getIntance().getMerchantToken(_appKey, _appSecret);
//            ObjectMapper mapper = new ObjectMapper();
//            InvoiceToken invoiceToken = mapper.readValue(json, InvoiceToken.class);
//            //此处需要处理为redis保存时间
//            String key = "nonoToken";
//            if (redisUtil.hasKey(key)) {
//                return (String) redisUtil.get(key);
//            } else {
//                redisUtil.set(key, invoiceToken.getAccess_token(), Integer.valueOf(invoiceToken.getExpires_in()) - 10);
//            }
//            return invoiceToken.getAccess_token();
//        } catch (Exception ex) {
//            return "";
//        }
    }

    //诺税通saas发票申请
    public String ApplyForInvoice(String content) {
        String method = "nuonuo.OpeMplatform.requestBillingNew";
        String result = requestAPI(method, content);
        return result;
    }

    //诺税通saas发票作废
    public String CancelForInvoice(String content) {
        String method = "nuonuo.OpeMplatform.requestBillingNew";
        String result = requestAPI(method, content);
        return result;
    }


    public String QueryInvoiceResult(String content) {
        String method = "nuonuo.OpeMplatform.queryInvoiceResult";
        String result = requestAPI(method, content);
        return result;
    }
//
//    public Map<String, String> getInvoiceUrlByInvoiceSerialNum(String invoiceSerialNum) {
//        String taxnum = "339901999999142";//授权企业税号, 商户填""
//        String method = "nuonuo.ElectronInvoice.queryInvoiceResult";
//        String token = "";
//        Map<String, String> map = new HashMap<>();
//        NNOpenSDK sdk = NNOpenSDK.getIntance();
//        String content = "{" + "\"serialNos\":[" + invoiceSerialNum + "]" + "}";
//        String senid = UUID.randomUUID().toString().replace("-", "");
//        String result = sdk.sendPostSyncRequest(_url, senid, appKey, appSecret, token, taxnum, method, content);
//        System.out.println(result);
//        JSONObject newresult = JSONObject.parseObject(result);
//        String code = newresult.getString("code");
//        String describe = newresult.getString("describe");
//        map.put("code", code);
//        if (code.equals(APPLY_SUCCESS_CODE)) {
//            JSONArray eventInfoData = (JSONArray) newresult.get("result");
//            JSONObject jsonArray = eventInfoData.getJSONObject(0);
//            String status = jsonArray.getString("status");
//            String statusMsg = jsonArray.getString("statusMsg");
//            map.put("status", status);
//            map.put("statusMsg", statusMsg);
//            if (status.equals(SUCCESS_CODE)) {
//                map.put("imgUrl", jsonArray.getString("imgUrls"));
//                map.put("pdfUrl", jsonArray.getString("pdfUrl"));
//                map.put("invoiceCode", jsonArray.getString("invoiceCode"));
//                map.put("invoiceNo", jsonArray.getString("invoiceNo"));
//                map.put("invoiceTime", jsonArray.getString("invoiceTime"));
//            }
//            return map;
//        } else {
//            map.put("statusMsg", describe);
//        }
//        return map;
//    }

    //申请开票
    public String GetKPJsonStr(UserInvoices userInvoices, ClassConfig classConfig) {
        InvoiceOrder order = new InvoiceOrder();
        order.setBuyerName(userInvoices.getInvoicesHead());//购方名称
        order.setBuyerTaxNum(userInvoices.getInvoicesCode());//购方税号
        order.setBuyerTel(userInvoices.getInvoicesTel());//购方电话
        order.setBuyerAddress(userInvoices.getInvoicesAddress());//购方地址
        order.setListFlag("0");
        order.setBuyerAccount(userInvoices.getInvoicesBank() + userInvoices.getInvoicesNo());//购方银行开户行及账号
        order.setOrderNo(userInvoices.getSyncOrderNo());//订单号201701053332079312313
        order.setInvoiceDate(TimerUtil.timeStamp2Date(userInvoices.getCreateTime()));//订单时间2022-01-13 12:30:00
        order.setPushMode("-1");//推送方式：-1,不推送;0,邮箱;1,手机（默认）;2,邮箱、手机
        order.setBuyerPhone(userInvoices.getBuyerPhone());//购方手机（pushMode为1或2时，此项为    必填，同时受企业资质是否必填控制）
        order.setEmail(userInvoices.getBuyerEmail());//推送邮箱（pushMode为0或2时，此项为必填，同时受企业资质是否必填控制）
        order.setInvoiceType("1");//开票类型：1:蓝票;2:红票 （数电票冲红请 对接数电快捷冲红接口）
        order.setInvoiceLine("p");//开票种类
        order.setCallBackUrl(_callBackUrl);//回调地址
        order.setSalerTaxNum(_salerTaxNum);//销方税号
        order.setSalerTel(_salerTel);//销方电话
        order.setSalerAddress(_salerAddress);//销方地址
        order.setMachineCode(_machineCode);//机器编码
        order.setTerminalNumber(_terminalNumber);////终端号
        order.setExtensionNumber(_extensionNumber);//分机号（只能为空或者数字）
        order.setClerk(_clerk);
        List<InvoiceDetail> invoiceDetailList = new ArrayList<>();
        InvoiceDetail invoiceDetail = new InvoiceDetail();
        if(classConfig!=null) {
            invoiceDetail.setGoodsName("培训费一" + classConfig.getClassName());

        }else {
            invoiceDetail.setGoodsName("培训费");
        }
        invoiceDetail.setGoodsCode("3070201020000000000");
        invoiceDetail.setWithTaxFlag("1");
        invoiceDetail.setTaxRate("0.06");
        invoiceDetail.setPrice(userInvoices.getInvoicesPrice().toString());
        invoiceDetail.setNum("1");
        invoiceDetailList.add(invoiceDetail);
        order.setInvoiceDetail(invoiceDetailList);//发票明细
        String jsonString = JSON.toJSONString(order);
        return "{\"order\":"+jsonString+"}";
    }



    //作废掉发票
    public String GetCancelKPJsonStr(UserInvoices userInvoices, ClassConfig classConfig) {
        InvoiceOrderCancel order = new InvoiceOrderCancel();
        order.setBuyerName(userInvoices.getInvoicesHead());//购方名称
        order.setBuyerTaxNum(userInvoices.getInvoicesCode());//购方税号
        order.setBuyerTel(userInvoices.getInvoicesTel());//购方电话
        order.setBuyerAddress(userInvoices.getInvoicesAddress());//购方地址
        order.setListFlag("0");
        order.setBuyerAccount(userInvoices.getInvoicesBank() + userInvoices.getInvoicesNo());//购方银行开户行及账号
        order.setOrderNo(userInvoices.getSyncOrderNo());//订单号201701053332079312313
        order.setInvoiceDate(TimerUtil.timeStamp2Date(userInvoices.getCreateTime()));//订单时间2022-01-13 12:30:00
        order.setPushMode("-1");//推送方式：-1,不推送;0,邮箱;1,手机（默认）;2,邮箱、手机
        order.setBuyerPhone(userInvoices.getBuyerPhone());//购方手机（pushMode为1或2时，此项为    必填，同时受企业资质是否必填控制）
        order.setEmail(userInvoices.getBuyerEmail());//推送邮箱（pushMode为0或2时，此项为必填，同时受企业资质是否必填控制）
        order.setInvoiceType("2");//开票类型：1:蓝票;2:红票 （数电票冲红请 对接数电快捷冲红接口）
        order.setInvoiceLine("p");//开票种类
        order.setCallBackUrl(_callBackUrl);//回调地址
        order.setSalerTaxNum(_salerTaxNum);//销方税号
        order.setSalerTel(_salerTel);//销方电话
        order.setSalerAddress(_salerAddress);//销方地址
        order.setMachineCode(_machineCode);//机器编码
        order.setTerminalNumber(_terminalNumber);////终端号
        order.setExtensionNumber(_extensionNumber);//分机号（只能为空或者数字）
        order.setClerk(_clerk);
        order.setInvoiceCode(userInvoices.getTaxCode());
        order.setInvoiceNum(userInvoices.getTaxNo());
        List<InvoiceDetail> invoiceDetailList = new ArrayList<>();
        InvoiceDetail invoiceDetail = new InvoiceDetail();
        if(classConfig!=null) {
            invoiceDetail.setGoodsName("培训费一" + classConfig.getClassName());
        }else {
            invoiceDetail.setGoodsName("培训费");
        }
        invoiceDetail.setGoodsCode("3070201020000000000");
        invoiceDetail.setWithTaxFlag("1");
        invoiceDetail.setTaxRate("0.06");
        invoiceDetail.setPrice(userInvoices.getInvoicesPrice().toString());
        invoiceDetail.setNum("-1");
        invoiceDetailList.add(invoiceDetail);
        order.setInvoiceDetail(invoiceDetailList);//发票明细
        String jsonString = JSON.toJSONString(order);
        return "{\"order\":"+jsonString+"}";
    }

    //单独查询发票
    public String GetKPQueryJsonStr(UserInvoices userInvoices) {
        InvoiceQuery invoiceQuery = new InvoiceQuery();
        String [] orderNos = new String[]{userInvoices.getSyncOrderNo()};  // 初始化该数组
        invoiceQuery.setOrderNos(orderNos);
        String jsonString = JSON.toJSONString(invoiceQuery);
        return jsonString;
    }
}


//
//    异常编码	异常	描述
//        070304	Incorrect clientId[xxxx]	请求参数clientId不正确
//        070305	Incorrect clientSecret[xxxx]	请求参数clientSecret不正确
//        070306	The number of calls is limited	超过调用次数上限(30天内限制请求50次)
//        070307	Incorrect appType[xxxx]	应用类型错误，请走对应的授权流程
//        070315	Incorrect content-type	请设置正确的content-type，
//        如application/x-www-form-urlencoded;charset=UTF-8