package com.steerinfo.ftp.uploadfile.controller;

import com.steerinfo.auth.utils.JwtUtil;
import com.steerinfo.framework.controller.BaseRESTfulController;
import com.steerinfo.framework.controller.RESTfulResult;
import com.steerinfo.framework.service.pagehelper.PageList;
import com.steerinfo.framework.utils.collection.ListUtils;
import com.steerinfo.ftp.securitytype.mapper.SecurityTypeMapper;
import com.steerinfo.ftp.securitytype.model.SecurityType;
import com.steerinfo.ftp.uploadfile.model.UploadFile;
import com.steerinfo.ftp.uploadfile.service.IUploadFileService;
import com.steerinfo.ftp.uploadfile.utils.FtpFileUtil;
import com.steerinfo.ftp.uploadfile.utils.IDutils;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
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.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * UploadFile RESTful接口：
 * @author generator
 * @version 1.0-SNAPSHORT 2021-07-24 04:06
 * 类描述
 * 修订历史：
 * 日期：2021-07-24
 * 作者：generator
 * 参考：
 * 描述：UploadFile RESTful接口
 * @see null
 * @Copyright 湖南视拓信息技术股份有限公司. All rights reserved.
 */
@RestController
@RequestMapping("/${api.version}/uploadfiles")
public class UploadFileController extends BaseRESTfulController {
    @Autowired
    IUploadFileService uploadFileService;
    @Autowired
    private FtpFileUtil ftpFileUtil;

    @Autowired
    private SecurityTypeMapper securityTypeMapper;
    @ApiOperation(value="获取列表", notes="分页查询")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "pageNum", value = "查询页数", required = false, dataType = "Integer"),
        @ApiImplicitParam(name = "pageSize", value = "每页记录数", required = false, dataType = "Integer")
    })
    @GetMapping(value = "/")
    public RESTfulResult list(@RequestParam HashMap parmas,Integer pageNum, Integer pageSize){
        PageList<UploadFile> list = uploadFileService.queryForPage(parmas, pageNum, pageSize);
        return success(list);
    }

    @ApiOperation(value="获取列表", notes="分页模糊查询")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "pageNum", value = "查询页数", required = false, dataType = "Integer"),
        @ApiImplicitParam(name = "pageSize", value = "每页记录数", required = false, dataType = "Integer")
    })
    //@RequiresPermissions("uploadfile:view")
    @GetMapping(value = "/like/")
    public RESTfulResult listLike(@RequestParam HashMap parmas,Integer pageNum, Integer pageSize){
        String fileType = parmas.get("fileType").toString().replace(",","|");
        parmas.put("fileType",fileType);
        PageList<UploadFile> list = uploadFileService.queryLikeForPage(parmas, pageNum, pageSize);
        return success(list);
    }
    
    @ApiOperation(value="创建", notes="根据UploadFile对象创建")
    @ApiImplicitParam(name = "uploadFile", value = "详细实体uploadFile", required = true, dataType = "UploadFile")
    //@RequiresPermissions("uploadfile:create")
    @PostMapping(value = "/")
    public RESTfulResult add(@ModelAttribute UploadFile model){
        UploadFile uploadFile = uploadFileService.add(model);
        return success(uploadFile);
    }

    @ApiOperation(value="获取详细信息", notes="根据url的id来获取详细信息")
    @ApiImplicitParam(paramType = "path", name = "id", value = "ID", required = true, dataType = "String")
    //@RequiresPermissions("uploadfile:view")
    @GetMapping(value = "/{id}")
    public RESTfulResult get(@PathVariable String id){
        UploadFile uploadFile = uploadFileService.getById(id);
        return success(uploadFile);
    }

    @ApiOperation(value="更新详细信息", notes="根据url的id来指定更新对象，并根据传过来的uploadFile信息来更新详细信息")
    @ApiImplicitParams({
        @ApiImplicitParam(paramType = "path", name = "id", value = "ID", required = true, dataType = "String"),
        @ApiImplicitParam(name = "uploadFile", value = "详细实体uploadFile", required = true, dataType = "UploadFile")
    })
    //@RequiresPermissions("uploadfile:update")
    @PutMapping(value = "/{id}", produces  = "application/json;charset=UTF-8")
    public RESTfulResult update(@PathVariable String id, @RequestBody UploadFile model){
        model.setId(id);
        UploadFile uploadFile = uploadFileService.modify(model);
        return success(uploadFile);
    }

    @ApiOperation(value="删除", notes="根据url的id来指定删除对象")
    @ApiImplicitParam(paramType = "path", name = "id", value = "ID", required = true, dataType = "String")
    @DeleteMapping(value = "/{id}")
    public RESTfulResult delete(@PathVariable String id) throws Exception {
    	List<String> list = Arrays.asList(id.split(","));
    	String path = null;
    	try {
    	if(ListUtils.isNotEmpty(list)) {
	    	List<String> ids = ListUtils.convertList(list);
	    	for (String item : ids) {
                UploadFile uploadFile = uploadFileService.getById(item);
                path = uploadFile.getFileUrl();
               if (ftpFileUtil.deleteFile(path)){
                   uploadFileService.delete(item);
               }else{
                   return failed(null,"部分文件删除失败");
               }
            }
            //uploadFileService.delete(ids);
    	}
        } catch (Exception e) {
    	    return failed(null,"删除失败");
        }
      return success();
    }

    @PutMapping(value = "/batchupdate", produces  = "application/json;charset=UTF-8")
    public RESTfulResult batchupdate(@RequestBody UploadFile[] models) {
        String userId = JwtUtil.getUseridByToken();
        for (int i = 0; i < models.length; i++) {
            UploadFile model = models[i];
            if (model.getId() == null || model.getId().equals("")) {
                return failed(null, "id为空");
            }
            model.setUpdateMan(userId);
            model.setUpdateTime(new Date());
            uploadFileService.modify(model);
        }
        return success();
    }

    @PostMapping("/file")
    public RESTfulResult fileUpload( @ModelAttribute MultipartFile file, String type){
        try {
            if(null == type || "".equals(type)){
                return failed(null,"请选择左边的文件目录");
            }
            SecurityType securityType = securityTypeMapper.selectByPrimaryKey(type);
            String userId = JwtUtil.getUseridByToken();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("/yyyy/MM/dd");
            String oldName = file.getOriginalFilename();
            String newName = IDutils.getImageName();
            newName = newName + oldName.substring(oldName.lastIndexOf("."));
            String filePath = simpleDateFormat.format(new Date());
            InputStream inputStream = file.getInputStream();
             boolean result = ftpFileUtil.uploadToFtp(inputStream,securityType.getSecurityUploadUrl()+filePath,newName,false);
            inputStream.close();
            if(result){
                UploadFile uploadFile = new UploadFile();
                uploadFile.setFileName(oldName);
                uploadFile.setFileUrl(securityType.getSecurityUploadUrl()+filePath+"/"+newName);
                uploadFile.setFileType(securityType.getSecurityType());
                uploadFile.setUploadTime(new Date());
                uploadFile.setCreateMan(userId);
                uploadFile.setType(securityType.getId());
                uploadFile.setCreateTime(new Date());
                uploadFileService.add(uploadFile);
                return success();
            }
        }catch (Exception e){
            e.getMessage();
        }
        return  failed(null,"上传文件失败");
    }

    /**
     * 预览文件
     * @param parmas
     * @return
     * @throws IOException
     */
    @GetMapping("/getfile")
    public RESTfulResult downloadFile (@RequestParam HashMap parmas)throws IOException {
        String fileName = parmas.get("fileName").toString();
        String fileUrl = parmas.get("fileUrl").toString();
        String str = fileName+"预览失败";
        try {
            str = ftpFileUtil.downloadFile(fileName,fileUrl);
        } catch (Exception e){
            e.printStackTrace();
            return failed(null, "预览失败");
        }
        return success(str);
    }

    /**
     * 下载文件
     * @param path
     * @param fileName
     * @param response
     */
    @RequestMapping(value = "/downloadFile")
    public void downloadFile(@RequestParam("fileUrl") String path, @RequestParam("fileName") String fileName, HttpServletResponse response) {
        try {
            boolean result = ftpFileUtil.download(response, fileName, path);
            if (!result) {
                //logger.error("下载文件<" + fileName + ">失败,文件不存在");
                response.sendError(HttpServletResponse.SC_NOT_FOUND, "下载文件失败，文件目录不存在或文件不存在。");
            }
        } catch (Exception e) {
            //logg.error("下载文件<" + fileName + ">失败", e);
        }
    }

    @GetMapping("/getIdAndName")
    public RESTfulResult getIdAndName(){
        Set<UploadFile> idAndName = uploadFileService.getIdAndName();
        return success(idAndName);
    }
}
