package com.reptileclient.jlifeapp.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.reptileclient.jlifeapp.result.CheckTokenException;
import com.reptileclient.jlifeapp.result.ResponseInfoEnum;
import com.reptileclient.jlifeapp.service.impl.HmBookTradeOrderServiceImpl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.*;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 请求盒马下载 3步骤
 *
 * @author lu
 */
public class HttpUtil {
	 private static final Logger logger = LoggerFactory.getLogger(HttpUtil.class);

    public static Gson gson = new Gson();
    public static RestTemplate restTemplate = new RestTemplate();
    public static SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
    // 1 请求下载数据
//	public static final String exportBookOrderList_URL = "https://hmall.hemaos.com/bookOrderNew/exportBookOrderList";

    // 2 下载中心 获取down列表 get请求 这个是下载中心的 服务单，技师作业单，服务付款单
//	public static final String down_list_xzzx = "https://contract.hemaos.com/getContractDownList?_input_charset=utf-8&currentPage=1&pageSize=50";
    public static final String down_list_xzzx = "https://frontend.hemaos.com/oss/queryTask";


    // 2.1下载列表 联营商交易及销售
    public static final String down_list_xzlb = "https://frontend.hemaos.com/adventurer/record?pageSize=50&isImport=false&currentPage=1";

    // 3.拿到盒马excel下载地址下载

    public static HttpHeaders setHeader(String token) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        headers.add("referer", "https://shuhe.hemaos.com/console/workspace/539/preview");
        List<String> cookies = new ArrayList<>();
        cookies.add("WDKSESSID=" + token);
        headers.put(HttpHeaders.COOKIE, cookies);
        return headers;
    }

    /**
     * 1请求下载数据
     *
     * @param token
     * @param parmJson
     * @return
     */
    public synchronized static Map<String, Object> request(String token, String parmJson, String url) {
//		parmJson = "{\"bookOrderNo\":null,"
//				+ "\"beginTime\":\"2020-11-24 00:00:00\",\"endTime\":\"2020-11-25 23:59:59\","
//				+ "\"pageIndex\":1,\"pageSize\":30000}";

        HttpHeaders headers = setHeader(token);
        restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
//		HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity(parmJson, headers);
        HttpEntity<String> request = new HttpEntity<>(parmJson, headers);
        
        String result = restTemplate.postForObject(url, request, String.class);
        //System.out.println("请求完了::" + result);

        Map<String, Object> body = gson.fromJson(result, Map.class);
        
        if ("true".equals(body.get("success").toString())) {
        	 JSONObject data = (JSONObject) JSON.toJSON(body.get("data"));
        	 JSONArray items = data.getJSONArray("list");
             if (CollectionUtils.isEmpty(items)) {
            	 logger.info("等待10s重新发起请求");
             	try {
         			new Thread().sleep(10000);
         		} catch (InterruptedException e) {
         			// TODO Auto-generated catch block
         			e.printStackTrace();
         		}
            	 result = restTemplate.postForObject(url, request, String.class);
            	 body = gson.fromJson(result, Map.class);
             }
        }
        
        return body;
    }
    
    @SuppressWarnings("unchecked")
	public static String requestGet(String token, String parm, String url) {
		HttpHeaders headers = HttpUtil.setHeader(token);
		headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
		headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
		restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
		
		HttpEntity<String> entity = new HttpEntity<String>(parm, headers);

		ResponseEntity<String> result = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
//		Map<String, Object> body = JsonUtil.getEntity(result.getBody(), Map.class);
		return result.getBody();
	}


    /**
     * post请求
     *
     * @param token
     * @param paramJson
     * @param url
     * @return
     */
    public static JSONObject requestPost(String token, String paramJson, String url) {

        HttpHeaders headers = setHeader(token);
        restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
//		HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity(parmJson, headers);
        HttpEntity<String> request = new HttpEntity<>(paramJson, headers);

        String result = restTemplate.postForObject(url, request, String.class);

        if (null == result) {

            throw new CheckTokenException(ResponseInfoEnum.TOKEN_INCORRECT_OR_HAS_EXPIRED);
        }
        JSONObject jsonObject = JSONObject.parseObject(result);

        return jsonObject.getJSONObject("data");
    }

    /**
     * 下载中心的 2 获取down列表 get请求 ，url参数固定的
     *
     * @param token
     * @return
     */
    public static String requestDownCenter(String token) {

        HttpHeaders headers = setHeader(token);
        headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        HttpEntity<String> entity = new HttpEntity<String>(null, headers);

        ResponseEntity<String> result = restTemplate.exchange(down_list_xzzx, HttpMethod.GET, entity, String.class);
        Map<String, Object> body = gson.fromJson(result.getBody(), Map.class);

        System.out.println(result.getBody());
        System.out.println(body.get("data"));
        List<Map<String, Object>> listData = (List<Map<String, Object>>) body.get("data");

        Map<String, String> bizParams = (Map<String, String>) listData.get(0).get("bizParams");

        String durl = "https:" + bizParams.get("ossUrl");

        System.out.println("下载地址：" + durl);

        return durl;
    }

    /**
     * 下载列表的 2.1 获取down列表 get请求 ，url参数固定的
     *
     * @param token
     * @return
     */
    public static String requestDownList(String token) {

        HttpHeaders headers = setHeader(token);
        headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        HttpEntity<String> entity = new HttpEntity<String>(null, headers);

        ResponseEntity<String> result = restTemplate.exchange(down_list_xzlb, HttpMethod.GET, entity, String.class);
        Map<String, Object> body = gson.fromJson(result.getBody(), Map.class);
        Map<String, Object> dt = (Map<String, Object>) body.get("data");

        System.out.println(result.getBody());
        System.out.println(body.get("data"));
        List<Map<String, Object>> listData = (List<Map<String, Object>>) dt.get("list");

        Map<String, Object> taskResult = (Map<String, Object>) listData.get(0).get("taskResult");

        // taskResult
        String durl = "https:" + taskResult.get("ossUrl");

        System.out.println("下载地址：" + durl);

        return durl;
    }

    /**
     * 3，下载文件
     * 返回本地路径
     *
     * @param url      网络地址
     * @param savaPath 保持的路径
     * @throws IOException
     */
    public static String downUrl(String url) throws IOException {
        String savaPath = "";
        String ymd = sdf.format(new Date());
        String fileName = url.substring(url.lastIndexOf("/") + 1, url.length());

        if (isWindows()) {
            // 是windows
            savaPath = "D://filestorage/export_file/" + ymd + "/";
        } else {
            // linux
            savaPath = "/ftpsrv/export_file/export_file/" + ymd + "/";
        }
        Path rootLocation = Paths.get(savaPath);
        Files.createDirectories(rootLocation);

        savaPath = savaPath + System.currentTimeMillis() + "_" + fileName;
        FileOutputStream outputStream = null;
        try {
            URL ur = new URL(url);
            // 链接url
            URLConnection uc = ur.openConnection();
            // 获取输入流
            InputStream in = uc.getInputStream();
            byte[] data = readInputStream(in);
            File file = new File(savaPath);

            outputStream = new FileOutputStream(file);
            outputStream.write(data);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            outputStream.close();
        }
        return savaPath;
    }

    public static byte[] readInputStream(InputStream inStream) throws Exception {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        // 创建一个Buffer字符串
        byte[] buffer = new byte[1024];
        // 每次读取的字符串长度，如果为-1，代表全部读取完毕
        int len = 0;
        // 使用一个输入流从buffer里把数据读取出来
        while ((len = inStream.read(buffer)) != -1) {
            // 用输出流往buffer里写入数据，中间参数代表从哪个位置开始读，len代表读取的长度
            outStream.write(buffer, 0, len);
        }
        // 关闭输入流
        inStream.close();
        // 把outStream里的数据写入内存
        return outStream.toByteArray();
    }

    public static boolean isWindows() {
        return System.getProperties().getProperty("os.name").toUpperCase().indexOf("WINDOWS") != -1;
    }

    public static void main(String[] args) throws IOException {
//		String ss="https://wdk-file.oss-cn-hangzhou.aliyuncs.com/wdk-mall/excel/1606460780836_服务订单-20201127150620.xlsx";
//		System.out.println(ss.substring(ss.lastIndexOf("/")+1,ss.length()));

//		String durl = requestDownCenter("apxi-F6AG1rIJ0QaKWDaRGWcwNY");
//		String savePath="D://"+durl.substring(durl.lastIndexOf("/")+1,durl.length());
//		downUrl(durl);

        System.out.println(requestDownCenter("q3ak5r6KFozdm1l4lEVEWI9BIZw"));

    }

}
