package com.gree.mall.miniapp.utils;


import cn.hutool.core.util.StrUtil;
import com.gree.mall.miniapp.constant.Constant;
import com.gree.mall.miniapp.exception.RemoteServiceException;
import org.apache.commons.lang3.StringUtils;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CommonUtils {


    public static String getAPPID(HttpServletRequest request){
        String header = request.getHeader(Constant.APPID);
        if(StringUtils.isBlank(header)){
            header = Constant.DEF_APPID;
        }
      //  header = Constant.DEF_APPID;
        return header;
    }

    public static List<String> initList(List<String> list,int size){
        int listSize = list.size();
        if(listSize < size){
            for(int i = listSize;i < size;i++){
                list.add("");
            }
        }
        return list;
    }

    public static String getStatusNameOfStudentExam(int status){
        if(status == 1){
            return "未完成";
        }else if(status == 2){
            return "已完成";
        }else if(status == 0){
            return "作废";
        }
        return "";
    }

    //(1.未考试 2.已及格,3.未及格)
    public static String getExamStatusNameOfStudentExam(int examStatus){
        if(examStatus == 1){
            return "未考试";
        }else if(examStatus == 2){
            return "已及格";
        }else{
            return "未及格";
        }
    }

    public static String getSourceName(int source){
        if(source == 1){
            return "后台新增";
        }else{
            return "线上报名";
        }
    }

    public static Boolean checkNotEmpty(Object... str){
        for(Object s : str){
            if(s instanceof String) {
                String value = (String)s;
                if (StringUtils.isBlank(value)) {
                    return false;
                }
            }else if(s == null) {
                return false;
            }
        }
        return true;
    }

    public static Boolean checkDate(String dateStr,String dateFormat){
        if(StringUtils.isBlank(dateStr)){
            return true;
        }
        SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
        try{
            sdf.parse(dateStr);
        }catch(Exception e){
            return false;
        }
        return true;
    }

    public static String getFormatUrl(String url) {
        if (url.startsWith("http:")) {
            url = StringUtils.replace(url, "http", "https");
        }

        return url;
    }

    /**
     * 从token获取userId
     */
    public static String getUserId(HttpServletRequest request){
        try {
            String token = getToken(request);
            if (StringUtils.isBlank(token)) {
                token = request.getParameter("token");
            }
            if (StringUtils.isBlank(token)) {
                token = request.getParameter("x-token");
            }
            if(StringUtils.isBlank(token)){
                return null;
            }
            return JwtUtils.validateJWT(token).getClaims().getId();
        }catch(Exception e){
            return "";
        }
    }

    public static String getNickName(){
        HttpServletRequest request = RequestContextHolder.getRequestAttributes() != null ? ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest() : null;
        return getNickName(request);
    }

    public static String getNickName(HttpServletRequest request){
        try{
            String token = getToken(request);
            if(StringUtils.isBlank(token))
                return null;
            return JwtUtils.validateJWT(token).getClaims().getSubject();
        }catch(Exception e){
            return "";
        }
    }

    /**
     * 获取token
     */
    public static String getToken(HttpServletRequest request){
        String token = request.getHeader("x-token");
        return token;
    }


    /**
     * 获取来源
     */
    public static String getSource(HttpServletRequest request){
        String token = request.getHeader("source");
        return token;
    }

    /**
     * 获取性别code
     * @param gender
     * @return
     */
    public static String getGenderCode(String gender){
        if(org.apache.commons.lang3.StringUtils.equals(gender,"男")){
            return "1";
        }else if(org.apache.commons.lang3.StringUtils.equals(gender,"女")){
            return "2";
        }
        //未知
        return "0";
    }

    public static void downloadFile(String fileName, HttpServletResponse response) throws IOException {
        InputStream inputStream  = CommonUtils.class.getResourceAsStream("/mapper/" + fileName);
        response.setContentType("content-type:octet-stream");
        response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
        OutputStream outputStream = response.getOutputStream();
        byte[] buffer = new byte[1024];
        int len;
        while ((len = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, len);
        }
        inputStream.close();
        outputStream.close();
    }


    /**
     * 检查下标对应的值不能为空
     * @param row
     * @param index
     * @return
     */
    public static Integer checkRowEmpty(List<String> row, int[] index){
        for(int i : index){
            if(StringUtils.isBlank(row.get(i))){
                return i;
            }
        }
        return null;
    }


    //xml解析
    public static Map doXMLParse(String strxml) throws JDOMException, IOException {
        strxml = strxml.replaceFirst("encoding=\".*\"", "encoding=\"UTF-8\"");
        if (null == strxml || "".equals(strxml)) {
            return null;
        }

        Map m = new HashMap();
        InputStream in = new ByteArrayInputStream(strxml.getBytes("UTF-8"));
        SAXBuilder builder = new SAXBuilder();
        Document doc = builder.build(in);
        Element root = doc.getRootElement();
        List list = root.getChildren();
        for (Object aList : list) {
            Element e = (Element) aList;
            String k = e.getName();
            String v = "";
            List children = e.getChildren();
            if (children.isEmpty()) {
                v = e.getTextNormalize();
            } else {
                v = getChildrenText(children);
            }
            m.put(k, v);
        }
        //关闭流
        in.close();
        return m;
    }

    private static String getChildrenText(List children) {
        StringBuilder sb = new StringBuilder();
        if (!children.isEmpty()) {
            for (Object aChildren : children) {
                Element e = (Element) aChildren;
                String name = e.getName();
                String value = e.getTextNormalize();
                List list = e.getChildren();
                sb.append("<").append(name).append(">");
                if (!list.isEmpty()) {
                    sb.append(getChildrenText(list));
                }
                sb.append(value);
                sb.append("</").append(name).append(">");
            }
        }

        return sb.toString();
    }

    /**
     * 根据URL地址获取文件
     * @param path URL网络地址
     * @param checkStr
     * @param replacePrefix
     * @return File
     */
    public static File getFileByHttpURL(String path, String address, String checkStr, String replacePrefix){
        String newUrl = path.split("[?]")[0];
        String[] suffix = newUrl.split("/");
        //得到最后一个分隔符后的名字
        String fileName = suffix[suffix.length - 1];
        String reqUrl = path;
        if (path.contains(checkStr)) {
            int endIndex = path.indexOf(checkStr) + checkStr.length();
            reqUrl = StrUtil.replace(reqUrl, 0, endIndex, replacePrefix + "/img/get?key=");
        }
        File file = null;
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try{
            file = new File(address+"/"+fileName);//创建临时文件
            URL urlFile = new URL(reqUrl);
            inputStream = urlFile.openStream();
            outputStream = new FileOutputStream(file);

            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead=inputStream.read(buffer,0,8192))!=-1) {
                outputStream.write(buffer, 0, bytesRead);
            }
        }catch (Exception e) {
            throw new RemoteServiceException(e.getMessage());
        }finally {
            try {
                if (null != outputStream) {
                    outputStream.close();
                }
                if (null != inputStream) {
                    inputStream.close();
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return file;
    }


    /**
     * 根据URL地址获取文件
     * @param path URL网络地址
     * @return File
     */
    public static File getFileByHttpURL(String path, String address, String fileName){
        String newUrl = path.split("[?]")[0];
        String[] suffix = newUrl.split("/");
        //得到最后一个分隔符后的名字
        File file = null;
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try{
            file = new File(address+"/"+fileName);//创建临时文件
            URL urlFile = new URL(path);
            inputStream = urlFile.openStream();
            outputStream = new FileOutputStream(file);

            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead=inputStream.read(buffer,0,8192))!=-1) {
                outputStream.write(buffer, 0, bytesRead);
            }
        }catch (Exception e) {
            throw new RemoteServiceException(e.getMessage());
        }finally {
            try {
                if (null != outputStream) {
                    outputStream.close();
                }
                if (null != inputStream) {
                    inputStream.close();
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return file;
    }



}
