package com.steerinfo.ems.trmfactory.controller;

import com.steerinfo.auth.utils.JwtUtil;
import com.steerinfo.ems.trmfactory.model.TRmFactory;
import com.steerinfo.ems.trmfactory.service.ITRmFactoryService;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.jar.JarEntry;

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

    private static final Logger LOGGER = LoggerFactory.getLogger(TRmFactoryController.class);

    @Autowired
    ITRmFactoryService tRmFactoryService;

    @ApiOperation(value="获取列表", notes="分页查询")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "pageNum", value = "查询页数", required = false, dataType = "Integer"),
        @ApiImplicitParam(name = "pageSize", value = "每页记录数", required = false, dataType = "Integer")
    })
    //@RequiresPermissions("trmfactory:view")
    @GetMapping(value = "/")
    public RESTfulResult list(@RequestParam HashMap parmas,Integer pageNum, Integer pageSize){
        PageList<TRmFactory> list = tRmFactoryService.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("trmfactory:view")
    @GetMapping(value = "/like/")
    public RESTfulResult listLike(@RequestParam HashMap parmas,Integer pageNum, Integer pageSize){
        PageList<TRmFactory> list = tRmFactoryService.queryLikeForPage(parmas, pageNum, pageSize);
        return success(list);
    }
    
    @ApiOperation(value="创建", notes="根据TRmFactory对象创建")
    @ApiImplicitParam(name = "tRmFactory", value = "详细实体tRmFactory", required = true, dataType = "TRmFactory")
    //@RequiresPermissions("trmfactory:create")
    @PostMapping(value = "/")
    public RESTfulResult add(@ModelAttribute TRmFactory model){
        model.setState(model.getState() == null ? "1" : model.getState());
        if(model.getName() == null || "".equals(model.getName()) || model.getType() == null || "".equals(model.getType())){
            return failed(null, "name,type这两者不能为空");
        }
        else if(tRmFactoryService.getById(model.getId()) != null){
            return failed(null, "id已存在，不能新增");
        }
        else{
            model.setSeqno(tRmFactoryService.getMaxSeqno() + 1);
            model.setCreateman(JwtUtil.getUseridByToken());
            TRmFactory tRmFactory = tRmFactoryService.add(model);
            return success(tRmFactory);
        }
    }

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

    @ApiOperation(value="更新详细信息", notes="根据url的id来指定更新对象，并根据传过来的tRmFactory信息来更新详细信息")
    @ApiImplicitParams({
        @ApiImplicitParam(paramType = "path", name = "id", value = "ID", required = true, dataType = "String"),
        @ApiImplicitParam(name = "tRmFactory", value = "详细实体tRmFactory", required = true, dataType = "TRmFactory")
    })
    //@RequiresPermissions("trmfactory:update")
    @PutMapping(value = "/{id}", produces  = "application/json;charset=UTF-8")
    public RESTfulResult update(@PathVariable String id, @RequestBody TRmFactory model){
        if(model.getName() == null || "".equals(model.getName()) || model.getType() == null || "".equals(model.getType())){
            return failed(null, "name,type这两者不能为空");
        }
        else {
            LOGGER.info("工厂维护表更新前数据是" + tRmFactoryService.getById(model.getId()).toString());
            model.setId(id);
            model.setUpdateman(JwtUtil.getUseridByToken());
            TRmFactory tRmFactory = tRmFactoryService.modify(model);
            LOGGER.info("工厂维护表更新后数据是" + tRmFactory.toString());
            return success(tRmFactory);
        }
    }

    @ApiOperation(value="删除", notes="根据url的id来指定删除对象")
    @ApiImplicitParam(paramType = "path", name = "id", value = "ID", required = true, dataType = "String")
    //@RequiresPermissions("trmfactory:delete")
    @DeleteMapping(value = "/{id}")
    public RESTfulResult delete(@PathVariable String id){
        String[] array = id.split(",");
        if(array.length >= 1) {
            int failnum = 0 ;
            String failmsg = "";
            for (int i = 0; i < array.length; i++) {
                try{
                    LOGGER.info("工厂信息维护要删除的第" + (i + 1) + "条数据是" + tRmFactoryService.getById(array[i]).toString());
                    tRmFactoryService.delete(array[i]);
                }
                catch (Exception e){
                    failnum++;
                    failmsg += "工厂信息维护删除在第" + (i + 1) + "条数据出现错误,错误原因是" + e + ",id是" + array[i];
                }
            }
            if(failnum > 0){
                LOGGER.info(JwtUtil.getUseridByToken() + "本次共删除" + array.length + "条数据,其中成功" + (array.length - failnum) + "条,失败" + failnum + "条,失败原因:" + failmsg);
                return success(51,"本次共删除" + array.length + "条数据,其中成功" + (array.length - failnum) + "条,失败" + failnum + "条,失败的数据id:" + array.toString());
            }
            return success();
        }
        else {
            return failed(null, "请输入要删除的id");
        }
    }

    @ApiOperation(value="批量更新详细信息", notes="根据传过来的tRmFactory数组信息来更新详细信息")
    @ApiImplicitParam(name = "tRmFactory", value = "详细实体tRmFactory", required = true, dataType = "TRmFactory")
    //@RequiresPermissions("trmfactory:update")
    @PutMapping(value = "/", produces  = "application/json;charset=UTF-8")
    public RESTfulResult batchupdate(@RequestBody TRmFactory[] model){
        int failnum = 0;
        String failmsg = "";
        List<String> errorid = new ArrayList<>();
        for(int i = 0;i < model.length;i++){
            try {
                LOGGER.info("工厂信息维护修改的第" + (i + 1) + "条数据:");
                LOGGER.info("工厂信息维护修改前数据是" + tRmFactoryService.getById(model[i].getId()).toString());
                model[i].setUpdateman(JwtUtil.getUseridByToken());
                TRmFactory tRmFactory = tRmFactoryService.modify(model[i]);
                LOGGER.info("工厂信息维护修改后数据是" + tRmFactory.toString());
            }
            catch(Exception e){
                failnum++;
                errorid.add(model[i].getId());
                failmsg += "工厂信息维护修改在第" + (i + 1) + "条数据出现错误,错误原因是" + e + ",id是" + model[i].getId();
            }
        }
        if(failnum > 0){
            LOGGER.info("本次共修改" + model.length + "条数据,其中成功" + (model.length - failnum) + "条,失败" + failnum + "条,失败原因:" + failmsg);
            return success(errorid,"51","本次共修改" + model.length + "条数据,其中成功" + (model.length - failnum) + "条,失败" + failnum + "条");
        }
        return success();
    }

    @ApiOperation(value = "查询",notes = "查询 Id and Name")
    @GetMapping("/getIAndName")
    public RESTfulResult getIAndName(){
        Set<TRmFactory> idAndName = tRmFactoryService.getIdAndName();
        return  success(idAndName);
    }
}
