package com.jeequan.jeepay.thirdparty.device.printer.fePrinter;

import com.alibaba.fastjson.JSONObject;
import com.jeequan.jeepay.core.exception.BizException;
import com.jeequan.jeepay.core.model.device.FePrinterParams;
import com.jeequan.jeepay.core.utils.DateKit;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: ZhuXiao
 * @Description:
 * @Date: 18:20 2021/7/6
*/
@Slf4j
public class FeUtil {

    public static final String REQ_URL = "http://api.feieyun.cn/Api/Open/";

    /**
     * @Author: ZhuXiao
     * @Description: 添加打印机至飞鹅后台
     * @Date: 9:51 2021/7/7
    */
    public static String addPrinter(FePrinterParams fePrinterParams) throws Exception {

        List<NameValuePair> nvps = FeUtil.genIsvParams(fePrinterParams);
        String snStr = String.format("%s#%s#%s", fePrinterParams.getDeviceParams().getDeviceNo(), fePrinterParams.getDeviceParams().getDeviceKey(), fePrinterParams.getDeviceParams().getDeviceNo());
        nvps.add(new BasicNameValuePair("apiname", "Open_printerAddlist"));
        nvps.add(new BasicNameValuePair("printerContent", snStr));

        return FeUtil.post(FeUtil.REQ_URL, nvps);
    }

    /**
     * @Author: ZhuXiao
     * @Description: 修改飞鹅后台打印机信息
     * @Date: 10:51 2021/7/7
     */
    public static String editPrinter(FePrinterParams fePrinterParams) throws Exception {

        List<NameValuePair> nvps = FeUtil.genIsvParams(fePrinterParams);
        nvps.add(new BasicNameValuePair("apiname", "Open_printerEdit"));
        nvps.add(new BasicNameValuePair("sn", fePrinterParams.getDeviceParams().getDeviceNo()));
        nvps.add(new BasicNameValuePair("name", fePrinterParams.getDeviceParams().getDeviceNo()));

        return FeUtil.post(FeUtil.REQ_URL, nvps);
    }

    /**
     * @Author: ZhuXiao
     * @Description: 打印订单
     * @Date: 9:58 2021/7/7
     */
    public static String print(FePrinterParams fePrinterParams, String content) throws Exception {

        List<NameValuePair> nvps = FeUtil.genIsvParams(fePrinterParams);
        nvps.add(new BasicNameValuePair("apiname", "Open_printMsg"));
        nvps.add(new BasicNameValuePair("sn", fePrinterParams.getDeviceParams().getDeviceNo()));
        nvps.add(new BasicNameValuePair("content",content));
        nvps.add(new BasicNameValuePair("times", StringUtils.defaultString(String.valueOf(fePrinterParams.getBizConfigParams().getPrintNum()), "1")));//打印联数

        return FeUtil.post(FeUtil.REQ_URL, nvps);
    }

    /**
     * @Author: ZhuXiao
     * @Description: 清空待打印订单
     * @Date: 9:59 2021/7/7
     */
    public static String clear(FePrinterParams fePrinterParams) throws Exception {

        List<NameValuePair> nvps = FeUtil.genIsvParams(fePrinterParams);
        nvps.add(new BasicNameValuePair("apiname", "Open_delPrinterSqs"));
        nvps.add(new BasicNameValuePair("sn", fePrinterParams.getDeviceParams().getDeviceNo()));

        return FeUtil.post(FeUtil.REQ_URL, nvps);
    }


    private static List<NameValuePair> genIsvParams(FePrinterParams fePrinterParams) {
        List<NameValuePair> nvps = new ArrayList<>();
        nvps.add(new BasicNameValuePair("user", fePrinterParams.getProviderParams().getUser()));
        String sTime = String.valueOf(DateKit.currentTimeMillis()/1000);
        nvps.add(new BasicNameValuePair("stime", sTime));
        nvps.add(new BasicNameValuePair("sig", signature(fePrinterParams.getProviderParams().getUser(), fePrinterParams.getProviderParams().getUkey(), sTime)));
        return nvps;
    }

    private static String post(String url, List<NameValuePair> list) throws Exception {

        CloseableHttpClient httpClient = getHttpClient();

        HttpPost post = new HttpPost(url);

        CloseableHttpResponse response = null;
        JSONObject resJSON;

        post.setEntity(new UrlEncodedFormEntity(list, "utf-8"));
        log.info("\n【飞鹅云打印请求】：{}", list.toString());

        response = httpClient.execute(post);
        int statecode = response.getStatusLine().getStatusCode();
        if(statecode == 200){
            HttpEntity httpentity = response.getEntity();
            if (httpentity != null){
                String result = EntityUtils.toString(httpentity);
                log.info("\n【飞鹅云打印返回】：{}", result);

                if (StringUtils.isBlank(result)) {
                    return null;
                }

                resJSON = JSONObject.parseObject(result);
                if (resJSON.getIntValue("ret") != 0) {
                    throw new BizException(resJSON.getString("msg"));
                }

                if (StringUtils.isBlank(resJSON.getString("data"))) {
                    resJSON.put("data", "success");
                }
                return resJSON.getString("data");
            }
        }

        return null;

    }

    private static CloseableHttpClient getHttpClient() {

        //通过POST请求，发送打印信息到服务器
        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(30000)//读取超时
                .setConnectTimeout(30000)//连接超时
                .build();

        return HttpClients.custom()
                .setDefaultRequestConfig(requestConfig)
                .build();
    }

    //生成签名字符串
    private static String signature(String user, String uKey, String sTime){
        return DigestUtils.sha1Hex(user + uKey + sTime);
    }

}
