package com.steerinfo.ems.trmbalancevalue.controller;

import com.steerinfo.auth.utils.JwtUtil;
import com.steerinfo.ems.Utils.BigDecimalUtil;
import com.steerinfo.ems.Utils.DateUtils;
import com.steerinfo.ems.trmactitem.model.TRmActItem;
import com.steerinfo.ems.trmactitem.service.ITRmActItemService;
import com.steerinfo.ems.trmactvalue.model.TRmActValue;
import com.steerinfo.ems.trmworkprocproductvalue.controller.TRmWorkprocProductValueController;
import com.steerinfo.ems.trmworkprocproductvalue.service.ITRmWorkprocProductValueService;
import com.steerinfo.framework.controller.BaseRESTfulController;
import com.steerinfo.framework.controller.RESTfulResult;
import com.steerinfo.framework.service.pagehelper.PageList;
import com.steerinfo.ems.trmbalancevalue.model.TRmBalanceValue;
import com.steerinfo.ems.trmbalancevalue.service.ITRmBalanceValueService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
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.math.BigDecimal;
import java.util.*;

/**
 * TRmBalanceValue RESTful接口：
 * @author generator
 * @version 1.0-SNAPSHORT 2019-10-17 04:39
 * 类描述
 * 修订历史：
 * 日期：2019-10-17
 * 作者：generator
 * 参考：
 * 描述：TRmBalanceValue RESTful接口
 * @see null
 * @Copyright 湖南视拓信息技术股份有限公司. All rights reserved.
 */
@RestController
@RequestMapping("/${api.version}/trmbalancevalues")
public class TRmBalanceValueController extends BaseRESTfulController {
    private static final Logger logger = LoggerFactory.getLogger(TRmWorkprocProductValueController.class);
    @Autowired
    ITRmBalanceValueService tRmBalanceValueService;
    @Autowired
    private ITRmWorkprocProductValueService tRmWorkprocProductValueService;
    @Autowired
    ITRmActItemService tRmActItemService;

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

    @ApiOperation(value="获取详细信息", notes="根据url的id来获取详细信息")
    @ApiImplicitParam(paramType = "path", name = "id", value = "ID", required = true, dataType = "String")
    //@RequiresPermissions("trmbalancevalue:view")
    @PostMapping(value = "/info", produces  = "application/json;charset=UTF-8")
    public RESTfulResult get(@RequestBody TRmBalanceValue 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);
        TRmBalanceValue tRmBalanceValue = tRmBalanceValueService.getById(m);
        return success(tRmBalanceValue);
    }

    @ApiOperation(value="更新详细信息", notes="根据主键(itemid, clock, timegranid)来指定更新对象，并根据传过来的tRmBalanceValue信息来更新详细信息")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "tRmBalanceValue", value = "详细实体tRmBalanceValue", required = true, dataType = "TRmBalanceValue")
    })
    //@RequiresPermissions("trmbalancevalue:update")
    @PutMapping(value = "/updateForUKey/", produces  = "application/json;charset=UTF-8")
    public RESTfulResult update(@RequestBody TRmBalanceValue model){
    	if (model == null) {
    		return failed(null, "请传入主键参数");
    	}
    	if (model.getItemid()== null || model.getItemid().isEmpty()) {
    		return failed(null, "请传入主键参数itemid");
    	}
    	if (model.getClock() == null || model.getClock().isEmpty()) {
    		return failed(null, "请传入主键参数clock");
    	}
    	if (model.getTimegranid() == null || model.getTimegranid().isEmpty()) {
    		return failed(null, "请传入主键参数timegranid");
    	}
        TRmBalanceValue tRmBalanceValue = tRmBalanceValueService.updateForUKey(model);
        return success(tRmBalanceValue);
    }

    @ApiOperation(value="删除", notes="根据url的id来指定删除对象")
    @ApiImplicitParam(paramType = "path", name = "id", value = "ID", required = true, dataType = "String")
    //@RequiresPermissions("trmbalancevalue:delete")
    @DeleteMapping(value = "/delete", produces  = "application/json;charset=UTF-8")
    public RESTfulResult delete(@RequestBody TRmBalanceValue 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);
        tRmBalanceValueService.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 = "/getBalanceitemForPage")
    public RESTfulResult getBalanceitemForPage(@RequestParam HashMap parmas,Integer pageNum, Integer pageSize){
    	PageList<Map> list = tRmBalanceValueService.getBalanceitemForPage(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("/getBalanceitemList")
    public RESTfulResult getBalanceitemList(@RequestParam HashMap parmas){
        List balanceitemList = tRmBalanceValueService.getBalanceitemList(parmas);
        return  success(balanceitemList);
    }

    @ApiOperation(value="批量更新详细信息", notes="根据传过来的usageData数组信息来更新详细信息")
    @ApiImplicitParam(name = "trmbalancevalue", value = "详细实体trmbalancevalue", required = true, dataType = "trmbalancevalue")
    @PutMapping(value = "/batchUpdate", produces  = "application/json;charset=UTF-8")
    public RESTfulResult batchupdate(@RequestBody TRmBalanceValue[] model){
        int failnum = 0;
        // ArrayList<String> failmsgs = new ArrayList<String>();
        String userId = JwtUtil.getUseridByToken();
        for(int i = 0;i < model.length;i++){
        	TRmActItem ta = tRmActItemService.getById(model[i].getItemid());
            if(ta == null){
                return  failed(null,"项目不存在");  
            }
            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());
            TRmBalanceValue t = tRmBalanceValueService.getById(m);
            if (t == null) {
                failnum++;
                logger.error("主键（id：" + model[i].getItemid() + "时间粒度:" + model[i].getTimegranid() + "时间:" + model[i].getClock() + "）修改对象不存在");
                continue;
            }
            if (model[i].getApportvalue() == null) {
                failnum++;
                logger.error("主键（id：" + model[i].getItemid() + "时间粒度:" + model[i].getTimegranid() + "时间:" + model[i].getClock() + "）数据请传入最终值");
                continue;
            }
            if (model[i].getActualvalue() == null) {
                failnum++;
                logger.error("主键（id：" + model[i].getItemid() + "时间粒度:" + model[i].getTimegranid() + "时间:" + model[i].getClock() + "）数据请传入计算值");
                continue;
            }
            if (model[i].getCorrectvalue() == null) {
                failnum++;
                logger.error("主键（id：" + model[i].getItemid() + "时间粒度:" + model[i].getTimegranid() + "时间:" + model[i].getClock() + "）数据请传入修正值");
                continue;
            }
            if (model[i].getActualvalue().compareTo(t.getActualvalue()) != 0) {
                failnum++;
                logger.error("主键（id：" + model[i].getItemid() + "时间粒度:" + model[i].getTimegranid() + "时间:" + model[i].getClock() + "）计算值不能修改");
                continue;
            }
            if (model[i].getActualvalue().add(model[i].getCorrectvalue()).compareTo(model[i].getApportvalue()) != 0) {
                failnum++;
                logger.error("主键（id：" + model[i].getItemid() + "时间粒度:" + model[i].getTimegranid() + "时间:" + model[i].getClock() + "）数据数值错误，最终值 = 计算值 + 修正值");
                continue;
            }
            try{
                logger.info("修改前数据是" + t.toString());
                t.setUserid(userId);
                t.setUptime(DateUtils.dateStr(new Date(),"yyyy-MM-dd HH:mm:ss"));
                t.setApportvalue(model[i].getApportvalue());
                t.setCorrectvalue(model[i].getCorrectvalue());
                Map<String, BigDecimal> dh = tRmWorkprocProductValueService.getOutPut(ta.getWorkprocid(), model[i].getClock(), model[i].getTimegranid(), "R");
                //实绩产量
                Double  sjcl  = dh.get("SJCL").doubleValue();
                //单耗值
	            t.setUcvalue(BigDecimalUtil.divide(t.getApportvalue().doubleValue(), sjcl, ta.getDigits()==null?2:ta.getDigits().intValue()));
                tRmBalanceValueService.modify(t);
            } catch (Exception e){
                failnum++;
                //failmsgs.add(m.toString());
                logger.error("T_RM_Balance_VALUE表的数据修改出现错误,错误原因是" + e + ",id是" + m.toString());
            }
        }
        if(failnum > 0){
            logger.info("本次共修改" + model.length + "条数据,其中成功" + (model.length - failnum) + "条,失败" + failnum + "条");
            return success("51","本次共修改" + model.length + "条数据,其中成功" + (model.length - failnum) + "条,失败" + failnum + "条");
        }
        return success();
    }
    
    @ApiOperation(value="批量重新计算", notes="根据url的id来指定更新对象，并根据传过来的TRmActValue信息来更新详细信息")
    @ApiImplicitParam(name = "TRmBalanceValue", value = "详细实体TRmBalanceValue", required = true, dataType = "TRmBalanceValue")
    @PutMapping(value = "/batchCompute", produces  = "application/json;charset=UTF-8")
    public RESTfulResult batchCompute(@RequestBody TRmBalanceValue[] model){
    	if(model.length<1){
    		return failed(null, "请勾选数据");
    	}
    	for (int i = 0; i< model.length; i++) {
    		TRmBalanceValue tv = model[i];
    		tRmBalanceValueService.restatData(tv.getItemid(), tv.getClock(), tv.getTimegranid());
    	}
    	return success();
    }
    
    @GetMapping("/getitem")
    public RESTfulResult getitem(@RequestParam HashMap<String,Object> parmas) {
    	List<Map<String, Object>> item = tRmBalanceValueService.getItem(parmas);
    	return success(item);
    }
}
