package com.steerinfo.ems.tmaintenancefile.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.ems.tmaintenancefile.model.TMaintenanceFile;
import com.steerinfo.ems.tmaintenancefile.service.ITMaintenanceFileService;
import com.steerinfo.ftp.securitytype.model.SecurityType;
import com.steerinfo.ftp.uploadfile.model.UploadFile;
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.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
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.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;
import java.math.BigDecimal;

/**
 * TMaintenanceFile RESTful接口：
 * @author generator
 * @version 1.0-SNAPSHORT 2022-06-06 02:51
 * 类描述
 * 修订历史：
 * 日期：2022-06-06
 * 作者：generator
 * 参考：
 * 描述：TMaintenanceFile RESTful接口
 * @see null
 * @Copyright 湖南视拓信息技术股份有限公司. All rights reserved.
 */
@RestController
    @RequestMapping("/${api.version}/tmaintenancefiles")
public class TMaintenanceFileController extends BaseRESTfulController {
    @Autowired
    private FtpFileUtil ftpFileUtil;
    @Autowired
    ITMaintenanceFileService tMaintenanceFileService;

    @ApiOperation(value="获取列表", notes="分页查询")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "pageNum", value = "查询页数", required = false, dataType = "Integer"),
        @ApiImplicitParam(name = "pageSize", value = "每页记录数", required = false, dataType = "Integer")
    })
    //@RequiresPermissions("tmaintenancefile:view")
    @GetMapping(value = "/")
    public RESTfulResult list(@RequestParam HashMap parmas,Integer pageNum, Integer pageSize){
        PageList<TMaintenanceFile> list = tMaintenanceFileService.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("tmaintenancefile:view")
    @GetMapping(value = "/like/")
    public RESTfulResult listLike(@RequestParam HashMap parmas,Integer pageNum, Integer pageSize){
        PageList<TMaintenanceFile> list = tMaintenanceFileService.queryLikeForPage(parmas, pageNum, pageSize);
        return success(list);
    }
    
    @ApiOperation(value="创建", notes="根据TMaintenanceFile对象创建")
    @ApiImplicitParam(name = "tMaintenanceFile", value = "详细实体tMaintenanceFile", required = true, dataType = "TMaintenanceFile")
    //@RequiresPermissions("tmaintenancefile:create")
    @PostMapping(value = "/")
    public RESTfulResult add(@ModelAttribute TMaintenanceFile model){
        TMaintenanceFile tMaintenanceFile = tMaintenanceFileService.add(model);
        return success(tMaintenanceFile);
    }

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

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

    @ApiOperation(value="删除", notes="根据url的id来指定删除对象")
    @ApiImplicitParam(paramType = "path", name = "id", value = "ID", required = true, dataType = "String")
    //@RequiresPermissions("tmaintenancefile:delete")
    @DeleteMapping(value = "/{id}")//String
    public RESTfulResult delete(@PathVariable String id){
    	List<String> list = Arrays.asList(id.split(","));
    	if(ListUtils.isNotEmpty(list)) {
	    	List<String> ids = ListUtils.convertList(list);
			  tMaintenanceFileService.delete(ids);
    	}
      return success();
    }

    @PostMapping("/file")
    public RESTfulResult fileUpload(@ModelAttribute MultipartFile files,String id){
        String filesid = "";
        if (files!=null){
                try {
                    String userId = JwtUtil.getUseridByToken();
                    //获取系统时间
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("/yyyy/MM/dd");
                    //获取文件名
                    String oldName = files.getOriginalFilename();
                    //取当前时间的长整形值包含毫秒
                    String newName = IDutils.getImageName();
                    //重新命名文件
                    newName = newName + oldName.substring(oldName.lastIndexOf("."));
                    String filePath = simpleDateFormat.format(new Date());
                    //获取输入流
                    InputStream inputStream = files.getInputStream();
                    boolean result = ftpFileUtil.uploadToFtp(inputStream, filePath, newName, false);
                    inputStream.close();
                    if (result) {
                        TMaintenanceFile uploadFile = new TMaintenanceFile();
                        uploadFile.setFilename(oldName);
                        uploadFile.setFilepath(filePath + "/" + newName);
                        uploadFile.setId(id);
                        TMaintenanceFile model = tMaintenanceFileService.add(uploadFile);
                        if (model != null) {
                            filesid += "," + model.getId();
                        }
                    } else {
                        return failed(null, "上传文件失败");
                    }
                } catch (Exception e) {
                    e.getMessage();
                }
        }else {
            return failed("请上传文件");
        }
            return success(filesid);
    }
    @GetMapping("/getlist/")
    public RESTfulResult getlist(@RequestParam String id){
        List<TMaintenanceFile> list = tMaintenanceFileService.list(id);
        return success(list);
    }
    @GetMapping("/getlists/")
    public RESTfulResult getlists(@RequestParam String construid){
        List<TMaintenanceFile> list = tMaintenanceFileService.lists(construid);
        return success(list);
    }
    @RequestMapping(value = "/downloadFile")
    public void downloadFile(@RequestParam("filePath") String filepath, @RequestParam("fileName") String fileName, HttpServletResponse response) {
        try {
            boolean result = ftpFileUtil.download(response, fileName, filepath);
            if (!result) {
                //logger.error("下载文件<" + fileName + ">失败,文件不存在");
                response.sendError(HttpServletResponse.SC_NOT_FOUND, "下载文件失败，文件目录不存在或文件不存在。");
            }
        } catch (Exception e) {
            //logg.error("下载文件<" + fileName + ">失败", e);
        }
    }
    @DeleteMapping(value = "/delfile/")
    public RESTfulResult delFile(@RequestParam("fileName") String name,@RequestParam("filePath") String path){
            int count=  tMaintenanceFileService.delFile(path);
            if (count>0){
                return success("删除成功");
            }else {
                return failed("删除文件失败，文件或不存在");
            }
    }
}
