package com.zcloud.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zcloud.entity.Page;
import com.zcloud.entity.PageData;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.http.MediaType;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;


public class Warden {
    public static String get32UUID() {
        return UuidUtil.get32UUID();
    }

    public static List<PageData> getList(String raw) {
        return JSON.parseArray(raw, PageData.class);
    }

    public static List<PageData> getList(JSONArray raw) {
        return JSON.parseArray(raw.toJSONString(), PageData.class);
    }

    public static PageData getPageData(JSONObject raw) {
        return JSON.parseObject(raw.toJSONString(), PageData.class);
    }

    public static <T> List<T> getList(String raw, Class<T> clazz) {
        return JSON.parseArray(raw, clazz);
    }

    public static void initData(PageData entity) {
        entity.put("CREATE_TIME", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        entity.put("CRATED_DATE", new Date());
        entity.put("CREATOR_ID", Jurisdiction.getUSER_ID());
        entity.put("CREATOR_NAME", Jurisdiction.getName());
        entity.put("OPERATE_TIME", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        entity.put("OPERATE_DATE", new Date());
        entity.put("OPERATOR_ID", Jurisdiction.getUSER_ID());
        entity.put("OPERATOR_NAME", Jurisdiction.getName());
        entity.put("ISDELETE", "0");
    }

    public static void updateData(PageData entity) {
        entity.put("OPERATE_TIME", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        entity.put("OPERATE_DATE", new Date());
        entity.put("OPERATOR_ID", Jurisdiction.getUSER_ID());
        entity.put("OPERATOR_NAME", Jurisdiction.getName());
        entity.put("ISDELETE", "0");
    }

    public static Map<String, Object> getPage(Page page) {
        Map<String, Object> map = new HashMap<>();
        map.put("showCount", page.getShowCount());
        map.put("totalPage", page.getTotalPage());
        map.put("totalResult", page.getTotalResult());
        map.put("currentPage", page.getCurrentPage());
        map.put("currentResult", page.getCurrentResult());
        return map;
    }

    public static String getServiceCompanyStatusName(String status) {
        // 映射状态
        if ("0".equals(status)) {
            return "未服务";
        } else {
            return "服务中";
        }
    }

    public static void setCorp(PageData condition) {
        if (!"admin".equals(Jurisdiction.getUsername())) {
            condition.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());
        }
    }

    public static String doGet(String url, String param) {
        StringBuilder result = new StringBuilder();
        BufferedReader in = null;
        try {
            String urlNameString = url + "?" + param;
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("Accept", "application/json");
            connection.setRequestProperty("Content-type", "application/json; charset=utf-8");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常!" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result.toString();

    }

    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url   发送请求的 URL
     * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(String url, String param) {
        OutputStreamWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("Accept", "application/json");
            conn.setRequestProperty("Content-type", "application/json; charset=utf-8");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");

            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
//                out = new PrintWriter(conn.getOutputStream(),"utf-8");
            out = new OutputStreamWriter(conn.getOutputStream(), StandardCharsets.UTF_8);
            // 发送请求参数

            out.write(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常!" + e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url  发送请求的 URL
     * @param json 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String jsonPost(String url, JSONObject json) throws Exception{
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数

            out.print(json);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("请求异常:"+e.getMessage());
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }

    public static String doPostData(String url, String json) throws Exception {
        DefaultHttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(url);
        String result = "";
        HttpResponse res = null;
        BufferedReader in = null;
        try {
            StringEntity s = new StringEntity(json.toString(), "UTF-8");
            s.setContentType("application/json");
            post.setHeader("Accept", "application/json");
            post.setHeader("Content-type", "application/json; charset=utf-8");
            post.setEntity(s);
            res = client.execute(post);
            if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                result = EntityUtils.toString(res.getEntity());
                return HttpStatus.SC_OK + "";
            }

        } catch (Exception e) {
            if (res == null) {
                return "HttpResponse 为 null!";
            }
            throw new RuntimeException(e);
        }
        if (res == null || res.getStatusLine() == null) {
            return "无响应";
        }
        return result;
    }

    public static <T> T getRestInformation(HttpServletRequest request, Class<T> clazz) throws Exception {
        BufferedReader reader = null;
        try {
            StringBuilder data = new StringBuilder();
            String line = null;
            reader = request.getReader();
            while (null != (line = reader.readLine())) data.append(line);
            reader.close();
            return JSONObject.parseObject(data.toString(), clazz);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("解析请求报文出错");
        } finally {
            assert reader != null;
            reader.close();
        }
    }

    public static String saveFile(MultipartFile[] files, String number) throws Exception{
        if (files.length == 0) throw new RuntimeException("文件为空");
        MultipartFile file = files[0];
        String ffile = DateUtil.getDays();
        String fileName = get32UUID() + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        Smb.sshSftp(file, fileName, Const.FILEPATHFILE + number + "/" + ffile);
        return Const.FILEPATHFILE + number + "/" + ffile + "/" + fileName;
    }

    public static String saveFile(MultipartFile file, String CORPINFO_ID) throws Exception{
        MultipartFile[] files = new MultipartFile[1];
        files[0] = file;
        return saveFile(files, CORPINFO_ID);
    }

    /**
     * 压缩文件
     */
    public static MultipartFile createZip(MultipartFile[] chenNuoShu) throws Exception{
        return zipFiles(convertToFile(chenNuoShu));
    }

    public static List<File> convertToFile(MultipartFile[] files) throws Exception {
        List<File> lstFile = new ArrayList<>();
        if (files.length == 0) {
            throw new RuntimeException("文件为空");
        }
        for (MultipartFile file : files) {
            if (file.equals("") || file.getSize() <= 0) {
                continue;
            } else {
                InputStream ins;
                ins = file.getInputStream();
                File toFile = new File(file.getOriginalFilename());
                inputStreamToFile(ins, toFile);
                lstFile.add(toFile);
                ins.close();
            }
        }
        return lstFile;
    }

    /**
     * 获取流文件
     *
     * @param ins
     * @param file
     */
    public static void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = Files.newOutputStream(file.toPath());
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static MultipartFile zipFiles(List<File> srcFiles) throws IOException {
        Date date = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dxfFileName = formatter.format(date).replace(" ", "_").replace(":", "-");

        FileInputStream fileInputStream;
        ByteArrayOutputStream byteOutStream = new ByteArrayOutputStream();
        try (ZipOutputStream zipOut = new ZipOutputStream(byteOutStream)) {
            String fileNames = "";
            Random random = new Random();
            for (File file : srcFiles) {
                fileInputStream = new FileInputStream(file);
                String fileName = file.getName();
                if (fileNames.contains(fileName)){
                    fileName = (random.nextInt(90000) + 10000) + fileName;
                }
                ZipEntry zipEntry = new ZipEntry(fileName);
                zipOut.putNextEntry(zipEntry);
                int len;
                byte[] buffer = new byte[1024];
                while ((len = fileInputStream.read(buffer)) > 0) {
                    zipOut.write(buffer, 0, len);
                }
                fileInputStream.close();
                // 删除文件
                boolean isDelete = file.delete();
                if (isDelete){
                    System.out.println("删除文件成功");
                }
            }
            zipOut.flush();
            zipOut.closeEntry();
            zipOut.close();


            InputStream inputStream = new ByteArrayInputStream(byteOutStream.toByteArray());

            FileItemFactory factory = new DiskFileItemFactory(16, null);
            FileItem item = factory.createItem("file", MediaType.MULTIPART_FORM_DATA_VALUE, true, LocalDateTime.now() + ".zip");
            OutputStream os = item.getOutputStream();
            IOUtils.copy(inputStream, os);

            return new CommonsMultipartFile(item);
        } catch (IOException e) {
            e.printStackTrace();
        }
        throw new IOException("压缩文件失败");
    }
}