package com.hzya.frame.sys.file.download.controller;

import com.github.pagehelper.PageInfo;
import com.hzya.frame.page.PageAttribute;
import com.hzya.frame.sys.file.download.entity.FileDownloadEntity;
import com.hzya.frame.sys.file.download.service.IFileDownloadService;
import com.hzya.frame.web.action.DefaultController;
import com.hzya.frame.web.entity.JsonResultEntity;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
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.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;

/**
 * @description: 系统文件下载  controller
 * @tableName: sys_file
 * @entityName: FileDownloadEntity
 * 包含：
 * 1、分页查询(queryPaged)
 * 2、index页面(goIndexPage)
 * 3、新增页面(goAddPage)
 * 4、新增信息保存(save)
 * 5、修改页面(goEditPage)
 * 6、修改信息保存(update)
 * 7、信息查看(goShowPage)
 * 8、删除信息(delete)
 * @author: gjh
 * @history: 1.0
 */

@Controller("sys_file_fileDownload")
@RequestMapping("/sys/file/FileDownloadController")
public class FileDownloadController extends DefaultController {
    @Autowired
    protected IFileDownloadService filedownloadService;

    /**
     * 系统文件下载分页信息
     **/
    @RequestMapping(value = "queryPaged")
    @ResponseBody
    public PageAttribute<FileDownloadEntity> queryPaged(FileDownloadEntity entity) throws Exception {
        PageAttribute<FileDownloadEntity> page = null;
        try {
            page = filedownloadService.queryPaged(entity);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return page;
    }

    /**
     * 跳转到系统文件下载的index页面
     **/
    @RequestMapping(value = "goIndexPage", method = RequestMethod.GET)
    public ModelAndView goIndexPage() {
        ModelAndView view = new ModelAndView();
        /**这里根据实际的需要填写需要传到前台的对象**/
        //view.addObject(attributeName, attributeValue);
        /**这里是返回对应的页面路径**/
        view.setViewName("/sys/file/download/download/list");
        return view;
    }

    /**
     * 跳转到系统文件下载信息新增页面
     **/
    @RequestMapping(value = "goAddPage")
    public ModelAndView goAddPage() {
        ModelAndView view = new ModelAndView();
        /**这里根据实际的需要填写需要传到前台的对象**/
        //view.addObject(attributeName, attributeValue);
        /**这里是返回对应的页面路径**/
        view.setViewName("/sys/file/download/download/add");
        return view;
    }

    /**
     * 系统文件下载新增信息保存
     **/
    @RequestMapping(value = "save", method = RequestMethod.POST)
    @ResponseBody
    public JsonResultEntity save(FileDownloadEntity entity) {
        try {
            filedownloadService.save(entity);
            return getSuccessMessageEntity("保存成功", "save");
        } catch (Exception e) {
            logger.error("save", e);
            e.printStackTrace();
            return getFailureMessageEntity("保存失败！" + e.getMessage(), "save");
        }
    }

    /**
     * 跳转到系统文件下载信息修改页面
     **/
    @RequestMapping(value = "edit/{id}")
    public ModelAndView goEditPage(@PathVariable("id") Long id) {
        ModelAndView view = new ModelAndView();
        /**这里根据实际的需要填写需要传到前台的对象**/
        FileDownloadEntity entity = filedownloadService.get(id);
        view.addObject("entity", entity);
        /**这里是返回对应的页面路径**/
        view.setViewName("/sys/file/download/download/edit");
        return view;
    }

    /**
     * 系统文件下载修改信息保存
     **/
    @RequestMapping(value = "update", method = RequestMethod.POST)
    @ResponseBody
    public JsonResultEntity update(FileDownloadEntity entity) {
        try {
            filedownloadService.update(entity);
            return getSuccessMessageEntity("更新成功！", "update");
        } catch (Exception e) {
            logger.error("update", e);
            e.printStackTrace();
            return getFailureMessageEntity("更新失败！" + e.getMessage(), "update");
        }
    }

    /**
     * 跳转到系统文件下载信息查看
     **/
    @RequestMapping(value = "show/{id}")
    public ModelAndView goShowPage(@PathVariable("id") Long id) {
        ModelAndView view = new ModelAndView();
        /**这里根据实际的需要填写需要传到前台的对象**/
        FileDownloadEntity entity = filedownloadService.get(id);
        view.addObject("entity", entity);
        /**这里是返回对应的页面路径**/
        view.setViewName("/sys/file/download/download/show");
        return view;
    }

    /**
     * 删除系统文件下载信息
     **/
    @RequestMapping(value = "delete", method = RequestMethod.POST)
    @ResponseBody
    public JsonResultEntity delete(Long id) {
        try {
            filedownloadService.removeById(id);
            return getSuccessMessageEntity("删除成功！", "delete");
        } catch (Exception e) {
            logger.error("delete", e);
            e.printStackTrace();
            return getFailureMessageEntity("删除失败！" + e.getMessage(), "delete");
        }
    }

    /**
     * 根据文件保存的新名称下载文件
     *
     * @param fileSaveName
     * @return
     */
    @RequestMapping(value = "fileDownload")
    public ResponseEntity<byte[]> fileDownload(String fileSaveName) {
        ResponseEntity<byte[]> responseEntity = null;
        try {
            HttpHeaders headers = new HttpHeaders();
            FileDownloadEntity fileDownloadEntity = filedownloadService.fileDownload(fileSaveName);
            String fileName = fileDownloadEntity.getFilename();

            fileName = new String(fileName.getBytes(StandardCharsets.UTF_8), "iso8859-1");

            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentDispositionFormData("attachment", fileName);

            responseEntity = new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(fileDownloadEntity.getFile()), headers, HttpStatus.CREATED);
        } catch (Exception e) {
            logger.error("download", e);
            e.printStackTrace();
        }
        return responseEntity;
    }


    @RequestMapping(value = "/seekExperts")
    @ResponseBody
    public void createFolw(HttpServletRequest request, HttpServletResponse response, String id) {
        //取路径
        FileInputStream fis = null;
        OutputStream os = null;
        try {
            FileDownloadEntity fileDownloadEntity = filedownloadService.fileDownload(id);
            fis = new FileInputStream(fileDownloadEntity.getFile());
            os = response.getOutputStream();
            int count = 0;
            byte[] buffer = new byte[1024 * 8];
            while ((count = fis.read(buffer)) != -1) {
                os.write(buffer, 0, count);
                os.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            fis.close();
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}

