package com.steerinfo.ems.tsubmitted.controller;

import com.steerinfo.auth.utils.JwtUtil;
import com.steerinfo.ems.Utils.DateUtils;
import com.steerinfo.ems.tmaintenance.model.TMaintenance;
import com.steerinfo.ems.tmaintenance.service.ITMaintenanceService;
import com.steerinfo.ems.tmaintenancefile.model.TMaintenanceFile;
import com.steerinfo.ems.tmaintenancefile.service.ITMaintenanceFileService;
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.tsubmitted.model.TSubmitted;
import com.steerinfo.ems.tsubmitted.service.ITSubmittedService;
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.poi.ss.formula.functions.T;
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 java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;
import java.math.BigDecimal;

/**
 * TSubmitted RESTful接口：
 * @author generator
 * @version 1.0-SNAPSHORT 2022-06-10 04:08
 * 类描述
 * 修订历史：
 * 日期：2022-06-10
 * 作者：generator
 * 参考：
 * 描述：TSubmitted RESTful接口
 * @see null
 * @Copyright 湖南视拓信息技术股份有限公司. All rights reserved.
 */
@RestController
@RequestMapping("/${api.version}/tsubmitteds")
public class TSubmittedController extends BaseRESTfulController {
    /** 文件保存路径  */
    public static final String FILE_DIR = "/static/";
    @Autowired
    ITSubmittedService tSubmittedService;
    @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("tsubmitted:view")
    @GetMapping(value = "/")
    public RESTfulResult list(@RequestParam HashMap parmas,Integer pageNum, Integer pageSize){
        PageList<TSubmitted> list = tSubmittedService.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("tsubmitted:view")
    @GetMapping(value = "/like/")
    public RESTfulResult listLike(@RequestParam HashMap parmas,Integer pageNum, Integer pageSize){
        PageList<TSubmitted> list = tSubmittedService.queryLikeForPage(parmas, pageNum, pageSize);
        return success(list);
    }
    
    @ApiOperation(value="创建", notes="根据TSubmitted对象创建")
    @ApiImplicitParam(name = "tSubmitted", value = "详细实体tSubmitted", required = true, dataType = "TSubmitted")
    //@RequiresPermissions("tsubmitted:create")
    @PostMapping(value = "/")
    public RESTfulResult add(@ModelAttribute TSubmitted model){
        TSubmitted tSubmitted = tSubmittedService.add(model);
        return success(tSubmitted);
    }

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

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

    @ApiOperation(value="删除", notes="根据url的id来指定删除对象")
    @ApiImplicitParam(paramType = "path", name = "id", value = "ID", required = true, dataType = "String")
    //@RequiresPermissions("tsubmitted: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);
			  tSubmittedService.delete(ids);
    	}
      return success();
    }

    @PutMapping("/getimage/")
    public RESTfulResult getimage(@ModelAttribute MultipartFile[] file, TSubmitted model) throws IOException {
        if (file!=null && file.length>0){
            //将文件名赋值给model
            TSubmitted tSubmitted = new TSubmitted();

            tSubmitted.setConstruid( model.getConstruid());
            String uploadDir = FILE_DIR +model.getConstruid()+"/";
            File dir = new File(uploadDir);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            dir.setReadOnly();
            for (int i = 0; i < file.length; i++) {
                //获取文件原始名
                String imagename= file[i].getOriginalFilename();
                model.setImagename(imagename);
                // 服务器端保存的文件对象
                File serverFile = new File(uploadDir, imagename);
                file[i].transferTo(serverFile.getAbsoluteFile());
                tSubmitted.setImagename(imagename);
            }
            return success(tSubmitted);
        }
        return failed("传入文件类型不符合");
    }

    @PostMapping(value = "/pus/")
    public RESTfulResult putMes(@ModelAttribute MultipartFile[] file, TSubmitted model, String del) {
        if (model.getSigntime()==null||"".equals(model.getSigntime())){
             return failed(null,"日期不能为空");
        }
        if (model.getState()==null||"".equals(model.getState())){
            return failed(null,"状态不能为空");
        } if (model.getConstrucontent()==null||"".equals(model.getConstrucontent())){
            return failed(null,"内容不能为空");
        }
        HashMap hashMap = new HashMap();
        hashMap.put("declareid",model.getDeclareid());
        //丛前端获取申报日期，利用SimpleDateFormat类转换为字符串
        String Signtime = model.getSigntime();

        //将转换为字符串的日期进行截取，截取出月和日
        String mouth = Signtime.substring(5, 7);
        Integer maxid = tSubmittedService.MaxID(mouth);
        model.setMaxid(new BigDecimal(maxid));

        String datetime = DateUtils.getCurrentTime("yyyy-MM-dd");
        if (model == null) {
            return failed(null, "参数错误！");
        }
        TSubmitted tSubmitted = new TSubmitted();
        String bid = model.getConstruid();
        model.setConstruid(model.getDeclareid()+ "_"+ String.format("%04d", maxid));
        String filenames ="";
        for (int i = 0; i <file.length ; i++) {
            filenames+=file[i].getOriginalFilename()+";";
        }
        model.setConstrufile(filenames);
        tSubmitted= tSubmittedService.add(model);
        String filesid = "";
        if (file!=null){
            for (int i = 0; i <file.length ; i++) {
                try {
                    String userId = JwtUtil.getUseridByToken();
                    //获取系统时间
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("/yyyy/MM/dd");
                    //获取文件名
                    String oldName = file[i].getOriginalFilename();
                    //取当前时间的长整形值包含毫秒
                    String newName = IDutils.getImageName();
                    //重新命名文件
                    newName = newName + oldName.substring(oldName.lastIndexOf("."));
                    String filePath = simpleDateFormat.format(new Date());
                    //获取输入流
                    InputStream inputStream = file[i].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(model.getConstruid());
                        TMaintenanceFile modela = tMaintenanceFileService.add(uploadFile);
                        if (modela != null) {
                            filesid += "," + modela.getId();
                        }
                    } else {
                        return failed(null, "上传文件失败");
                    }
                } catch (Exception e) {
                    e.getMessage();
                }
            }
            return success(filesid);
        }
        return success(tSubmitted);
    }
    @DeleteMapping("/del/{construid}")
    public RESTfulResult del(@PathVariable String construid){
               tSubmittedService.delete(construid);
               return success("撤销成功");
    }

}
