package com.steerinfo.ems.usagedata.controller;

import com.steerinfo.framework.controller.BaseRESTfulController;
import com.steerinfo.framework.controller.RESTfulResult;
import com.steerinfo.framework.service.pagehelper.PageList;
import com.steerinfo.auth.utils.JwtUtil;
import com.steerinfo.ems.ifemsmesactitem.service.IIfEmsMesActitemService;
import com.steerinfo.ems.trmactvalue.model.TRmActValue;
import com.steerinfo.ems.usagedata.model.UsageData;
import com.steerinfo.ems.usagedata.service.IUsageDataService;
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.io.IOException;
import java.util.*;

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

    private static final Logger LOGGER = LoggerFactory.getLogger(UsageDataController.class);
    @Autowired
    IUsageDataService usageDataService;
    @Autowired
    IIfEmsMesActitemService ifEmsMesActitemService;

   @ApiOperation(value="获取列表", notes="分页查询")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "pageNum", value = "查询页数", required = false, dataType = "Integer"),
        @ApiImplicitParam(name = "pageSize", value = "每页记录数", required = false, dataType = "Integer")
    })
    //@RequiresPermissions("usagedata:view")
    @GetMapping(value = "/")
    public RESTfulResult list(@RequestParam HashMap parmas,Integer pageNum, Integer pageSize){
        PageList<UsageData> list = usageDataService.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("usagedata:view")
    @GetMapping(value = "/like/")
    public RESTfulResult listLike(@RequestParam HashMap parmas,Integer pageNum, Integer pageSize){
        PageList<UsageData> list = usageDataService.queryLikeForPage(parmas, pageNum, pageSize);
        return success(list);
    }

    @ApiOperation(value="创建", notes="根据UsageData对象创建")
    @ApiImplicitParam(name = "usageData", value = "详细实体usageData", required = true, dataType = "UsageData")
    //@RequiresPermissions("usagedata:create")
    @PostMapping(value = "/")
    public RESTfulResult add(@RequestBody UsageData model){
        HashMap<String, Object> m = new HashMap<String, Object>();
        m.put("dataCode", model.getDataCode());
        m.put("dt", model.getDt());
        if(!usageDataService.selectDataCodeAndDt(m).isEmpty()){
            return failed(null, model.getDt() + "的" + model.getDataName() + "已存在，不能新增");
        }
        else{
            UsageData usageData = usageDataService.add(model);
            return success(usageData);
        }
    }

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

    @ApiOperation(value="更新详细信息", notes="根据url的id来指定更新对象，并根据传过来的usageData信息来更新详细信息")
    @ApiImplicitParams({
        @ApiImplicitParam(paramType = "path", name = "id", value = "ID", required = true, dataType = "String"),
        @ApiImplicitParam(name = "usageData", value = "详细实体usageData", required = true, dataType = "UsageData")
    })
    //@RequiresPermissions("usagedata:update")
    @PutMapping(value = "/{id}", produces  = "application/json;charset=UTF-8")
    public RESTfulResult update(@PathVariable String id, @RequestBody UsageData model){
        model.setId(id);
        LOGGER.info("USAGE_DATA表的数据发生修改(操作人ID：" + JwtUtil.getUseridByToken() + "):");
        LOGGER.info("修改前数据是" + usageDataService.getById(model.getId()).toString());
        model.setUpman(JwtUtil.getUseridByToken());
        UsageData usageData = usageDataService.modify(model);
        LOGGER.info("修改后数据是" + usageData.toString());
        return success(usageData);
    }

    @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 UsageData[] 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("USAGE_DATA表的数据发生修改(操作人ID：" + userId + "):");
                LOGGER.info("修改前数据是" + usageDataService.getById(model[i].getId()).toString());
                model[i].setUpman(userId);
                UsageData usageData = usageDataService.modify(model[i]);
                LOGGER.info("修改后数据是" + usageData.toString());
            }
            catch(Exception e){
                failnum++;
                failmsgs.add(model[i].getId());
                LOGGER.error("USAGE_DATA表的数据修改出现错误,错误原因是" + e + ",id是" + model[i].getId());
            }
        }
        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的id来指定删除对象")
    @ApiImplicitParam(paramType = "path", name = "id", value = "ID", required = true, dataType = "String")
    //@RequiresPermissions("usagedata:delete")
    @DeleteMapping(value = "/{id}")
    public RESTfulResult delete(@PathVariable String id){
        LOGGER.info("USAGE_DATA表的数据发生了删除(操作人ID：" + JwtUtil.getUseridByToken() + "):");
        LOGGER.info("删除的数据是" + usageDataService.getById(id).toString());
        usageDataService.delete(id);
        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 UsageData[] 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("USAGE_DATA表的数据发生了删除(操作人ID：" + userId + "):");
                LOGGER.info("删除的数据是" + usageDataService.getById(model[i].getId()).toString());
                usageDataService.delete(model[i].getId());
            }
            catch(Exception e){
                failnum++;
                failmsgs.add(model[i].getId());
                LOGGER.error("USAGE_DATA表的数据修改出现错误,错误原因是" + e + ",id是" + model[i].getId());
            }
        }
        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="")
    @GetMapping(value = "/getAutoSum")
    public RESTfulResult getAutoSum(String clock){
        String s = usageDataService.getAutoSum(clock);
        return success(s);
    }
    
    @ApiOperation(value="修改自动上传状态", notes="根据状态来获取数据")
    @PostMapping(value = "/setuploadstate/")
    public RESTfulResult setuploadstate(@RequestParam String uploadstate){
        Map<String, Object> params = new HashMap<>();
        params.put("paramkey", "ems_usage_auto_upload");
        params.put("paramvalue", uploadstate);
        if(ifEmsMesActitemService.updateParam(params) == 0){
            params.put("keyconmment", "EMS能源上报_晋泰信和，是否自动上传，0手动，1自动");
            ifEmsMesActitemService.insertParam(params);
        }
        return success();
    }

    @ApiOperation(value="获取自动上传状态", notes="获取自动上传状态")
    @GetMapping(value = "/getuploadstate/")
    public RESTfulResult getuploadstate(){
        Map<String, Object> params = new HashMap<>();
        params.put("paramkey", "ems_usage_auto_upload");
        List<Map<String, Object>> list = ifEmsMesActitemService.selectParam(params);
        if(list.size() == 0){
            params.put("paramvalue", "0");
            params.put("keyconmment", "EMS能源上报_晋泰信和，是否自动上传，0手动，1自动");
            ifEmsMesActitemService.insertParam(params);
            return success("0");
        }
        else {
            return success(list.get(0).get("PARAM_VALUE").toString());
        }
    }
    
    /**
     * 上传数据，改写状态为1：已传输
     * 
     * @param model 能源采集消耗
     * @return
     * @throws IOException
     */
    @PostMapping(value = "/updatedata/")
    public RESTfulResult post(@RequestBody String[] ids) throws IOException{
    	List<String> errorid = new ArrayList<String>();
    	String userId = JwtUtil.getUseridByToken();
    	for (int i = 0;i <ids.length;i++) {
    		UsageData usageData = usageDataService.getById(ids[i]);
    		usageData.setOperatorMan(userId);
    		usageData.setOperatorDate(new Date());
            int r = usageDataService.updateState(usageData);
            if(r<1){
            	errorid.add(ids[i]);
            }
        }
    	String msg = "本次共上传" + ids.length + "条数据，成功" + (ids.length - errorid.size()) + "条，失败" + errorid.size() + "条";
    	if(errorid.size()>0){
    		msg = msg + "，失败id：" + errorid.toString();
    	}
		return success(msg);
    }
    
    @ApiOperation(value="批量重新计算", notes="根据url的id来指定更新对象，并根据传过来的UsageData信息来更新详细信息")
    @ApiImplicitParam(name = "UsageData", value = "详细实体UsageData", required = true, dataType = "UsageData")
    //@RequiresPermissions("trmcalpointvalue:update")
    @PutMapping(value = "/batchCompute", produces  = "application/json;charset=UTF-8")
    public RESTfulResult batchCompute(@RequestBody UsageData[] model){
    	if(model.length<1){
    		return failed(null, "请选择数据");
    	}
    	for (int i = 0; i< model.length; i++) {
    		UsageData tv = model[i];
    		usageDataService.restatData(tv.getDt(), tv.getDataCode());
    	}
    	return success();
    }

}
