package com.yh.saas.platform.controller;

import ch.qos.logback.classic.Logger;
import com.alipay.sofa.runtime.api.annotation.SofaReference;
import com.winsea.svc.base.base.entity.CommonAppendix;
import com.winsea.svc.base.base.exception.FileErrorCodeEnums;
import com.winsea.svc.base.base.exception.FileException;
import com.winsea.svc.base.base.exception.OfficeException;
import com.winsea.svc.base.base.service.IAppendixService;
import com.yh.saas.common.support.util.IdGenerator;
import com.yh.saas.common.support.util.StringUtils;
import com.yh.saas.common.support.util.po.POHelper;
//import com.zhuozhengsoft.pageoffice.OpenModeType;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.*;

@RestController
@RequestMapping("/office")
public class OfficeController {

    @Value("${file-root-path}")
    private String fileRootPath;

    private Logger log = (Logger) LoggerFactory.getLogger(this.getClass());

    @Autowired
    private POHelper pOHelper;

    @SofaReference
    private IAppendixService appendixService;

    /**
     * 测试用请求
     *
     * @return
     */
    @GetMapping("/file")
    public ModelAndView showIndex(HttpServletRequest request) {
        ModelAndView mv = new ModelAndView("office/office");
        // 页面点击连接拼接的文件ID
        String fileId = request.getParameter("fileId");
        // 标识：是否另存  0 保存源文件   1 另存新文件     如果打开的是模板 保存的时候即为另存  1
        // 保存关闭按按钮 showSave 1：显示 0 不显示
        String sameFlag = StringUtils.isEmpty(request.getParameter("sameFlag")) ? "0" : request.getParameter("sameFlag");
        String newFilePath = StringUtils.isEmpty(request.getParameter("newFilePath")) ? "" : request.getParameter("newFilePath");
        String showSaveFlag = StringUtils.isEmpty(request.getParameter("showSaveFlag")) ? "0" : request.getParameter("showSaveFlag");

        // 将打开的文件ID保存到session中  之后在打开该文件的方法中需要
        request.getSession().setAttribute("fileId", fileId);
        request.getSession().setAttribute("sameFlag", sameFlag);
        request.getSession().setAttribute("newFilePath", newFilePath);
        request.getSession().setAttribute("showSaveFlag", showSaveFlag);
        return mv;
    }

    /**
     * 获取打开文件的URL连接
     *
     * @param request
     * @param response
     * @param map
     */
    @GetMapping("/getUrl")
    public String getUrl(HttpServletRequest request, HttpServletResponse response, Map<String, Object> map) {
        String fileId = (String) request.getSession().getAttribute("fileId");
        String sameFlag = (String) request.getSession().getAttribute("sameFlag");
        String newFilePath = (String) request.getSession().getAttribute("newFilePath");
        String showSaveFlag = (String) request.getSession().getAttribute("showSaveFlag");
        String urlSTR = request.getParameter("urlSTR");
        return "javascript:POBrowser.openWindowModeless('" + urlSTR + "/office/open?fileId=" + fileId + "&userName=abc&sameFlag=" + sameFlag + "&newFilePath=" + newFilePath + "&showSaveFlag=" + showSaveFlag + "&urlSTR=" + urlSTR + "','fullscreen=yes;');";
    }

    /**
     * 删除无效文件
     *
     * @param fileId
     */
    @GetMapping("/delTemp")
    public void delTempNewFile(HttpServletRequest request, @RequestParam String fileId) {
        // 编辑文件后不进行保存操作 删除临时保存的附件信息
        CommonAppendix file = appendixService.getAppendixById(fileId);
        if (file != null) {
            try {
                File tempFile = new File(fileRootPath + File.separator
                        + URLDecoder.decode(file.getAppendixPath(), String.valueOf(StandardCharsets.UTF_8)));
                if (tempFile.exists() && tempFile.delete()) {
                    log.info(tempFile.getAbsolutePath() + "刪除成功！");
                }
            } catch (UnsupportedEncodingException e) {
                throw new FileException(FileErrorCodeEnums.READ_EXCEPTION);
            }
        }

        appendixService.deleteById(fileId);
        request.getSession().removeAttribute("TempFileId");
    }

    /**
     * 根据文件id取的文件路径，初始化并显示Office浏览器
     *
     * @param request
     * @param map
     * @param fileId   文件id
     * @param userName 文档编辑者名称
     * @return 返回到Office页面
     * @throws UnsupportedEncodingException
     */
    @GetMapping("/open")
    public ModelAndView open(HttpServletRequest request, Map<String, Object> map, @RequestParam String fileId, @RequestParam String userName, String sameFlag) throws UnsupportedEncodingException {
//        Map<String, Object> result = checkFileId(fileId);
        return null;
//        return show(request, map, (CommonAppendix) result.get("appendix"), userName, (OpenModeType) result.get("openModeType"));
    }

    /**
     * 初始化并显示Office浏览器
     *
     * @param request
     * @param map
     * @param userName 文档编辑者名称
     * @return 返回到Office页面
     * @throws UnsupportedEncodingException
     */
//    private ModelAndView show(HttpServletRequest request, Map<String, Object> map, @RequestParam CommonAppendix appendix, @RequestParam String userName, OpenModeType openModeType) throws UnsupportedEncodingException {
//        String htmlCode = "文件格式不支持";
//
//        if (userName == null || "".equals(userName.trim())) {
//            userName = "administrator";
//        }
//
//        if (openModeType != null) {
//            if ("1".equals(request.getParameter("sameFlag"))) {
//                // 以模板为准  另存新路径文件   需要插入条新common_appendix记录
//                String oldFilePath = appendix.getAppendixPath();
//                String newFilePath = request.getParameter("newFilePath");
//                String newFileId = IdGenerator.generateLongIncrId();
//                appendix.setAppendixId(newFileId);
//                String temp = appendix.getAppendixName();
//                String fileType = temp.substring(temp.lastIndexOf(".") + 1, temp.length());
//                // 创建时间戳文件名
//                temp = String.valueOf(new Date().getTime());
//                newFilePath = newFilePath + temp + "." + fileType;
//                appendix.setAppendixPath(newFilePath);
//
//                appendixService.insert(appendix);
//                //
//                if (oldFilePath.startsWith("/")) {
//                    oldFilePath = oldFilePath.substring(1);
//                }
//
//                //
//                if (newFilePath.startsWith("/")) {
//                    newFilePath = newFilePath.substring(1);
//                }
//
//                htmlCode = pOHelper.openOffice(request, newFileId, oldFilePath, newFilePath, openModeType, userName, "PageOfficeCtrl1");
//            } else {
//                String strApixString = appendix.getAppendixPath();
//                // 原路径保存文件
//                htmlCode = pOHelper.openOffice(request, strApixString, null, userName, "PageOfficeCtrl1");
//            }
//
//        }
//        /*
//         * else { // PDF格式 htmlCode =
//         * pOHelper.openPdf(request,appendix.getAppendixPath(), "PageOfficeCtrl1"); }
//         */
//
//        map.put("pageOffice", htmlCode);
//
//        ModelAndView mv = new ModelAndView("office/browser");
//        return mv;
//    }

    /**
     * 保存文档操作
     *
     * @param request
     * @param response
     * @param map
     * @throws UnsupportedEncodingException
     */
    @PostMapping("/save")
    public void save(HttpServletRequest request, HttpServletResponse response, Map<String, Object> map) throws IOException {
        pOHelper.saveOffice(request, response);
    }

    /**
     * 根据fileId 检查文件正确性
     *
     * @return
     */
//    private Map<String, Object> checkFileId(String fileId) {
//
//        Map<String, Object> result = new HashMap<>();
//        String fileType = "";
//        OpenModeType openModeType = null;
//
//        if (fileId == null || "".equals(fileId.trim())) {
//            //文件路径不能为空
//            throw new OfficeException(FileErrorCodeEnums.FILE_PATH_BLANK);
//        }
//
//        CommonAppendix appendix = appendixService.getAppendixById(fileId);
//        if (appendix == null || "".equals(appendix.getAppendixPath())) {
//            //文件路径不能为空
//            throw new OfficeException(FileErrorCodeEnums.FILE_PATH_BLANK);
//        }
//
//        String filePath = appendix.getAppendixPath();
//        if (filePath == null || "".equals(filePath.trim())) {
//            //文件路径不能为空
//            throw new OfficeException(FileErrorCodeEnums.FILE_PATH_BLANK);
//        }
//
//        filePath = filePath.replaceAll("%2E", ".");
//        if (filePath.contains(".")) {
//            fileType = filePath.substring(filePath.lastIndexOf("."), filePath.length());
//        } else {
//            //文件类型异常
//            throw new OfficeException(FileErrorCodeEnums.FILE_TYPE_EXCEPTION);
//        }
//
//        if (".doc#.docx#.wps".contains(fileType)) {
//            openModeType = OpenModeType.docNormalEdit;
//        } else if (".xls#.xlsx".contains(fileType)) {
//            openModeType = OpenModeType.xlsNormalEdit;
//        } else if (".ppt#.pptx".contains(fileType)) {
//            openModeType = OpenModeType.pptNormalEdit;
//        } else {
//            //Todo:pdf文件处理   现有pageoffice 标准版 不支持PDF功能
//            //文件类型异常
//            throw new OfficeException(FileErrorCodeEnums.FILE_TYPE_EXCEPTION);
//        }
//        result.put("openModeType", openModeType);
//        result.put("appendix", appendix);
//        return result;
//
//    }

    @GetMapping("/setTempFileId")
    public void setFileId(HttpServletRequest request) {
        // request.getSession().setAttribute("TempFileId",request.getParameter("FileId"));
    }

    @GetMapping("/getTempFileId")
    public List<String> getTempFileId(HttpServletRequest request) {
        List<String> list = new ArrayList<String>();
        String tempFileId = "";
        tempFileId = request.getSession().getAttribute("TempFileId") == null ? ""
                : (String) request.getSession().getAttribute("TempFileId");

        list.add(tempFileId);
        request.getSession().removeAttribute("TempFileId");
        return list;
    }

}
