package com.steerinfo.ems.tcm0365.controller;

import com.steerinfo.ems.Utils.DateUtils;
import com.steerinfo.ems.tcm036.model.TCm036;
import com.steerinfo.ems.tcm0365.model.TCm0365;
import com.steerinfo.ems.tcm0365.service.ITCm0365Service;
import com.steerinfo.framework.controller.BaseRESTfulController;
import com.steerinfo.framework.controller.RESTfulResult;
import com.steerinfo.framework.service.pagehelper.PageList;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
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.util.Arrays;
import java.util.HashMap;

/**
 * TCm0365 RESTful接口：
 * @author 王金涛
 * @version 1.0-SNAPSHORT 2019-10-29 10:02
 * 类描述
 * 修订历史：
 * 日期：2019-10-29
 * 作者：王金涛
 * 参考：
 * 描述：TCm0365 RESTful接口
 * @see null
 * @Copyright 湖南视拓信息技术股份有限公司. All rights reserved.
 */
@RestController
@RequestMapping("/${api.version}/tcm0365s")
public class TCm0365Controller extends BaseRESTfulController {

    @Autowired
    ITCm0365Service tCm0365Service;
    
    /** 文件保存路径  */
	public static final String FILE_DIR = "/static/";

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

    @ApiOperation(value="删除", notes="根据url的id来指定删除对象")
    @ApiImplicitParam(paramType = "path", name = "id", value = "ID", required = true, dataType = "String")
    //@RequiresPermissions("tcm0365:delete")
    @DeleteMapping(value = "/{id}")
    public RESTfulResult delete(@PathVariable String id){
        if (StringUtils.indexOf(id, ",") == -1) {
            tCm0365Service.delete(id);
        } else {
            tCm0365Service.delete(Arrays.asList(id.split(",")));
        }
        return success();
    }

    @ApiOperation(value="暂存", notes="根据url的id来指定更新对象，并根据传过来的tCm0365信息来更新详细信息")
    @ApiImplicitParam(name = "tCm0365", value = "详细实体tCm0365", required = true, dataType = "TCm0365")
    //@RequiresPermissions("tcm0365:update")
    @PutMapping(value = "/")
    public RESTfulResult update(@ModelAttribute MultipartFile[] file, TCm0365 model, String del){
    	if (model == null) {
    		return failed(null, "参数错误！");
    	}
    	TCm0365 tCm0365 = new TCm0365();
    	String bid = model.getBillsno();
        if(model.getBillsno() == null || "".equals(model.getBillsno()) || tCm0365Service.getById(model.getBillsno()) == null){
            if(model.getCreattime() == null || "".equals(model.getCreattime())){
                model.setCreattime(DateUtils.getCurrentTime("yyyy-MM-dd HH:mm:ss"));
            }
            model.setBillstatus("create");
            int maxid = tCm0365Service.getMaxId() == null ? 1 : Integer.parseInt(tCm0365Service.getMaxId()) + 1;
            model.setBillsno("DLYFD_" + DateUtils.getCurrentTime("yyyyMMdd") + "_"+ String.format("%04d", maxid));
            tCm0365 = tCm0365Service.add(model);
        } else {
            tCm0365 = tCm0365Service.modify(model);
        }
        try {
        	// 上传文件
        	if (file!=null && file.length>0) {
        		// 文件目录，如果目录不存在，自动创建
        		String uploadDir = FILE_DIR + tCm0365.getBillsno() + "/";
                File dir = new File(uploadDir);
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                for (int i = 0;i < file.length;i++){
                    // 上传文件名
                	String fileName = file[i].getOriginalFilename();
                    // 服务器端保存的文件对象
                    File serverFile = new File(uploadDir, fileName);
                    file[i].transferTo(serverFile.getAbsoluteFile());
                }
        	}
            // 删除文件
            if(del!=null && !del.isEmpty() && !bid.isEmpty()) {
            	for (String df : del.split(";")){
            		if (!df.isEmpty() && df.trim().length()>1) {
            			String path = FILE_DIR + bid + "/" + df;
                		File f = new File(path).getAbsoluteFile();
                		if(f.exists()){
                			f.delete();
                		}
            		}
            	}
            }
        } catch (Exception e) {
            e.printStackTrace();
            return failed(null,"上传失败!失败原因："+e.toString());
        }
        return success(tCm0365);
    }

    @ApiOperation(value="提交", notes="根据url的id来指定更新对象，并根据传过来的tCm0365信息来更新详细信息")
    @ApiImplicitParam(name = "tCm0365", value = "详细实体tCm0365", required = true, dataType = "TCm0365")
    //@RequiresPermissions("tcm0365:update")
    @PutMapping(value = "/submit/")
    public RESTfulResult submit(@ModelAttribute MultipartFile[] file, TCm0365 model, String del){
    	if (model == null) {
    		return failed(null, "参数错误！");
    	}
    	TCm0365 tCm0365 = new TCm0365();
    	String bid = model.getBillsno();
        if(model.getBillsno() == null || "".equals(model.getBillsno()) || tCm0365Service.getById(model.getBillsno()) == null){
            if(model.getCreattime() == null || "".equals(model.getCreattime())){
                model.setCreattime(DateUtils.getCurrentTime("yyyy-MM-dd HH:mm:ss"));
            }
            model.setBillstatus("sign");
            int maxid = tCm0365Service.getMaxId() == null ? 1 : Integer.parseInt(tCm0365Service.getMaxId()) + 1;
            model.setBillsno("DLYFD_" + DateUtils.getCurrentTime("yyyyMMdd") + "_"+ String.format("%04d", maxid));
            tCm0365 = tCm0365Service.add(model);
        } else {
            switch (model.getBillstatus()) {
                case "":
                    if(model.getCreattime() == null || "".equals(model.getCreattime())){
                        model.setCreattime(DateUtils.getCurrentTime("yyyy-MM-dd HH:mm:ss"));
                    }
                    model.setBillstatus("sign");
                    break;
                case "create":
                    model.setBillstatus("sign");
                    break;
                case "sign":
                    if (model.getSigntime() == null || "".equals(model.getSigntime())) {
                        model.setSigntime(DateUtils.getCurrentTime("yyyy-MM-dd HH:mm:ss"));
                    }
                    model.setBillstatus("execute");
                    break;
                case "execute":
                    if (model.getExecutivetime() == null || "".equals(model.getExecutivetime())) {
                        model.setExecutivetime(DateUtils.getCurrentTime("yyyy-MM-dd HH:mm:ss"));
                    }
                    model.setBillstatus("executed");
                    break;
                case "drop":
                    break;
                case "returncreate":
                    model.setSignman("");
                    model.setSigntime("");
                    model.setBillstatus("create");
                    break;
                default:
                    failed(null, "单据状态参数错误！");
            }
            tCm0365 = tCm0365Service.modify(model);
        }
        try {
        	// 上传文件
        	if (file!=null && file.length>0) {
        		// 文件目录，如果目录不存在，自动创建
        		String uploadDir = FILE_DIR + tCm0365.getBillsno() + "/";
                File dir = new File(uploadDir);
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                for (int i = 0;i < file.length;i++){
                    // 上传文件名
                	String fileName = file[i].getOriginalFilename();
                    // 服务器端保存的文件对象
                    File serverFile = new File(uploadDir, fileName);
                    file[i].transferTo(serverFile.getAbsoluteFile());
                }
        	}
            // 删除文件
            if(del!=null && !del.isEmpty() && !bid.isEmpty()) {
            	for (String df : del.split(";")){
            		if (!df.isEmpty() && df.trim().length()>1) {
            			String path = FILE_DIR + bid + "/" + df;
                		File f = new File(path).getAbsoluteFile();
                		if(f.exists()){
                			f.delete();
                		}
            		}
            	}
            }
        } catch (Exception e) {
            e.printStackTrace();
            return failed(null,"上传失败!失败原因："+e.toString());
        }
        return success(tCm0365);
    }

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

    @ApiOperation(value="获取列表", notes="分页模糊查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "查询页数", required = false, dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "每页记录数", required = false, dataType = "Integer")
    })
    //@RequiresPermissions("tcm0365:view")
    @GetMapping(value = "/like/")
    public RESTfulResult listLike(@RequestParam HashMap parmas,Integer pageNum, Integer pageSize){
        PageList<TCm0365> list = tCm0365Service.queryLikeForPage(parmas, pageNum, pageSize);
        return success(list);
    }

 @ApiOperation(value="创建", notes="根据TCm0365对象创建")
 @ApiImplicitParam(name = "tCm0365", value = "详细实体tCm0365", required = true, dataType = "TCm0365")
 //@RequiresPermissions("tcm0365:create")
 @PostMapping(value = "/")
 public RESTfulResult add(@ModelAttribute TCm0365 model){
 if(model.getCreattime() == null || "".equals(model.getCreattime())){
 model.setCreattime(DateUtils.getCurrentTime("yyyy-MM-dd HH:mm:ss"));
 }
 model.setOperatestatus("save");
 model.setBillstatus("create");
 TCm0365 tCm0365 = tCm0365Service.add(model);
 return success(tCm0365);
 }
    */
}
