package com.steerinfo.ems.tmaintenance.controller;

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

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

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

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

    @ApiOperation(value="删除", notes="根据url的id来指定删除对象")
    @ApiImplicitParam(paramType = "path", name = "id", value = "ID", required = true, dataType = "String")
    //@RequiresPermissions("tmaintenance: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);
			  tMaintenanceService.delete(ids);
    	}
      return success();
    }
    @ApiOperation(value = "创建", notes = "根据TMaintenance对象创建")
    @ApiImplicitParam(name = "tMaintenance", value = "详细实体tMaintenance", required = true, dataType = "TMaintenance")
    //@RequiresPermissions("tmaintenance:create")
    @PostMapping(value = "/addone")
    public RESTfulResult addone(@ModelAttribute TMaintenance model) {
        //丛前端获取申报日期，利用SimpleDateFormat类转换为字符串
        String declaretime = model.getDeclaretime();
        //将转换为字符串的日期进行截取，截取出月和日
        String mouth = declaretime.substring(5, 7);
        String day = declaretime.substring(8, 10);
        Integer maxid = tMaintenanceService.MaxID(mouth);
        String id = model.getDeclareid() + mouth + "_" + day + "_" + maxid;
        model.setRecord(maxid);
        model.setDeclareid(id);
        TMaintenance tMaintenance = tMaintenanceService.add(model);
        return success(tMaintenance);
    }

    //查出所有数据
    @GetMapping("/getAll")
    public RESTfulResult getall() {
        List<TMaintenance> tMaintenance = tMaintenanceService.selectAll();
        return success(tMaintenance);
    }

    //逻辑删除
    @PutMapping(value = "/del/{ids}")
    public RESTfulResult delectMes(@PathVariable String[] ids) {
        String dateid = DateUtils.getCurrentTime("yyyy-MM-dd HH:mm:ss");
        int count = 0;
        for (int i = 0; i < ids.length; i++) {
            count = tMaintenanceService.deleMes(ids[i], dateid);

        }
        return success(count, "本次共删除" + count + "条数据");
    }
    //取消提交
    @PutMapping(value = "/updatecheck/{ids}")
    public RESTfulResult updatecheck(@PathVariable String[] ids) {
        String dateid = DateUtils.getCurrentTime("yyyy-MM-dd HH:mm:ss");
        int count = 0;
        for (int i = 0; i < ids.length; i++) {
            count = tMaintenanceService.updatecheck(ids[i]);
        }
        return success(count, "本次共删除" + count + "条数据");
    }

    //修改
    @PutMapping(value = "/pus/")
    public RESTfulResult putMes(@ModelAttribute MultipartFile[] file, TMaintenance model, String del) {
        String datetime = DateUtils.getCurrentTime("yyyy-MM-dd HH:mm:ss");
        if (model == null) {
            return failed(null, "参数错误！");
        }
        TMaintenance tMaintenance = new TMaintenance();
        String bid = model.getDeclareid();
        String filenames=tMaintenanceService.selectfilename(bid);
        if (filenames==null){
            filenames = "";
        }
        String filenamesa = "";
        for (int i = 0; i < file.length; i++) {
            filenamesa+=file[i].getOriginalFilename()+";";
        }
        String newfilename = filenames+";"+filenamesa;
        model.setFilename(newfilename);
        model.setChargetime(datetime);
        tMaintenanceService.modify(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.getDeclareid());
                        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(tMaintenance);
    }

    //多项匹配模糊查询
    @GetMapping("/getmsg")
    public RESTfulResult getMsg(HashMap parameters) {
        List<TMaintenance> tMaintenance = tMaintenanceService.queryLike(parameters);

        return success(tMaintenance);
    }

    //批量
//    @PutMapping(value = "/pusAll")
//    public RESTfulResult pusAll( String[] declareid,String billstatus) {
//        for (int i = 0; i <declareid.length ; i++) {
//            tMaintenanceService.pusMesAll(declareid[i],billstatus);
//        }
//        return success();
//    }

    @PutMapping(value = "/pusAll")
    public RESTfulResult pusAll(@RequestBody TMaintenance[]params) {
        for (int i = 0; i <params.length ; i++) {
            String Declareid= params[i].getDeclareid();
            String Billstatus= params[i].getBillstatus();
            tMaintenanceService.pusMesAll(Declareid,Billstatus);
        }
        return success();
    }

    @ApiOperation(value="暂存", notes="根据url的id来指定更新对象，并根据传过来的tCm035信息来更新详细信息")
    @ApiImplicitParam(name = "tCm035", value = "详细实体tCm035", required = true, dataType = "TCm035")
    //@RequiresPermissions("tcm035:update")
    @PutMapping(value = "/submit/")
    public RESTfulResult update(@ModelAttribute MultipartFile[] file, TMaintenance model, String del){
        if (model == null) {
            return failed(null, "参数错误！");
        }
        String ids= "";
        if(model.getApplayer()=="烧结"||"烧结".equals(model.getApplayer())){
            ids = "SJ_";
        }
        if(model.getApplayer()=="炼钢"||"炼钢".equals(model.getApplayer())){
            ids = "LG_";
        }
        if(model.getApplayer()=="建材"||"建材".equals(model.getApplayer())){
            ids = "JC_";
        }
        if(model.getApplayer()=="电厂"||"电厂".equals(model.getApplayer())){
            ids = "DC_";
        }
        if(model.getApplayer()=="高炉"||"高炉".equals(model.getApplayer())){
            ids = "GL_";
        }
        if(model.getApplayer()=="机焦"||"机焦".equals(model.getApplayer())){
            ids = "JJ_";
        }
        if(model.getApplayer()=="高线"||"高线".equals(model.getApplayer())){
            ids = "GX_";
        }
        if(model.getApplayer()=="型钢"||"型钢".equals(model.getApplayer())){
            ids = "XG_";
        }
        TMaintenance tMaintenance = new TMaintenance();
        //丛前端获取申报日期，利用SimpleDateFormat类转换为字符串
        String declaretime = model.getDeclaretime();
        //将转换为字符串的日期进行截取，截取出月和日
        String mouth = declaretime.substring(5, 7);
        Integer maxid = tMaintenanceService.MaxID(mouth);
        model.setRecord(maxid);
        String updatetime = DateUtils.getCurrentTime("yyyy-MM-dd HH:mm:ss");
        model.setChargetime(updatetime);
        String bid = model.getDeclareid();
        model.setDeclareid(ids+DateUtils.getCurrentTime("yyyyMMdd") + "_"+ String.format("%04d", maxid));
        String filenames ="";
        for (int i = 0; i <file.length ; i++) {
            filenames+=file[i].getOriginalFilename()+";";
        }
        model.setFilename(filenames);
        tMaintenance = tMaintenanceService.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.getDeclareid());
                        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(tMaintenance);
    }
    //审批首页加载数据
    @GetMapping(value = "/likeapproval/")
    public RESTfulResult listLikeapproval(@RequestParam HashMap parmas, Integer pageNum, Integer pageSize) {
        PageList<TMaintenance> list = tMaintenanceService.listLikeapproval(parmas, pageNum, pageSize);
        return success(list);
    }
    //审批分类查询
    @GetMapping(value = "/likeapprovals/")
    public RESTfulResult listLikeapprovals(@RequestParam HashMap parmas, Integer pageNum, Integer pageSize) {
        PageList<TMaintenance> list = tMaintenanceService.listLikeapprovals(parmas, pageNum, pageSize);

        return success(list);
    }
    @PutMapping(value = "/pusAlla")
    public RESTfulResult pusAlla(@RequestBody TMaintenance[]params) {
        String datetime = DateUtils.getCurrentTime("yyyy-MM-dd HH:mm:ss");
        for (int i = 0; i <params.length ; i++) {
            String Declareid= params[i].getDeclareid();
            String Billstatus= params[i].getBillstatus();
            String approver = params[i].getApprover();
            tMaintenanceService.pusMesAlla(Declareid,Billstatus,approver,datetime);
        }
        return success();
    }
    //报工审批分类查询
    @GetMapping(value = "/approval/")
    public RESTfulResult listLikapproval(@RequestParam HashMap parmas, Integer pageNum, Integer pageSize) {
        PageList<TMaintenance> list = tMaintenanceService.approval(parmas, pageNum, pageSize);
        return success(list);
    }
    //根据报工状态改变审核单状态
    @PostMapping("/upstate/")
    public RESTfulResult upstate(@RequestParam HashMap<String,String> tSubmitted){
        TMaintenance tMaintenance = new TMaintenance();
       String declareid= tSubmitted.get("declareid");
        String state = tSubmitted.get("state");

       if (state==null||"".equals(state)){
           return failed(null,"状态不能为空");
       }else {
           tMaintenance.setDeclareid(declareid);
           tMaintenance.setBillstatus(state);
           Integer count = tMaintenanceService.upstate(tMaintenance);
           return success(count);
       }
    }
    //下载附件
    @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);
        }
    }
}
