package com.steerinfo.ems.trmplanvalue.controller;

import com.steerinfo.auth.utils.JwtUtil;
import com.steerinfo.ems.Utils.DateUtils;
import com.steerinfo.ems.formula.service.IFormulaService;
import com.steerinfo.ems.trmactitem.mapper.TRmActItemMapper;
import com.steerinfo.ems.trmactitem.model.TRmActItem;
import com.steerinfo.framework.controller.BaseRESTfulController;
import com.steerinfo.framework.controller.RESTfulResult;
import com.steerinfo.framework.service.pagehelper.PageList;
import com.steerinfo.ems.trmplanvalue.model.TRmPlanValue;
import com.steerinfo.ems.trmplanvalue.service.ITRmPlanValueService;
import com.steerinfo.task.SpringCronTask;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

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

    private static final Logger logger = LoggerFactory.getLogger(SpringCronTask.class);
    @Autowired
    ITRmPlanValueService tRmPlanValueService;
    @Autowired
    TRmActItemMapper tRmActItemMapper;
    @Autowired
    IFormulaService formulaService;

    @ApiOperation(value="获取列表", notes="分页查询")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "pageNum", value = "查询页数", required = false, dataType = "Integer"),
        @ApiImplicitParam(name = "pageSize", value = "每页记录数", required = false, dataType = "Integer")
    })
    //@RequiresPermissions("trmplanvalue:view")
    @GetMapping(value = "/")
    public RESTfulResult list(@RequestParam HashMap parmas,Integer pageNum, Integer pageSize){
        PageList<TRmPlanValue> list = tRmPlanValueService.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("trmplanvalue:view")
    @GetMapping(value = "/like/")
    public RESTfulResult listLike(@RequestParam HashMap parmas,Integer pageNum, Integer pageSize){
        PageList<TRmPlanValue> list = tRmPlanValueService.queryLikeForPage(parmas, pageNum, pageSize);
        return success(list);
    }
    
    @ApiOperation(value="创建", notes="根据TRmPlanValue对象创建")
    @ApiImplicitParam(name = "tRmPlanValue", value = "详细实体tRmPlanValue", required = true, dataType = "TRmPlanValue")
    //@RequiresPermissions("trmplanvalue:create")
    @PostMapping(value = "/")
    public RESTfulResult add(@ModelAttribute TRmPlanValue model){
        TRmPlanValue tRmPlanValue = tRmPlanValueService.add(model);
        return success(tRmPlanValue);
    }

    @ApiOperation(value="获取详细信息", notes="根据url的id来获取详细信息")
    @ApiImplicitParam(paramType = "path", name = "id", value = "ID", required = true, dataType = "String")
    //@RequiresPermissions("trmplanvalue:view")
    @GetMapping(value = "/{id}")
    public RESTfulResult get(@PathVariable TRmPlanValue model){
        if(model.getClock() == null || model.getClock().isEmpty()){
            return failed(null, "请传入时间");
        }
        if(model.getTimegranid() == null || model.getTimegranid().isEmpty()){
            return failed(null, "请传入时间粒度");
        }
        if(model.getItemid() == null || model.getItemid().isEmpty()){
            return failed(null, "请传入项目编号");
        }
        HashMap<String, Object> m = new HashMap<String, Object>();
        m.put("clock", model.getClock());
        m.put("timegranid", model.getTimegranid());
        m.put("itemid", model.getItemid());
        model.setId(m);
        TRmPlanValue tRmPlanValue = tRmPlanValueService.getById(m);
        return success(tRmPlanValue);
    }

    @ApiOperation(value="更新详细信息", notes="根据url的id来指定更新对象，并根据传过来的tRmPlanValue信息来更新详细信息")
    @ApiImplicitParams({
        @ApiImplicitParam(paramType = "path", name = "id", value = "ID", required = true, dataType = "String"),
        @ApiImplicitParam(name = "tRmPlanValue", value = "详细实体tRmPlanValue", required = true, dataType = "TRmPlanValue")
    })
    //@RequiresPermissions("trmplanvalue:update")
    @PutMapping(value = "/{id}", produces  = "application/json;charset=UTF-8")
    public RESTfulResult update(@PathVariable String id, @RequestBody TRmPlanValue model){
        if(model.getClock() == null || model.getClock().isEmpty()){
            return failed(null, "请传入时间");
        }
        if(model.getTimegranid() == null || model.getTimegranid().isEmpty()){
            return failed(null, "请传入时间粒度");
        }
        if(model.getItemid() == null || model.getItemid().isEmpty()){
            return failed(null, "请传入项目编号");
        }
        HashMap<String, Object> m = new HashMap<String, Object>();
        m.put("clock", model.getClock());
        m.put("timegranid", model.getTimegranid());
        m.put("itemid", model.getItemid());
        model.setId(m);
        TRmPlanValue tRmPlanValue = tRmPlanValueService.modify(model);
        return success(tRmPlanValue);
    }

    @ApiOperation(value="删除", notes="根据url的id来指定删除对象")
    @ApiImplicitParam(paramType = "path", name = "id", value = "ID", required = true, dataType = "String")
    //@RequiresPermissions("trmplanvalue:delete")
    @DeleteMapping(value = "/{id}")
    public RESTfulResult delete(@RequestBody TRmPlanValue model){
        if(model.getClock() == null || model.getClock().isEmpty()){
            return failed(null, "请传入时间");
        }
        if(model.getTimegranid() == null || model.getTimegranid().isEmpty()){
            return failed(null, "请传入时间粒度");
        }
        if(model.getItemid() == null || model.getItemid().isEmpty()){
            return failed(null, "请传入项目编号");
        }
        HashMap<String, Object> m = new HashMap<String, Object>();
        m.put("clock", model.getClock());
        m.put("timegranid", model.getTimegranid());
        m.put("itemid", model.getItemid());
        model.setId(m);
        tRmPlanValueService.delete(m);
        return success();
    }
    
    @ApiOperation(value="获得供需计划对比分析数据", notes="能源综合分析-供需计划分析-供需计划对比分析页面，分页查询")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "pageNum", value = "查询页数", required = false, dataType = "Integer"),
        @ApiImplicitParam(name = "pageSize", value = "每页记录数", required = false, dataType = "Integer")
    })
    @GetMapping(value = "/getDate621ForPage")
    public RESTfulResult getDate621ForPage(@RequestParam HashMap<String, Object> parmas,Integer pageNum, Integer pageSize){
    	if(parmas.get("workprocid")!=null && !parmas.get("workprocid").toString().isEmpty()){
			String workprocid = parmas.get("workprocid").toString();
			if(!workprocid.startsWith("'")){
				workprocid = "'" + workprocid.replaceAll(",", "','").replaceAll("，", "','") + "'";
			}
			parmas.put("workprocid", workprocid);
		}
    	PageList<Map<String, Object>> list = tRmPlanValueService.getDate621ForPage(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")
    })
    @GetMapping(value = "/getDate622ForPage")
    public RESTfulResult getDate622ForPage(@RequestParam HashMap<String, Object> parmas,Integer pageNum, Integer pageSize){
    	if(parmas.get("workprocid")!=null && !parmas.get("workprocid").toString().isEmpty()){
			String workprocid = parmas.get("workprocid").toString();
			if(!workprocid.startsWith("'")){
				workprocid = "'" + workprocid.replaceAll(",", "','").replaceAll("，", "','") + "'";
			}
			parmas.put("workprocid", workprocid);
		}
    	PageList<Map<String, Object>> list = tRmPlanValueService.getDate622ForPage(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"),
        @ApiImplicitParam(name = "pageNum2", value = "查询页数2", required = false, dataType = "Integer"),
        @ApiImplicitParam(name = "pageSize2", value = "每页记录数2", required = false, dataType = "Integer")
    })
    @GetMapping(value = "/getDate623ForPage")
    public RESTfulResult getDate623ForPage(@RequestParam HashMap<String, Object> parmas,Integer pageNum, Integer pageSize,Integer pageNum2, Integer pageSize2){
    	if(parmas.get("workprocid")!=null && !parmas.get("workprocid").toString().isEmpty()){
			String workprocid = parmas.get("workprocid").toString();
			if(!workprocid.startsWith("'")){
				workprocid = "'" + workprocid.replaceAll(",", "','").replaceAll("，", "','") + "'";
			}
			parmas.put("workprocid", workprocid);
		}
    	List<Map<String, Object>> list = tRmPlanValueService.getDate6231ForPage(parmas, pageNum, pageSize);
    	List<Map<String, Object>> list2 = tRmPlanValueService.getDate6232ForPage(parmas, pageNum2, pageSize2);
    	Map<String, Object> m = new HashMap<String, Object>();
    	m.put("result1", list);
    	m.put("result2", list2);
        return success(m);
    }

    @ApiModelProperty(value = "批量更新实体信息",notes = "根据url的id来指定更新对象,并根据传过来的tRmPlanValue集合来更新详细信息")
    @ApiImplicitParam(name = "List<tRmPlanValue>",value = "详细实体tRmPlanValue集合",required = true,dataType = "tRmPlanValue")
    @PutMapping(value = "/batchUpdate",produces ="application/json;charset=UTF-8" )
    public RESTfulResult batchupdate(@RequestBody TRmPlanValue[] model){
        int failnum = 0;
        ArrayList<String> failmsgs = new ArrayList<String>();
        String userId = JwtUtil.getUseridByToken();
        for(int i = 0;i < model.length;i++){
            HashMap<String, Object> m = new HashMap<String, Object>();
            m.put("clock", model[i].getClock());
            m.put("timegranid", model[i].getTimegranid());
            m.put("itemid", model[i].getItemid());
            try{
                logger.info("T_RM_Plan_VALUE表的数据发生修改(操作人ID：" + userId + "):");
                logger.info("修改前数据是" + tRmPlanValueService.getById(m).toString());
                model[i].setUserid(userId);
                model[i].setUptime(DateUtils.dateStr(new Date(),"yyyy-MM-dd HH:mm:ss"));
                TRmPlanValue usageData = tRmPlanValueService.updateForUKey(model[i]);
                logger.info("修改后数据是" + usageData.toString());
            }
            catch (Exception e){
                failnum++;
                failmsgs.add(m.toString());
                logger.error("T_RM_Plan_VALUE表的数据修改出现错误,错误原因是" + e + ",id是" + m.toString());
            }
        }
        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来指定更新对象，并根据传过来的TRmActValue信息来更新详细信息")
    @ApiImplicitParam(name = "TRmActValue", value = "详细实体TRmActValue", required = true, dataType = "TRmActValue")
    //@RequiresPermissions("trmcalpointvalue:update")
    @PutMapping(value = "/batchCompute", produces  = "application/json;charset=UTF-8")
    public RESTfulResult batchCompute(@RequestBody TRmPlanValue[] model){
    	if(model.length<1){
    		return failed(null, "请勾选数据");
    	}
    	for (int i = 0; i< model.length; i++) {
    		TRmPlanValue tv = model[i];
    		tRmPlanValueService.restatData(tv.getItemid(), tv.getClock(), tv.getTimegranid());
    	}
    	return success();
    }
    
    @ApiOperation(value="重新计算项目数据")
    @GetMapping(value = "/reData")
    public RESTfulResult reData(@RequestParam HashMap<String, Object> parmas, String clock, String timegranid){
        if (clock==null || clock.isEmpty()) {
            return failed(null, "请传入时间");
        }
        if (timegranid==null || timegranid.isEmpty()) {
            return failed(null, "请传入时间粒度");
        }
        if(parmas.get("workprocid") != null && !parmas.get("workprocid").toString().isEmpty()){
            String workprocid = parmas.get("workprocid").toString();
            if(!workprocid.startsWith("'")){
                workprocid = "'" + workprocid.replaceAll(",", "','").replaceAll("，", "','") + "'";
            }
            parmas.put("workprocid", workprocid);
        }
        if(parmas.get("energyid") != null && !parmas.get("energyid").toString().isEmpty()){
            String energyid = parmas.get("energyid").toString();
            if(!energyid.startsWith("'")){
                energyid = "'" + energyid.replaceAll(",", "','").replaceAll("，", "','") + "'";
            }
            parmas.put("energyid", energyid);
        }
        if(parmas.get("propertyid") != null && !parmas.get("propertyid").toString().isEmpty()){
            String propertyid = parmas.get("propertyid").toString();
            if(!propertyid.startsWith("'")){
                propertyid = "'" + propertyid.replaceAll(",", "','").replaceAll("，", "','") + "'";
            }
            parmas.put("propertyid", propertyid);
        }
        if(parmas.containsKey("itemid") && parmas.get("itemid") != null && !"".equals(parmas.get("itemid").toString())){
            String itemid = parmas.get("itemid").toString();
            if(!itemid.startsWith("'")){
            	itemid = "'" + itemid.replaceAll(",", "','").replaceAll("，", "','") + "'";
            }
            parmas.put("itemid", itemid);
        }
        String res = "";
        parmas.put("itemtype", "P");
        parmas.put("useflag", "1");
        // 查询需要统计的项目信息
        List<TRmActItem> l = tRmActItemMapper.selectActr(parmas);
        int size = l.size();
        for(int i = 0; i<l.size(); i++){
            if(res.isEmpty()){
                res = formulaService.reItemVal(l.get(i).getItemid(),clock,timegranid,clock);
            }else{
                formulaService.reItemVal(l.get(i).getItemid(),clock,timegranid,clock);
            }
            logger.info("剩下要处理的项目数：" + (size-1-i) + "(" + size + ")");
        }
        if(!res.isEmpty()){
            return success(null, res);
        }
        return success();
    }
}
