package cn.estsh.i3plus.core.apiservice.controller.busi;

import cn.estsh.i3plus.core.api.iservice.busi.ISysDictionaryService;
import cn.estsh.i3plus.core.api.iservice.busi.ISysFileService;
import cn.estsh.i3plus.platform.common.tool.StringTool;
import cn.estsh.i3plus.platform.common.util.CommonConstWords;
import cn.estsh.i3plus.platform.common.util.PlatformConstWords;
import cn.estsh.i3plus.pojo.base.bean.BaseConstWords;
import cn.estsh.i3plus.pojo.base.bean.ListPager;
import cn.estsh.i3plus.pojo.base.common.Pager;
import cn.estsh.i3plus.pojo.base.enumutil.CommonEnumUtil;
import cn.estsh.i3plus.pojo.base.enumutil.ResourceEnumUtil;
import cn.estsh.i3plus.pojo.platform.bean.SysDictionary;
import cn.estsh.i3plus.pojo.platform.bean.SysFile;
import cn.estsh.impp.framework.base.controller.CoreBaseController;
import cn.estsh.impp.framework.boot.exception.ImppBusiException;
import cn.estsh.impp.framework.boot.exception.ImppExceptionBuilder;
import cn.estsh.impp.framework.boot.exception.ImppExceptionEnum;
import cn.estsh.impp.framework.boot.fastdfs.FastDFSClient;
import cn.estsh.impp.framework.boot.util.ResultBean;
import cn.estsh.impp.framework.boot.util.ValidatorBean;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

/**
 * @Description : 文件资源服务
 * @Reference :
 * @Author : yunhao
 * @Date : 2018-10-25 16:34
 * @Modify :
 **/
@RestController
@Api(description = "文件资源服务")
@RequestMapping(PlatformConstWords.BASE_URL +"/sys-file")
public class SysFileController extends CoreBaseController{
    public static final Logger LOGGER = LoggerFactory.getLogger(SysFileController.class);

    @Autowired
    private ISysFileService sysFileService;

    @Autowired
    private ISysDictionaryService dictionaryService;

    @Autowired
    private FastDFSClient dfsClient;

    @PutMapping(value = "/update")
    @ApiOperation(value = "修改文件资源",notes = "修改文件资源")
    public ResultBean updateSysFile(SysFile sysFile){
        try {
            // 条件验证
            ValidatorBean.beginValid(sysFile)
                    .notNull("id",sysFile.getId())
                    .notNull("name",sysFile.getName());

            sysFileService.updateSysFile(sysFile);
            return  ResultBean.success("操作成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        }catch(ImppBusiException busExcep){
            return ResultBean.fail(busExcep);
        }catch(Exception e){
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @DeleteMapping(value = "/delete/{id}")
    @ApiOperation(value = "根据id删除文件资源",notes = "根据id删除文件资源")
    public ResultBean deleteSysFileById(@PathVariable("id") String id){
        try {
            sysFileService.deleteSysFileById(Long.parseLong(id));
            return ResultBean.success("操作成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        }catch(ImppBusiException busExcep){
            return ResultBean.fail(busExcep);
        }catch(Exception e){
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @GetMapping(value = "/list")
    @ApiOperation(value = "查询全部文件资源",notes = "查询全部文件资源")
    public ResultBean findSysFileAll(SysFile sysFile){
        try {
            List<SysFile> sysFileList = sysFileService.listSysFile();
            return ResultBean.success("操作成功")
                    .setResultList(sysFileList)
                    .setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        }catch(ImppBusiException busExcep){
            return ResultBean.fail(busExcep);
        }catch(Exception e){
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @GetMapping(value = "/get/{id}")
    @ApiOperation(value = "根据id查询文件资源",notes = "根据id查询文件资源")
    public ResultBean getSysFileById(@PathVariable("id") String id){
        try {
            ValidatorBean.checkIsNumber(id,"id必须为数字");

            SysFile sysFile = sysFileService.getSysFileById(Long.parseLong(id));
            return ResultBean.success("操作成功")
                    .setResultObject(sysFile)
                    .setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        }catch(ImppBusiException busExcep){
            return ResultBean.fail(busExcep);
        }catch(Exception e){
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @GetMapping(value = "/query")
    @ApiOperation(value = "文件资源复杂查询，分页，排序",notes = "文件资源复杂查询，分页，排序")
    public ResultBean querySysFileByPager(SysFile sysFile, Pager pager){
        try {
            ListPager sysFileListPager = sysFileService.querySysFileByPager(sysFile,pager);
            return  ResultBean.success("操作成功").setListPager(sysFileListPager).setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        }catch(ImppBusiException busExcep){
            return ResultBean.fail(busExcep);
        }catch(Exception e){
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @DeleteMapping(value = "/batch-delete")
    @ApiOperation(value = "批量删除文件资源",notes = "批量删除文件资源")
    public ResultBean deleteSysFileByIds(String[] ids){
        try{
            if(ids.length == 0){
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.CORE.getCode())
                        .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                        .setErrorDetail("请选择需要删除的资源。")
                        .build();
            }

            sysFileService.deleteSysFileByIds(StringTool.getArrayLong(ids));
            return ResultBean.success("操作成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        }catch(ImppBusiException busExcep){
            return ResultBean.fail(busExcep);
        }catch(Exception e){
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @PostMapping("/upload")
    @ApiOperation(value = "文件上传",notes = "文件上传")
    public ResultBean singleFileUpload(@RequestParam("file") MultipartFile file) {
        try {
            if(file.isEmpty()){
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.CORE.getCode())
                        .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                        .setErrorDetail("请选择需要上传的文件。")
                        .build();
            }

            boolean checkFileN = dictionaryService.checkFileName(file.getOriginalFilename());
            if(!checkFileN){
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.CORE.getCode())
                        .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_FORMAT.getCode())
                        .setErrorDetail("文件格式不支持")
                        .setErrorSolution("请到字典管理中添加文件类型")
                        .build();
            }

            SysFile fileDb = sysFileService.uploadFile(file);

            return ResultBean.success("上传成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode()).setResultObject(fileDb);
        }catch(ImppBusiException busExcep){
            return ResultBean.fail(busExcep);
        }catch(Exception e){
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @GetMapping("/download/{id}")
    @ApiOperation(value = "文件下载",notes = "文件下载")
    public ResultBean singleDownload(@PathVariable("id")String id, HttpServletResponse response) {
        try {
            ValidatorBean.checkIsNumber(id,"文件ID不能为空");

            SysFile sysFile = sysFileService.getSysFileById(Long.parseLong(id));
            if(sysFile == null){
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.CORE.getCode())
                        .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_NOT_EXIT.getCode())
                        .setErrorDetail("文件不存在")
                        .build();
            }

            InputStream fis = dfsClient.downFile(sysFile.getDfsGroupName(), sysFile.getDfsFileName());

            if(fis == null){
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.CORE.getCode())
                        .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_NOT_EXIT.getCode())
                        .setErrorDetail("文件已过期")
                        .build();
            }

            response.setContentType("application/force-download");// 设置强制下载不打开
            response.addHeader("Content-Disposition", "attachment;fileName=" + sysFile.getFileOriginalName());// 设置文件名
            response.addHeader("Content-type", "application/octet-stream");// 设置文件名

            BufferedInputStream bis = null;
                try {
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    byte[] buffer = new byte[1024];
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            // 增加文件下载次数
            sysFile.setDownloadNum(sysFile.getDownloadNum() + 1);
            sysFileService.updateSysFile(sysFile);
            return ResultBean.success("下载").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        }catch(ImppBusiException busExcep){
            return ResultBean.fail(busExcep);
        }catch(Exception e){
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @PostMapping(value = "/insert")
    @ApiOperation(value = "新增文件资源",notes = "新增文件资源")
    public ResultBean insertSysFile(@RequestBody SysFile sysFile){
        try {
            // 条件验证
            ValidatorBean.beginValid(sysFile)
                    .notNull("dfsFileName",sysFile.getDfsFileName())
                    .notNull("dfsGroupName",sysFile.getDfsGroupName())
                    .notNull("fileOriginalName",sysFile.getFileOriginalName());

            // 文件类型验证
            SysDictionary dictionary = dictionaryService.getSysDictionaryByParentCodeAndCode(BaseConstWords.DICTIONARY_FILE_TYPE,
                    StringTool.getStringFileSuffix(sysFile.getFileOriginalName(),false));
            if(dictionary == null){
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.CORE.getCode())
                        .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_FORMAT.getCode())
                        .setErrorDetail("文件格式不支持")
                        .setErrorSolution("请到字典管理中添加文件类型")
                        .build();
            }

            // 初始化数据
            sysFile.setFileTypeId(dictionary.getId());
            sysFile.setFileTypeName(dictionary.getName());

            sysFile = sysFileService.insertSysFile(sysFile);
            return  ResultBean.success("操作成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode()).setResultObject(sysFile);
        }catch(ImppBusiException busExcep){
            return ResultBean.fail(busExcep);
        }catch(Exception e){
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

}