package com.cftech.waybill.utils;

import com.sf.util.Base64ImageTools;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 顺丰面单打印工具类
 * Created by 16444 on 2020/11/26.
 */
@Slf4j
public class BillPrinterUtils {

    private static boolean TOP_LOGO = true;

    /**
     * 打印方法
     * @return
     */
    public static boolean executePrinter(String printStr) {
        System.out.print(printStr);
        String link = FqConstants.TWO_UNITED_150;
        try {
            link = isPrinterLogo(link, true);

            URL url = new URL(link);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
            //connection.setRequestProperty("Content-Type", "text/plain;charset=utf-8");
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(3 * 5000);


            connection.getOutputStream().write(printStr.getBytes("utf-8"));
            connection.getOutputStream().flush();
            connection.getOutputStream().close();


            InputStream in = connection.getInputStream();
            BufferedReader inReader = new BufferedReader(new InputStreamReader(in, "utf-8"));
            String y = "";
            String strImg = "";
            while ((y=inReader.readLine()) != null) {
                strImg = y.substring(y.indexOf("[")+1, y.length()-"]".length()-1);

                if(strImg.startsWith("\"")){
                    strImg = strImg.substring(1, strImg.length());
                }
                if(strImg.endsWith("\"")){
                    strImg = strImg.substring(0, strImg.length()-1);
                }
            }

            //去掉换行符
            strImg = strImg.replace("\\n", "");

            SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd-HHmmss");
            String dateStr = format.format(new Date());

            List<String> files = new ArrayList<>();

            if(strImg.contains("\",\"")){
                //如子母单及签回单需要打印两份或者以上
                String[] arr = strImg.split("\",\"");
                /**输出图片到本地 支持.jpg、.png格式**/
                for(int i = 0; i < arr.length; i++) {
                    String fileName = "D:\\qiaoWay"+dateStr+"-"+i+".jpg";
                    Base64ImageTools.generateImage(arr[i].toString(), fileName);
                    files.add(fileName);
                }
            }else{
                String fileName = "D:\\qiaoWaybill"+dateStr+".jpg";
                Base64ImageTools.generateImage(strImg, fileName);
                files.add(fileName);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
            log.error("调用顺丰打印sdk服务失败 errorMsg = " + e.getMessage());
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            log.error("调用顺丰打印sdk服务失败 errorMsg = " + e.getMessage());
            return false;
        }
        return true;
    }

    /**
     * 是否打印logo
     * V2.0/V3.0模板顶部是带logo的  V2.1/V3.1顶部不带logo
     * @param url
     * @return
     */
    public static String isPrinterLogo(String url, boolean TOP_LOGO) {
        if (url.contains("V2.0") && TOP_LOGO) {
            url = url.replace("V2.0", "V2.1");
        }
        if (url.contains("V3.0") && TOP_LOGO){
            url = url.replace("V3.0", "V3.1");
        }
        if (url.contains("V2.8.0") && TOP_LOGO) {
            url = url.replace("V2.8.0", "V2.8.1");
        }
        System.out.println(url);
        return url;
    }
}
