package com.yeejoin.amos.fas.business.controller;

import com.alibaba.fastjson.JSONObject;
import com.yeejoin.amos.fas.business.service.intfc.IPlanVisual3dService;
import com.yeejoin.amos.fas.core.util.*;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
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.multipart.MultipartFile;
import org.typroject.tyboot.core.foundation.enumeration.UserType;
import org.typroject.tyboot.core.restful.doc.TycloudOperation;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 上传下载管理
 *
 * @author zcx
 */

@RestController
@RequestMapping(value = "/file")
public class FileController extends AbstractBaseController {

    private static final transient Logger log = LoggerFactory.getLogger(FileController.class);

    // 上传路径
    @Value("${file.uploadUrl}")
    private String fileUploadDir;

    // 文件读取参数
    @Value("${file.readUrl}")
    private String readUrl;

    @Autowired
    private IPlanVisual3dService iMaasVisualService;

    //文件上传
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/uploadfile", method = RequestMethod.POST)
    public CommonResponse uploadfile(@RequestPart("file") MultipartFile file) {
        String contentType = file.getContentType();   //图片文件类型
        String fileName = FileUtil.getFileName(file.getOriginalFilename());  //图片名字
        try {
            //调用文件处理类FileUtil，处理文件，将文件写入指定位置
            FileUtil.uploadFile(file.getBytes(), fileUploadDir, fileName);
            return new CommonResponse("SUCCESS", fileName);
        } catch (Exception e) {
            return new CommonResponse("FAILED", "上传失败");
        }

    }

    // 文件删除
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/deleteFile", method = RequestMethod.POST)
    public CommonResponse deleteFile(@RequestBody String path) {
        try {
            File file = new File(fileUploadDir + path);

            if (file.exists()) {

                if (file.delete()) {
                    return new CommonResponse("FAILED", "删除成功");
                } else {
                    return new CommonResponse("FAILED", "删除失败");
                }
            } else {
                return new CommonResponse("FAILED", "文件不存在");
            }

        } catch (Exception e) {
            return new CommonResponse("FAILED", "删除异常");
        }
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @PostMapping(value = "/plan/{appId}/texts")
    public CommonResponse uploadTextPlans(@PathVariable("appId") String appId, MultipartFile[] files) {
        CommonResponse response = FileUtil.uploadFiles(fileUploadDir, files);
        if (null != response && response.getResult().equals("SUCCESS")) {
            Map<String, String> pathNameMap = (Map<String, String>) response.getDataList();
            iMaasVisualService.uploadTextPlan(appId, pathNameMap);
            return CommonResponseUtil.success("上传成功");
        }
        return CommonResponseUtil.failure("上传失败");
    }

    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public CommonResponse upload(@RequestPart("file") MultipartFile file) {
        return FileUtil.uploadFile(fileUploadDir, file);
    }

    // 图片读取
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/getFile", method = RequestMethod.GET)
    @ResponseBody
    public void getFile(String in, @RequestParam(name = "open", required = false) String open,
                        HttpServletResponse response, HttpServletRequest request) throws Exception {
        if (StringUtil.isNotEmpty(in)) {
            in = in.replaceAll("\\.\\.", "");
        }
        String fileName = fileUploadDir + in;
        File file = new File(fileName);
        if (!file.exists()) {
            ResponseUtils.renderText(response, "File not exists!");
            return;
        }
        FileInputStream fis = new FileInputStream(file);
        ResponseUtils.downFileByInputStream(file.getName(), fis, response, open);
        IOUtils.closeQuietly(fis);
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/download/**", method = RequestMethod.GET)
    public void download(HttpServletResponse response, HttpServletRequest request) throws Exception {
        try (FileInputStream inputStream = new FileInputStream(fileUploadDir + request.getServletPath().substring(15));
             ServletOutputStream outputStream = response.getOutputStream();) {
            IOUtils.copy(inputStream, outputStream);
        } catch (Exception e) {
            e.printStackTrace();
            ResponseUtils.renderText(response, "File not exists!");
        }
    }
    
    /**
     * 删除文件
     *
     * @param files 文件名称集合
     * @return
     * @author nihuanshan
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "DELETE", value = "删除文件", notes = "删除文件")
    @RequestMapping(value = "/delFiles", method = RequestMethod.DELETE, produces = "application/json;charset=UTF-8")
    public CommonResponse delFiles(@ApiParam(value = "删除文件", required = true) @RequestParam List<String> files) {
        if (CollectionUtils.isNotEmpty(files)) {
            for (String name : files) {
                System.out.println("file is:" + name);
                String fileName = fileUploadDir + name;
                File file = new File(fileName);
                if (file.exists()) {
                    file.delete();
                }
            }
        }
        return new CommonResponse("SUCCESS", "删除文件成功");
    }

    /**
     * @return
     * @author: nihuanshan
     * @date: 2018年11月30日 下午3:15:38
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @PostMapping(value = "/lookHtmlText", produces = "application/json;charset=UTF-8")
    @ApiOperation(value = "查看文件内容", notes = "查看文件内容")
    public CommonResponse lookHtmlText(@ApiParam(value = "查看文件内容", required = true) @RequestBody String file)
            throws Exception {
        JSONObject obj = JSONObject.parseObject(file);
        String fileName = fileUploadDir;
        if (obj.containsKey("file")) {
            fileName += obj.getString("file");
        }
        File fi = new File(fileName);
        if (!fi.exists()) {
            return new CommonResponse("SUCCESS", "访问的文件不存在!", "查询成功");
        }
        if (fileName.endsWith(".pdf")) {
            String data = obj.getString("file");
            return new CommonResponse("SUCCESS", data, "查询成功");
        } else if (fileName.endsWith(".doc") || fileName.endsWith(".docx")) {
            String htmlFileName = fileName.substring(0, fileName.indexOf(".")) + ".html";
            File htmlFile = new File(htmlFileName);
            WordConverterUtils.wordToHtml(fileName, htmlFileName, readUrl);
            FileInputStream fis = new FileInputStream(htmlFile);
            String data = IOUtils.toString(fis, "utf-8"); // "gb2312"
            fis.close();
            return new CommonResponse("SUCCESS", data, "查询成功");
        } else {
            return new CommonResponse("SUCCESS", "访问的文件不存在!", "查询成功");
        }

    }


    /**
     * 查看文档（加导航栏）
     *
     * @param file
     * @return
     * @throws Exception
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @PostMapping(value = "/lookHtmlTextNav", produces = "application/json;charset=UTF-8")
    @ApiOperation(value = "查看文件内容（加导航栏）", notes = "查看文件内容（加导航栏）")
    public CommonResponse lookHtmlTextNav(@ApiParam(value = "查看文件内容（加导航栏）", required = true) @RequestBody String file)
            throws Exception {
        JSONObject obj = JSONObject.parseObject(file);
        String fileName = fileUploadDir;
        if (obj.containsKey("file")) {
            fileName += obj.getString("file");
        }
        File fi = new File(fileName);
        if (!fi.exists()) {
            return new CommonResponse("SUCCESS", "访问的文件不存在!", "查询成功");
        }
        if (fileName.endsWith(".doc") || fileName.endsWith(".docx")) {
            String htmlFileName = fileName.substring(0, fileName.lastIndexOf(".")) + ".html";
            File htmlFile = new File(htmlFileName);
            String data = WordConverterUtils.wordToHtmlString(fileName, readUrl);
            Map<String, Object> processData = null;
            if (fileName.endsWith(".doc")) {
                processData = DocUtil.processDoc(data);
            } else {
                processData = DocUtil.processDocx(data);
            }

            String htmlContent = (String) processData.get("html");
            try (Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(htmlFileName), StandardCharsets.UTF_8));) {
                writer.write(htmlContent);
                writer.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
            String filePath = obj.getString("file");
            processData.put("html", "/" + filePath.substring(0, filePath.lastIndexOf(".")) + ".html");

            return new CommonResponse("SUCCESS", processData, "查询成功");
        }if(fileName.endsWith(".pdf")) {
        	Map<String, Object> processData = new HashMap<String, Object>();
        	MyNode node = PdfUtil.getPdfNavs(fileName);
        	processData.put("nodes", node.getChildren());
        	String filePath = obj.getString("file");
            processData.put("html", "/" + filePath.substring(0, filePath.lastIndexOf(".")) + ".pdf");
        	return new CommonResponse("SUCCESS", processData, "查询成功");
        }else {
            return new CommonResponse("SUCCESS", "文件类型不为doc/docx", "查询成功");
        }
    }
    
    
}
