package com.bcxin.web.controller;

import com.alibaba.fastjson.JSONObject;
import com.bcxin.config.WPSConfig;
import com.bcxin.service.FilePreviewFactory;
import com.bcxin.service.IFilePreview;
import com.bcxin.service.IWpsFilePreview;
import com.bcxin.service.impl.XfileService;
import com.bcxin.utils.BASE64Util;
import com.bcxin.utils.ConfigUtil;
import com.bcxin.utils.JwtUtil;
import com.bcxin.utils.constant.Const;
import com.bcxin.utils.constant.ResultEnum;
import com.bcxin.vo.wps.ResultVo;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.Claims;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

@Controller
public class OnlinePreviewController {

    @Resource
    private IWpsFilePreview iWpsFilePreview;

    @Resource
    private FilePreviewFactory previewFactory;

    @Resource
    private XfileService xfileService;

    @RequestMapping(value = "/preview", method = RequestMethod.GET)
    public ModelAndView preview(HttpServletRequest request,Model model){
        String token = request.getParameter("token");
        String forceWay = request.getParameter("forceWay");
        Claims claims;
        try {
            claims = JwtUtil.parseJWT(token, ConfigUtil.getValue("JWT_KEY"));
        } catch (Exception e) {
            return new ModelAndView("error");
        }
        String subject = claims.getSubject();
        String url = xfileService.preview(subject);

        /* 如果是内网环境，走openOffice预览*/
        String network = ConfigUtil.getValue("network");
        if ("intranet".equals(network)) {
            IFilePreview filePreview = previewFactory.get(url);
            url = url.replace("%2F","/");
            String view = filePreview.filePreviewHandle(url, model);
            return new ModelAndView(view);
        }
        if ("op".equals(forceWay)) {
            IFilePreview filePreview = previewFactory.get(url);
            url = url.replace("%2F","/");
            String view = filePreview.filePreviewHandle(url, model);
            return new ModelAndView(view);
        }
        // 除了wps能支持的，其他走openOffice预览
        String suffix = url.substring(url.lastIndexOf(".")+1).toLowerCase();
        if (!(WPSConfig.WPS_PREVIEW_TYPE_EXCEL + WPSConfig.WPS_PREVIEW_TYPE_PPT + WPSConfig.WPS_PREVIEW_TYPE_WORD).contains(suffix)) {
            IFilePreview filePreview = previewFactory.get(url);
            url = url.replace("%2F","/");
            String view = filePreview.filePreviewHandle(url, model);
            return new ModelAndView(view);
        } else {
            try {
                ResultVo resultVo = iWpsFilePreview.previewHandle(url,Const.Y,"");
                if (ResultEnum.FAIL.getCode().equals(resultVo.getCode())) {
                    return new ModelAndView("error");
                }
                model.addAttribute("previewUrl", resultVo.getData().toString());
                return new ModelAndView("redirect");
            } catch (Exception e) {
                e.printStackTrace();
            }
            return new ModelAndView("error");
        }
    }

    @RequestMapping(value = "/view", method = RequestMethod.GET)
    public ModelAndView view(HttpServletRequest request, Model model) throws Exception{
        request.setCharacterEncoding("UTF-8");
        String token = request.getParameter("token");
        String forceWay = request.getParameter("forceWay");
        String url = BASE64Util.decryptBASE64(token);
        /* 如果是内网环境，走openOffice预览*/
        String network = ConfigUtil.getValue("network");
        if ("intranet".equals(network)) {
            IFilePreview filePreview = previewFactory.get(url);
            url = url.replace("%2F","/");
            String view = filePreview.filePreviewHandle(url, model);
            return new ModelAndView(view);
        }
        if ("op".equals(forceWay)) {
            IFilePreview filePreview = previewFactory.get(url);
            url = url.replace("%2F","/");
            String view = filePreview.filePreviewHandle(url, model);
            return new ModelAndView(view);
        }
        // 除了wps能支持的，其他走openOffice预览
        String suffix = url.substring(url.lastIndexOf(".")+1);
        if (!(WPSConfig.WPS_PREVIEW_TYPE_EXCEL + WPSConfig.WPS_PREVIEW_TYPE_PPT + WPSConfig.WPS_PREVIEW_TYPE_WORD).contains(suffix)) {
            IFilePreview filePreview = previewFactory.get(url);
            url = url.replace("%2F","/");
            String view = filePreview.filePreviewHandle(url, model);
            return new ModelAndView(view);
        } else {
            try {
                ResultVo resultVo = iWpsFilePreview.previewHandle(url,Const.Y,"");
                if (ResultEnum.FAIL.getCode().equals(resultVo.getCode())) {
                    return new ModelAndView("error");
                }
                model.addAttribute("previewUrl", resultVo.getData().toString());
                return new ModelAndView("redirect");
            } catch (Exception e) {
                e.printStackTrace();
            }
            return new ModelAndView("error");
        }
    }


    @RequestMapping(value = "/convert", method = RequestMethod.GET)
    public @ResponseBody JSONObject convert(HttpServletRequest request){
        JSONObject json = new JSONObject();
        String token = request.getParameter("token");
        Claims claims;
        try {
            claims = JwtUtil.parseJWT(token, ConfigUtil.getValue("JWT_KEY"));
        } catch (Exception e) {
            return json;
        }
        String subject = claims.getSubject();
        String url = xfileService.convert(subject);
        json.put("status", Const.HTTP_STATUS_OK);
        json.put("newUrl",url);
        return json;
    }

    /**
     * @param url
     * @param model
     * @return
     */
    @RequestMapping(value = "onlinePreview", method = RequestMethod.GET)
    public String onlinePreview(String url, Model model, HttpServletRequest req) {
        req.setAttribute("fileKey", req.getParameter("fileKey"));
        IFilePreview IFilePreview = previewFactory.get(url);
        return IFilePreview.filePreviewHandle(url, model);
    }

    /**
     * 多图片切换预览
     *
     * @param model
     * @param req
     * @return
     * @throws UnsupportedEncodingException
     */
    @RequestMapping(value = "picturesPreview", method = RequestMethod.GET)
    public String picturesPreview(String urls, String currentUrl, Model model, HttpServletRequest req) throws UnsupportedEncodingException {
        // 路径转码
        String decodedUrl = URLDecoder.decode(urls, "utf-8");
        String decodedCurrentUrl = URLDecoder.decode(currentUrl, "utf-8");
        // 抽取文件并返回文件列表
        String[] imgs = decodedUrl.split("\\|");
        List imgurls = Arrays.asList(imgs);
        model.addAttribute("imgurls", imgurls);
        model.addAttribute("currentUrl",decodedCurrentUrl);
        return "picture";
    }

    @RequestMapping(value = "picturesPreview", method = RequestMethod.POST)
    public String picturesPreview(Model model, HttpServletRequest req) throws UnsupportedEncodingException {
        String urls = req.getParameter("urls");
        String currentUrl = req.getParameter("currentUrl");
        // 路径转码
        String decodedUrl = URLDecoder.decode(urls, "utf-8");
        String decodedCurrentUrl = URLDecoder.decode(currentUrl, "utf-8");
        // 抽取文件并返回文件列表
        String[] imgs = decodedUrl.split("\\|");
        List imgurls = Arrays.asList(imgs);
        model.addAttribute("imgurls", imgurls);
        model.addAttribute("currentUrl",decodedCurrentUrl);
        return "picture";
    }
    /**
     * 根据url获取文件内容
     * 当pdfjs读取存在跨域问题的文件时将通过此接口读取
     *
     * @param urlPath
     * @param resp
     */
    @RequestMapping(value = "/getCorsFile", method = RequestMethod.GET)
    public void getCorsFile(String urlPath, HttpServletResponse resp) {
        InputStream inputStream = null;
        try {
            String strUrl = urlPath.trim();
            URL url = new URL(strUrl);
            //打开请求连接
            URLConnection connection = url.openConnection();
            HttpURLConnection httpURLConnection = (HttpURLConnection) connection;
            httpURLConnection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            inputStream = httpURLConnection.getInputStream();
            byte[] bs = new byte[1024];
            int len;
            while (-1 != (len = inputStream.read(bs))) {
                resp.getOutputStream().write(bs, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                IOUtils.closeQuietly(inputStream);
            }
        }
    }




    /**
     * 重载/view方法，
     * @param request
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/editwps", method = RequestMethod.GET)
    public String viewwps(HttpServletRequest request,Model model) throws Exception {
        request.setCharacterEncoding("UTF-8");
        String token = request.getParameter("token");
        String decodeUrl = BASE64Util.decryptBASE64(token);
        String sysName = request.getParameter("sysName");
        String readonly = request.getParameter("readonly");
        String fileId = request.getParameter("fileId");
        // 除了wps能支持的，其他走openOffice预览
        String suffix = decodeUrl.substring(decodeUrl.lastIndexOf("."));
//        if ("zip".equalsIgnoreCase(suffix) || "jar".equalsIgnoreCase(suffix) || "gzip".equalsIgnoreCase(suffix)) {
        if (!(WPSConfig.WPS_PREVIEW_TYPE_EXCEL + WPSConfig.WPS_PREVIEW_TYPE_PPT + WPSConfig.WPS_PREVIEW_TYPE_WORD).contains(suffix)) {
                IFilePreview filePreview = previewFactory.get(decodeUrl);
            return filePreview.filePreviewHandle(decodeUrl, model);
        } else {
            try {
                ResultVo resultVo = iWpsFilePreview.previewHandle(decodeUrl, Const.N,"");
                HashMap map =  new ObjectMapper().readValue((String) resultVo.getData(), HashMap.class);
                return String.valueOf(map.get("redirect_url"));
            } catch (Exception e) {
                e.printStackTrace();
            }
            return "wps方法出错";
        }
    }


    public static void main(String[] args) throws Exception{
        String data6 = BASE64Util.encryptBASE64("http://bcxinsaasprod.baibaodun.cn/upload%2F2021-02-20%2F1613801223653264941.pdf");

        String byteArray6 = BASE64Util.decryptBASE64(data6);

        //System.out.println("解析钱："+data6);
        //System.out.println("解析后："+byteArray6);
        //
        //String jwttoken = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ7XCJmaWxlVXJsXCI6XCJodHRwOi8vYmN4aW5zYWFzcHJvZC5iYWliYW9kdW4uY24vdXBsb2FkJTJGMjAyMC0xMS0wNCUyRjE2MDQ0Njk3NjkwODAzNjEzNTUuZG9jeFwifSIsImV4cCI6MTYwNTY4MjgxM30.HdjF4Zqn5DQxiM-_UgH83fgdsbo3YHLEEeRUjClBTfw";
        //Claims claims = JwtUtil.parseJWT(jwttoken, "sdoDFyzfieqMrisd4H5o5t9weOl6GmSr");
        //String subject = claims.getSubject();
        //System.out.println("解析后1："+subject);

        System.out.println("----------------------我是分接线--------------------------");

        System.out.println("http://preview.abcxin.com/view?token="+data6);
        System.out.println("http://localhost:8012/view?token="+data6);
        System.out.println("http://localhost:8012/view?forceWay=op&token="+data6);
        //System.out.println("http://47.93.117.58:8012/view?token="+data7);
        //Console.log(token);
        //Console.log(DES3.decode(token));


        //Map<String,String> paramMap = Maps.newHashMap();
        //paramMap.put("province", "360000");
        //paramMap.put("city", "123");
        //paramMap.put("area", "1234");
        //String sql = "select * from sp_activity where province = {province} [and city = {city}] [and area = {area}] and active = 1";
        //Pattern PATTERN = Pattern.compile("\\[.*?]");
        //Matcher matcher = PATTERN.matcher(sql);
        //
        //while (matcher.find()) {
        //    for (String key : paramMap.keySet()) {
        //        if (StringUtil.isEmpty(paramMap.get(key)) && (matcher.group().contains("{" + key + "}"))) {
        //            sql = sql.replace(matcher.group(), "");
        //        }
        //    }
        //}
        //for (String key : paramMap.keySet()) {
        //    if (sql.contains("{" + key + "}")) {
        //        sql = sql.replace("{" + key + "}", paramMap.get(key));
        //    }
        //}
        //
        //sql = sql.replace("[","");
        //sql = sql.replace("]","");
        //System.out.println(sql);

        //String sql = "select * from sp_activity where province = 360000 [and city = {city}]  and active = 1";
        //Pattern PATTERN = Pattern.compile("\\[.*?]");
        //Matcher matcher = PATTERN.matcher(sql);
        //while (matcher.find()) {
        //    System.out.println(sql);
        //}

    }



}
