package com.steerinfo.ems.trmindexitemtype.controller;

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.auth.utils.JwtUtil;
import com.steerinfo.ems.trmindexitem.mapper.TRmIndexItemMapper;
import com.steerinfo.ems.trmindexitem.model.TRmIndexItem;
import com.steerinfo.ems.trmindexitemtype.model.TRmIndexItemType;
import com.steerinfo.ems.trmindexitemtype.service.ITRmIndexItemTypeService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * TRmIndexItemType RESTful接口：
 * @author generator
 * @version 1.0-SNAPSHORT 2020-06-30 03:34
 * 类描述
 * 修订历史：
 * 日期：2020-06-30
 * 作者：generator
 * 参考：
 * 描述：TRmIndexItemType RESTful接口
 * @see null
 * @Copyright 湖南视拓信息技术股份有限公司. All rights reserved.
 */
@RestController
@RequestMapping("/${api.version}/trmindexitemtypes")
public class TRmIndexItemTypeController extends BaseRESTfulController {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(TRmIndexItemTypeController.class);

    @Autowired
    ITRmIndexItemTypeService tRmIndexItemTypeService;
    @Autowired
    private TRmIndexItemMapper tRmIndexItemMapper;

    @ApiOperation(value="获取列表", notes="分页查询")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "pageNum", value = "查询页数", required = false, dataType = "Integer"),
        @ApiImplicitParam(name = "pageSize", value = "每页记录数", required = false, dataType = "Integer")
    })
    //@RequiresPermissions("trmindexitemtype:view")
    @GetMapping(value = "/")
    public RESTfulResult list(@RequestParam HashMap parmas,Integer pageNum, Integer pageSize){
        PageList<TRmIndexItemType> list = tRmIndexItemTypeService.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("trmindexitemtype:view")
    @GetMapping(value = "/like/")
    public RESTfulResult listLike(@RequestParam HashMap parmas,Integer pageNum, Integer pageSize){
        PageList<TRmIndexItemType> list = tRmIndexItemTypeService.queryLikeForPage(parmas, pageNum, pageSize);
        return success(list);
    }
    
    @ApiOperation(value="创建", notes="根据TRmIndexItemType对象创建")
    @ApiImplicitParam(name = "tRmIndexItemType", value = "详细实体tRmIndexItemType", required = true, dataType = "TRmIndexItemType")
    //@RequiresPermissions("trmindexitemtype:create")
    @PostMapping(value = "/")
    public RESTfulResult add(@ModelAttribute TRmIndexItemType model){
    	if(model == null) {
    		return failed(null, "请传入参数数据");
    	}
    	if(model.getItemtype() == null || model.getItemtype().isEmpty() || model.getItemtype().trim().length() >1) {
    		return failed(null, "指标用途代码为一位字母");
    	}
    	if(model.getName() == null || model.getName().trim().isEmpty()) {
    		return failed(null, "指标用途名称不能为空");
    	}
    	if(tRmIndexItemTypeService.getById(model.getItemtype())!=null) {
    		return failed(null, "指标用途代码[" + model.getItemtype() + "]已存在");
    	}
    	model.setItemtype(model.getItemtype().toUpperCase());
    	model.setCreateman(JwtUtil.getUseridByToken());
    	model.setCreatetime(new Date());
        TRmIndexItemType tRmIndexItemType = tRmIndexItemTypeService.add(model);
        return success(tRmIndexItemType);
    }

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

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

    @ApiOperation(value="删除", notes="根据url的id来指定删除对象")
    @ApiImplicitParam(paramType = "path", name = "id", value = "ID", required = true, dataType = "String")
    //@RequiresPermissions("trmindexitemtype:delete")
    @DeleteMapping(value = "/{id}")//String
    public RESTfulResult delete(@PathVariable String id){
    	HashMap<String, Object> parmas = new HashMap<String, Object>();
    	if(id!=null && !id.isEmpty()){
			if(!id.startsWith("'")){
				String itemtype = "'" + id.replaceAll(",", "','").replaceAll("，", "','") + "'";
				parmas.put("itemtype", itemtype);
			}else{
				parmas.put("itemtype", id);
			}
			List<TRmIndexItem> l = tRmIndexItemMapper.selectLikeByParameters(parmas);
			if(l!=null && l.size()>0){
				return failed(null, "用途类型已被使用，不能删除");
			}
		}else{
			return failed(null, "请传入要删除的编号");
		}
    	List<String> list = Arrays.asList(id.split(","));
    	if(ListUtils.isNotEmpty(list)) {
	    	List<String> ids = ListUtils.convertList(list);
			tRmIndexItemTypeService.delete(ids);
    	}
    	return success();
    }
    
    @ApiOperation(value="批量更新详细信息", notes="根据传过来的tRmIndexItemType数组信息来更新详细信息")
    @ApiImplicitParam(name = "tRmIndexItemType", value = "详细实体tRmIndexItemType", required = true, dataType = "tRmIndexItemType")
    //@RequiresPermissions("trmworkproc:update")
    @PutMapping(value = "/", produces  = "application/json;charset=UTF-8")
    public RESTfulResult batchupdate(@RequestBody TRmIndexItemType[] 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("指标用途维护修改前数据是" + tRmIndexItemTypeService.getById(model[i].getId()).toString());
                model[i].setCreateman(JwtUtil.getUseridByToken());
                model[i].setCreatetime(new Date());
                TRmIndexItemType tRmIndexItemType = tRmIndexItemTypeService.modify(model[i]);
                LOGGER.info("指标用途维护修改后数据是" + tRmIndexItemType.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();
    }
}
