package com.steerinfo.ems.tcm0310.controller;

import com.steerinfo.auth.utils.JwtUtil;
import com.steerinfo.ems.tcm0310.model.TCm0310;
import com.steerinfo.ems.tcm0310.service.ITCm0310Service;
import com.steerinfo.ems.tcm0312.service.ITCm0312Service;
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.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.HashMap;
import java.util.List;
import java.util.Map;

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

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

    @Autowired
    ITCm0310Service tCm0310Service;
    @Autowired
    ITCm0312Service tCm0312Service;

    @ApiOperation(value="获取列表", notes="分页查询")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "pageNum", value = "查询页数", required = false, dataType = "Integer"),
        @ApiImplicitParam(name = "pageSize", value = "每页记录数", required = false, dataType = "Integer")
    })
    //@RequiresPermissions("tcm0310:view")
    @GetMapping(value = "/")
    public RESTfulResult list(@RequestParam HashMap parmas,Integer pageNum, Integer pageSize){
        PageList<TCm0310> list = tCm0310Service.queryForPage(parmas, pageNum, pageSize);
        return success(list);
    }
    
    @ApiOperation(value="创建", notes="根据TCm0310对象创建")
    @ApiImplicitParam(name = "tCm0310", value = "详细实体tCm0310", required = true, dataType = "TCm0310")
    //@RequiresPermissions("tcm0310:create")
    @PostMapping(value = "/")
    public RESTfulResult add(@ModelAttribute TCm0310 model){
        model.setSort(tCm0310Service.getmaxsort() + 1);
        if (model.getWatercode() == null || "".equals(model.getWatercode())) {
            Long maxid = tCm0310Service.getMaxId() == null ? 1 : Long.parseLong(tCm0310Service.getMaxId()) + 1;
            model.setWatercode("Q" + String.format("%05d", maxid));
        }
        model.setCreateman(JwtUtil.getUseridByToken());
        TCm0310 tCm0310 = tCm0310Service.add(model);
        return success(tCm0310);
    }

    @ApiOperation(value="更新详细信息", notes="根据主键watercode来指定更新对象，并根据传过来的tCm0310信息来更新详细信息")
    @ApiImplicitParam(name = "tCm0310", value = "详细实体tCm0310", required = true, dataType = "TCm0310")
    @PutMapping(value = "/")
    public RESTfulResult update(@RequestBody TCm0310 model){
        if(model.getWatercode() == null || model.getWatercode().isEmpty()){
            return failed(null, "请传入主键参数:watercode");
        }
        else {
            LOGGER.info("水质系统维护修改前的数据是" + tCm0310Service.getById(model.getWatercode()).toString());
            model.setUpdateman(JwtUtil.getUseridByToken());
            TCm0310 tCm0310 = tCm0310Service.modify(model);
            LOGGER.info("水质系统维护修改后的数据是" + tCm0310.toString());
            return success(tCm0310);
        }
    }

    @ApiOperation(value="删除", notes="根据主键watercode来指定删除对象")
    @ApiImplicitParam(paramType = "path", name = "id", value = "ID", required = true, dataType = "String")
    @DeleteMapping(value = "/{id}")
    //@RequiresPermissions("tcm0310:delete")
    public RESTfulResult delete(@PathVariable String id) {
        String[] array = id.split(",");
        int failnum = 0;
        String failmsg = "";
        for (int i = 0; i < array.length; i++) {
            if(tCm0312Service.queryByProperty("systemname", array[i]).size() != 0){
                LOGGER.error("水质系统维护在删除第" + (i + 1) + "条数据时出现问题，id是" + array[i] + "原因是在T_CM_0312表存在关系。");
                failnum++;
                failmsg += array[i] + "在水质监测计划制定维护界面存在关系，请先删除对应关系！";
                continue;
            }
            if(tCm0310Service.getById(array[i]) == null){
                LOGGER.error("水质系统维护在删除第" + (i + 1) + "条数据时出现问题，水质系统维护不存在该" + array[i]);
                failnum++;
                failmsg += System.getProperty("line.separator") +"水质系统维护不存在该" + array[i];
                continue;
            }
            LOGGER.info("水质系统维护要删除的第" + (i + 1) + "条数据是" + tCm0310Service.getById(array[i]).toString());
            tCm0310Service.delete(array[i]);
        }
        if(failnum > 0){
            LOGGER.info(JwtUtil.getUseridByToken() + "本次共删除" + array.length + "条数据,其中成功" + (array.length - failnum) + "条,失败" + failnum + "条,失败的数据id:" + failmsg);
            return success(51,"本次共删除" + array.length + "条数据,其中成功" + (array.length - failnum) + "条,失败" + failnum + "条,失败原因：" + failmsg);
        }
        return success();
    }

    @ApiOperation(value="系统名称下拉框", notes="查询id和name")
    @GetMapping(value = "/getidandname/")
    public RESTfulResult getNameAndId(){
        List<TCm0310> tCm0310 = tCm0310Service.getNameAndId();
        return success(tCm0310);
    }

    @ApiOperation(value="批量更新详细信息", notes="根据传过来的tCm0310数组信息来更新详细信息")
    @ApiImplicitParam(name = "tCm0310", value = "tCm0310", required = true, dataType = "TCm0310")
    //@RequiresPermissions("tcm0310:update")
    @PutMapping(value = "/", produces  = "application/json;charset=UTF-8")
    public RESTfulResult batchupdate(@RequestBody TCm0310[] 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("水质系统维护修改前数据是" + tCm0310Service.getById(model[i].getId()).toString());
                model[i].setUpdateman(JwtUtil.getUseridByToken());
                TCm0310 tCm0310 = tCm0310Service.modify(model[i]);
                LOGGER.info("水质系统维护修改后数据是" + tCm0310.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="分页模糊查询")
     @ApiImplicitParams({
     @ApiImplicitParam(name = "pageNum", value = "查询页数", required = false, dataType = "Integer"),
     @ApiImplicitParam(name = "pageSize", value = "每页记录数", required = false, dataType = "Integer")
     })
     //@RequiresPermissions("tcm0310:view")
     @GetMapping(value = "/like/")
     public RESTfulResult listLike(@RequestParam HashMap parmas,Integer pageNum, Integer pageSize){
     PageList<TCm0310> list = tCm0310Service.queryLikeForPage(parmas, pageNum, pageSize);
     return success(list);
     }
     @ApiOperation(value="获取详细信息", notes="根据url的id来获取详细信息")
     @ApiImplicitParam(paramType = "path", name = "id", value = "ID", required = true, dataType = "String")
     //@RequiresPermissions("tcm0310:view")
     @GetMapping(value = "/{id}")
     public RESTfulResult get(@PathVariable String id){
     TCm0310 tCm0310 = tCm0310Service.getById(id);
     return success(tCm0310);
     }
     */
}
