package com.steerinfo.ems.tpmcase.controller;

import com.steerinfo.auth.utils.JwtUtil;
import com.steerinfo.ems.Utils.DateUtils;
import com.steerinfo.ems.tpmcase.model.TPmCase;
import com.steerinfo.ems.tpmcase.service.TPmCaseService;
import com.steerinfo.ems.trmenergytype.model.TRmEnergyType;
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.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Set;

/**
 * @author 李日量
 * @Date 2019/10/10 10:10
 * @Copyright 湖南视拓信息技术股份有限公司
 */
@RestController
@RequestMapping("/${api.version}/tpmcase")

public class TpmCaseController extends BaseRESTfulController {

    private static final Logger logger = LoggerFactory.getLogger(TpmCaseController.class);
    @Autowired
    private TPmCaseService tPmCaseService;


    @ApiOperation(value = "创建",notes = "根据TPmCase对象进行创建")
    @ApiImplicitParam(name = "tPmCase",value = "详细实体TPmCase", required = true, dataType = "TPmCase")
    @PostMapping(value = "/")
    public RESTfulResult add(@RequestBody TPmCase model) {
        System.out.println(model);
        TPmCase tPmCase = tPmCaseService.add(model);
        return success(tPmCase);
    }

    @ApiOperation(value = "删除",notes = "根据caseId来删除")
    @ApiImplicitParam(name = "caseId",value = "caseId",required = true,dataType = "caseId")
    @DeleteMapping(value = "/{caseId}")
    public RESTfulResult delete(@PathVariable String caseId){
        if(StringUtils.indexOf(caseId,",") == -1){
            tPmCaseService.delete(caseId);
        }
        else {
            tPmCaseService.delete(Arrays.asList(caseId.split(",")));
        }
        return success();
    }

    @ApiOperation(value="批量删除", notes="根据url的id来指定删除对象")
    @ApiImplicitParam(paramType = "path", name = "id", value = "ID", required = true, dataType = "String")
    @DeleteMapping(value = "/batchDel")
    public RESTfulResult batchDel(@RequestBody TPmCase[] model){
        int failnum = 0;
        ArrayList<String> failmsgs = new ArrayList<String>();
        String userId = JwtUtil.getUseridByToken();
        for(int i = 0;i < model.length;i++){
            try {
                logger.info("T_PM_CASE表的数据发生了删除(操作人ID：" + userId + "):");
                logger.info("删除的数据是" + tPmCaseService.getById(model[i].getCaseId()).toString());
                tPmCaseService.delete(model[i].getCaseId());
            }
            catch(Exception e){
                failnum++;
                failmsgs.add(model[i].getCaseId());
                logger.error("T_PM_CASE表的数据修改出现错误,错误原因是" + e + ",id是" + model[i].getCaseId());
            }
        }
        if(failnum > 0){
            logger.info("本次共准备删除" + model.length + "条数据,其中成功" + (model.length - failnum) + "条,失败" + failnum + "条");
            return success(failmsgs, "51","本次共准备删除" + model.length + "条数据,其中成功" + (model.length - failnum) + "条,失败" + failnum + "条,失败的数据id:" + failmsgs.toString());
        }
        return success();
    }

    @ApiOperation(value="更新详细信息", notes="根据url的caseId来指定更新对象")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "path", name = "caseId", value = "caseId", required = true, dataType = "String"),
            @ApiImplicitParam(name = "tPmCase", value = "详细实体TPmCase", required = true, dataType = "TPmCase")
       })
    @PutMapping(value = "/{caseId}",produces  = "application/json;charset=UTF-8")
    public RESTfulResult update(@PathVariable String caseId,
                                @RequestBody TPmCase model){
        model.setCaseId(caseId);
        logger.info("T_PM_CASE表的数据发生修改(操作人ID：" + JwtUtil.getUseridByToken() + "):");
        logger.info("修改前数据是" + tPmCaseService.getById(caseId));
        model.setUpman(JwtUtil.getUseridByToken());
        model.setUpdatetime(DateUtils.getCurrentTimetoDate("yyyy-MM-dd HH:mm:ss"));
        TPmCase modify = tPmCaseService.modify(model);
        logger.info("修改后数据是" + modify.toString());
        return  success(modify);
    }

    @ApiOperation(value="批量更新详细信息", notes="根据传过来的usageData数组信息来更新详细信息")
    @ApiImplicitParam(name = "usageData", value = "详细实体usageData", required = true, dataType = "usageData")
    @PutMapping(value = "/batchUpdate", produces  = "application/json;charset=UTF-8")
    public RESTfulResult batchupdate(@RequestBody TPmCase[] model){
        int failnum = 0;
        ArrayList<String> failmsgs = new ArrayList<String>();
        String userId = JwtUtil.getUseridByToken();
        for(int i = 0;i < model.length;i++){
            try {
                logger.info("T_PM_CASE表的数据发生修改(操作人ID：" + userId + "):");
                logger.info("修改前数据是" + tPmCaseService.getById(model[i].getCaseId()).toString());
                model[i].setUpman(userId);
                model[i].setUpdatetime(DateUtils.getCurrentTimetoDate("yyyy-MM-dd HH:mm:ss"));
                TPmCase usageData = tPmCaseService.modify(model[i]);
                logger.info("修改后数据是" + usageData.toString());
            }
            catch(Exception e){
                failnum++;
                failmsgs.add(model[i].getCaseId());
                logger.error("T_PM_CASE表的数据修改出现错误,错误原因是" + e + ",id是" + model[i].getCaseId());
            }
        }
        if(failnum > 0){
            logger.info("本次共修改" + model.length + "条数据,其中成功" + (model.length - failnum) + "条,失败" + failnum + "条");
            return success(failmsgs, "51","本次共修改" + model.length + "条数据,其中成功" + (model.length - failnum) + "条,失败" + failnum + "条,失败的数据id:" + failmsgs.toString());
        }
        return success();
    }

    @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,  @RequestParam("pageNum") Integer pageNum,   @RequestParam("pageSize") Integer pageSize){
        PageList<TRmEnergyType> list = tPmCaseService.queryLikeForPage(parmas,pageNum,pageSize);
        return success(list);
    }


    @ApiOperation(value = "查询CASEIDNAME 和 ICASEID")
    @GetMapping("/getIdAndName")
        public RESTfulResult getIdAndName(){
        Set<TPmCase> idAndName = tPmCaseService.getIdAndName();
        return  success(idAndName);

    }


}
