package com.steerinfo.ems.trmactitem.controller;

import com.steerinfo.auth.utils.JwtUtil;
import com.steerinfo.ems.Utils.DateUtils;
import com.steerinfo.ems.formula.model.Formula;
import com.steerinfo.ems.formula.service.IFormulaService;
import com.steerinfo.ems.trmactitem.mapper.TRmActItemMapper;
import com.steerinfo.framework.controller.BaseRESTfulController;
import com.steerinfo.framework.controller.RESTfulResult;
import com.steerinfo.framework.service.pagehelper.PageList;
import com.steerinfo.ems.trmactitem.model.TRmActItem;
import com.steerinfo.ems.trmactitem.service.ITRmActItemService;
import com.steerinfo.ems.trmactvalue.service.ITRmActValueService;
import com.steerinfo.ems.trmbalancevalue.service.ITRmBalanceValueService;
import com.steerinfo.ems.trmdfvalue.service.ITRmDfValueService;
import com.steerinfo.ems.trmdwvalue.service.ITRmDwValueService;
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.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.*;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

/**
 * TRmActItem RESTful接口：
 * @author generator
 * @version 1.0-SNAPSHORT 2019-10-11 11:41
 * 类描述
 * 修订历史：
 * 日期：2019-10-11
 * 作者：generator
 * 参考：
 * 描述：TRmActItem RESTful接口
 * @see null
 * @Copyright 湖南视拓信息技术股份有限公司. All rights reserved.
 */
@RestController
@RequestMapping("/${api.version}/trmactitems")
public class TRmActItemController extends BaseRESTfulController {
    private static final Logger logger = LoggerFactory.getLogger(SpringCronTask.class);
    @Autowired
    TRmActItemMapper  tRmActItemMapper;

    @Autowired
    ITRmActItemService tRmActItemService;

    @Autowired
    IFormulaService formulaService;
    
    @Autowired
    ITRmActValueService tRmActValueService;
    
    @Autowired
    ITRmBalanceValueService tRmBalanceValueService;
    
    @Autowired
    ITRmPlanValueService tRmPlanValueService;
    
    @Autowired
    ITRmDwValueService tRmDwValueService;
    
    @Autowired
    ITRmDfValueService tRmDfValueService;

    @ApiOperation(value="获取列表", notes="分页查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "查询页数", required = false, dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "每页记录数", required = false, dataType = "Integer")
    })

    //@RequiresPermissions("trmactitem:view")
    @GetMapping(value = "/")
    public RESTfulResult list(@RequestParam HashMap parmas,Integer pageNum, Integer pageSize){
        PageList<TRmActItem> list = tRmActItemService.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("trmactitem:view")
    @GetMapping(value = "/like/")
    public RESTfulResult listLike(@RequestParam HashMap parmas,Integer pageNum, Integer pageSize){
    	if(parmas.containsKey("energyid") && parmas.get("energyid") != null && !"".equals(parmas.get("energyid").toString())){
            String energyid = parmas.get("energyid").toString();
            if(energyid.indexOf(",") == -1){
                parmas.put("energyid", "and t.energyid = '" + energyid + "'");
            } else {
            	energyid = "and t.energyid in ('" + energyid.replaceAll(",", "','") + "')";
                parmas.put("energyid", energyid);
            }
        }
    	
    	if(parmas.containsKey("workprocid") && parmas.get("workprocid") != null && !"".equals(parmas.get("workprocid").toString())){
            String workprocid = parmas.get("workprocid").toString();
            if(workprocid.indexOf(",") == -1){
                parmas.put("workprocid", "and t.workprocid = '" + workprocid + "'");
            } else {
            	workprocid = "and t.workprocid in ('" + workprocid.replaceAll(",", "','") + "')";
                parmas.put("workprocid", workprocid);
            }
        }
    	
    	if(parmas.containsKey("propertyid") && parmas.get("propertyid") != null && !"".equals(parmas.get("propertyid").toString())){
            String propertyid = parmas.get("propertyid").toString();
            if(propertyid.indexOf(",") == -1){
                parmas.put("propertyid", "and t.propertyid = '" + propertyid + "'");
            } else {
            	propertyid = "and t.propertyid in ('" + propertyid.replaceAll(",", "','") + "')";
                parmas.put("propertyid", propertyid);
            }
        }
    	  if(parmas.get("itemid") != null && !parmas.get("itemid").toString().isEmpty()){
              String itemid = parmas.get("itemid").toString();
              if(!itemid.startsWith("'")){
              	itemid = "'" + itemid.replaceAll(",", "','").replaceAll("，", "','") + "'";
              }
              parmas.put("itemid", itemid); 
          }
    	
        PageList<TRmActItem> list = tRmActItemService.queryLikeForPage(parmas, pageNum, pageSize);
        return success(list);
    }


    @ApiOperation(value="创建", notes="根据TRmActItem对象创建")
    @ApiImplicitParam(name = "tRmActItem", value = "详细实体tRmActItem", required = true, dataType = "TRmActItem")
    //@RequiresPermissions("trmactitem:create")
    @PostMapping(value = "/")
    public RESTfulResult add(@RequestBody Map<String,Object> maps){
		// 能介
		Map trmenergy = (Map) maps.get("trmenergy");
		String trmenergyId = (String) trmenergy.get("id");
		String trmenergyName = (String) trmenergy.get("name");
		// 工序
		Map trmworkproc = (Map) maps.get("trmworkproc");
		String trmworkprocId = (String) trmworkproc.get("id");
		String trmworkprocName = (String) trmworkproc.get("name");
		// 能介类型
		Map trmenergyproperty = (Map) maps.get("trmenergyproperty");
		String trmenergypropertyId = (String) trmenergyproperty.get("id");
		String trmenergypropertyName = (String) trmenergyproperty.get("name");
        //单位
        Map trmunit = (Map) maps.get("trmunit");
        String trmunitId = trmunit.get("id")==null?"":trmunit.get("id").toString();
        Integer seqno = maps.get("seqno") == null || maps.get("seqno").toString().isEmpty() ? 10 : Integer.valueOf(maps.get("seqno").toString());
		String itemtype = (String) maps.get("itemtype");
		String itemid = trmworkprocId + trmenergyId + trmenergypropertyId + itemtype;
		String itemtypeName = "";
		if (itemtype.equalsIgnoreCase("R")) {
			itemtypeName = "实绩";
		} else if (itemtype.equalsIgnoreCase("P")) {
			itemtypeName = "计划";
		}
		String itemname = trmworkprocName + trmenergyName + itemtypeName + trmenergypropertyName;
		String itemdesc = maps.get("itemdesc")==null?"":maps.get("itemdesc").toString();
		if (itemdesc.isEmpty()) {
			itemdesc = itemname;
		}
		TRmActItem rmActItem = tRmActItemService.getById(itemid);
		if (rmActItem != null) {
			return failed(null, "已存在该项目");
		}
		// 数值精度
        String digits = maps.get("digits") == null || maps.get("digits").toString().isEmpty() ? "3" :maps.get("digits").toString();
        TRmActItem  tRmActItem = new TRmActItem();
        tRmActItem.setId(itemid);
        tRmActItem.setItemname(itemname);
        tRmActItem.setItemdesc(itemdesc);
        tRmActItem.setItemtype(itemtype);
        tRmActItem.setPropertyid(trmenergypropertyId);
        tRmActItem.setWorkprocid(trmworkprocId);
        tRmActItem.setEnergyid(trmenergyId);
        tRmActItem.setUnitid(trmunitId);
        tRmActItem.setUseflag("1");
        tRmActItem.setSeqno(seqno);
        tRmActItem.setDigits(Short.parseShort(digits));
        tRmActItem.setUserid(JwtUtil.getUseridByToken());
        tRmActItem.setState(maps.get("state")==null?"":maps.get("state").toString());
        tRmActItem.setIsup(maps.get("isup")==null?"0":maps.get("isup").toString());
        tRmActItem.setShowno(maps.get("showno")==null || maps.get("showno").toString().trim().isEmpty() ?null:Integer.valueOf(maps.get("showno").toString()));
        tRmActItem.setAssociateid(maps.get("associateid")==null?"":maps.get("associateid").toString());
        tRmActItem.setClock(DateUtils.dateStr(new Date(), "yyyy-MM-dd HH:mm:ss"));
        tRmActItem.setFid(maps.get("fid")==null?"":maps.get("fid").toString());
        tRmActItem.setBz(maps.get("bz")==null?"":maps.get("bz").toString());
        tRmActItem.setMintimegranid(maps.get("mintimegranid")==null?"MONTH":maps.get("mintimegranid").toString());
        tRmActItemService.add(tRmActItem);
        //增加公式
        Formula formula = new Formula();
        formula.setClock("202001"); // DateUtils.getCurrentTime("yyyyMM")
        formula.setCode(itemid);
        formula.setDescription(itemname);
        formula.setSourcecode("R("+maps.get("tablename")+","+itemid+")");
        formula.setIsavailable("1");
        formula.setRevisetime(DateUtils.getCurrentTime("yyyy-MM-dd HH:mm:ss"));
        formula.setTablename(maps.get("tablename").toString());
        formulaService.add(formula);
        return success(tRmActItem);
    }

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

    @ApiOperation(value="更新详细信息", notes="根据url的id来指定更新对象，并根据传过来的tRmActItem信息来更新详细信息")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "path", name = "id", value = "ID", required = true, dataType = "String"),
            @ApiImplicitParam(name = "tRmActItem", value = "详细实体tRmActItem", required = true, dataType = "TRmActItem")
    })
    //@RequiresPermissions("trmactitem:update")
    @PutMapping(value = "/{id}", produces  = "application/json;charset=UTF-8")
    public RESTfulResult update(@PathVariable String id, @RequestBody TRmActItem model){
        model.setId(id);
        model.setDefaulman(JwtUtil.getUseridByToken());
        model.setModificationtime(DateUtils.dateStr(new Date(), "yyyy-MM-dd HH:mm:ss"));
        Map<String,Object> params =  new HashMap<>();
        params.put("clock", DateUtils.getCurrentTime("yyyyMM"));
        params.put("code", model.getItemid());
        Formula fm = formulaService.getByParams(params);
        List<Formula> associatedFormula = formulaService.getAssociatedFormula(model.getItemid());
        if(model.getUseflag().equalsIgnoreCase("0")) {
            if (associatedFormula.size() > 0) {
                String ids = "";
                for (Formula formula : associatedFormula) {
                    ids += formula.getClock() + "  " + formula.getCode() + ",";
                }
                return failed(500, "该项目公式已经被其他项目关联,无法进行禁用 关联的项目有:" + ids);
            }
        }
        if (model.getUseflag().equalsIgnoreCase("1")){
            String s = formulaService.checkFormula(fm);
            if (!s.equals("")){
                return failed(500,"该项目所对应的公式不合法无法启动    "+"["+s+"]");
            }
        }
        fm.setDescription(model.getItemname());
        fm.setIsavailable(model.getUseflag());
        formulaService.updateFormula(fm);
        TRmActItem tRmActItem = tRmActItemService.modify(model);
        logger.info("用户id为"+ JwtUtil.getUseridByToken()+"进行了修改操作"+DateUtils.dateStr(new Date(),"yyyy-MM-dd HH:mm:ss"));
        return success(tRmActItem);
    }

    @ApiModelProperty(value = "批量更新实体信息",notes = "根据url的id来指定更新对象,并根据传过来的tRmActItem集合来更新详细信息")
    @ApiImplicitParam(name = "List<TRmActItem>",value = "详细实体tRmActItem集合",required = true,dataType = "TRmActItem")
    @PutMapping(value = "/batchUpdate",produces ="application/json;charset=UTF-8" )
    public RESTfulResult batchUpdate(@RequestBody TRmActItem[] model){
        int failnum = 0;
        ArrayList<String> failmsgs = new ArrayList<String>();
        ArrayList<String> warnmsg = new ArrayList<String>();
        String userId = JwtUtil.getUseridByToken();
        for(int i = 0;i < model.length;i++){
            try {
            	TRmActItem old = tRmActItemService.getById(model[i].getId());
                logger.info("T_RM_ACT_ITEM表的数据发生修改(操作人ID：" + userId + "):");
                logger.info("修改前数据是" + old.toString());
                String oldMintimegranid = old.getMintimegranid();
                // 如果修改最小时间粒度，判断公式是否合法（最小时间粒度影响公式计算）
                if(!oldMintimegranid.equalsIgnoreCase(model[i].getMintimegranid())){
                	HashMap<String, Object> parmas = new HashMap<>();
                	parmas.put("code", model[i].getItemid());
                	parmas.put("clock", DateUtils.dateStr(new Date(), "yyyyMM"));
                	// 获取公式
                	Formula fm = formulaService.getFormulaCodeClock(parmas);
                	String res = formulaService.checkFormulaMint(fm, model[i].getMintimegranid());
                	if(!res.isEmpty()){
                		warnmsg.add(model[i].getId() + ":" + res);
                    }
                }
                model[i].setDefaulman(userId);
                model[i].setModificationtime(DateUtils.dateStr(new Date(), "yyyy-MM-dd HH:mm:ss"));
                TRmActItem trmData = tRmActItemService.modify(model[i]);
                if(model[i].getItemdesc()!=null && !model[i].getItemdesc().trim().isEmpty()) {
                	Map<String, Object> pm = new HashMap<>();
                    pm.put("code", model[i].getItemid());
                    pm.put("description", model[i].getItemdesc().trim());
                    formulaService.updateDesBycode(pm);
                }
                logger.info("修改后数据是" + trmData.toString());
            }
            catch(Exception e){
                failnum++;
                failmsgs.add(model[i].getId());
                logger.error("T_RM_ACT_ITEM表的数据修改出现错误,错误原因是" + e + ",id是" + model[i].getId());
            }
        }
        String wmsg = "";
    	if(warnmsg.size()>0){
    		wmsg = "(" + warnmsg.toString() + ")";
    	}
        if(failnum > 0){
            logger.info("本次共修改" + model.length + "条数据,其中成功" + (model.length - failnum) + "条,失败" + failnum + "条");
            return success(failmsgs, "51","本次共修改" + model.length + "条数据,其中成功" + (model.length - failnum) + "条"+wmsg+",失败" + failnum + "条:" + failmsgs.toString());
        }
        if(warnmsg.size()>0){
        	return success(null, wmsg);
    	}else{
    		return success();
    	}
    }

    @ApiOperation(value = "批量删除",notes = "根据url传过来的id集合删除对象")
    @ApiImplicitParam(paramType = "path",name = "id",value = "ID",required = true,dataType = "String")
    @DeleteMapping("/batchDel")
    public RESTfulResult dels(@RequestBody TRmActItem[] 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_RM_ACT_ITEM表的数据发生了删除(操作人ID：" + userId + "):");
                logger.info("删除的数据是" + tRmActItemService.getById(model[i].getId()).toString());
                List<Formula> list = formulaService.getFormulaByCode(model[i].getId());
            	if(list!=null && list.size()>0){
            		String item="";
            		for(Formula fa:list){
            			item += "[" + fa.getClock() +"版本，项目编号"+ fa.getCode() + "],";
            		}
            		item = item.substring(0,item.length()-1);
            		return failed(null, item + " 公式中包含计量点 " + model[i].getId() + "，请先处理");
            	}
            	Map<String, Object> params = new HashMap<String, Object>();
    			params.put("itemid", model[i].getId());
            	if (model[i].getId().endsWith("R")) {
            		if(tRmActValueService.getCount(params) > 0){
            			return failed(null, model[i].getId() + " 已有数据，请先处理");
            		}
            		// tRmActValueService.deleteByParams(params);
            	} else if (model[i].getId().endsWith("B")) {
            		if(tRmBalanceValueService.getCount(params) > 0){
            			return failed(null, model[i].getId() + " 已有数据，请先处理");
            		}
            		// tRmBalanceValueService.deleteByParams(params);
            	} else if (model[i].getId().endsWith("P")) {
            		if(tRmPlanValueService.getCount(params) > 0){
            			return failed(null, model[i].getId() + " 已有数据，请先处理");
            		}
            		// tRmPlanValueService.deleteByParams(params);
            	} else if (model[i].getId().endsWith("W")) {
            		if(tRmDwValueService.getCount(params) > 0){
            			return failed(null, model[i].getId() + " 已有数据，请先处理");
            		}
            		// tRmDwValueService.deleteByParams(params);
            	} else if (model[i].getId().endsWith("F")) {
            		if(tRmDfValueService.getCount(params) > 0){
            			return failed(null, model[i].getId() + " 已有数据，请先处理");
            		}
            	}
                tRmActItemService.delete(model[i].getId());
                formulaService.deleteBycode(model[i].getId());
            }
            catch(Exception e){
                failnum++;
                failmsgs.add(model[i].getId());
                logger.error("T_RM_ACT_ITEM表的数据删除时出现错误,错误原因是" + 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("trmactitem:delete")
    @DeleteMapping(value = "/{id}")
    public RESTfulResult delete(@PathVariable String id){
        if (StringUtils.indexOf(id, ",") == -1) {
            tRmActItemService.delete(id);
        } else {
            tRmActItemService.delete(Arrays.asList(id.split(",")));
        }
        formulaService.deleteBycode(id);
        return success();
    }

    @ApiOperation(value = "查询 ITEMNAME 和 ITEMID")
    @GetMapping("/getIdAndName")
    public RESTfulResult getIdAndName(){
        List<TRmActItem> idAndName = tRmActItemService.getIdAndName("P");
        return success(idAndName);
    }

    @ApiOperation(value="批量新增", notes="根据TRmActItem对象创建")
    @ApiImplicitParam(name = "list<tRmActItem>", value = "详细实体tRmActItem集合", required = true, dataType = "List<tRmActItem>")
    @PostMapping(value = "/batchAdd")
    public RESTfulResult batchAdd(List<TRmActItem> models){
    	for (TRmActItem item : models) {
    		if(item.getItemid().isEmpty()) {
                return failed(null, "itemid不能为空");
    		}
    	}
    	int re = tRmActItemService.batchAdd(models);
    	return success();
    }

    @ApiOperation(value = "查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "查询页数", required = false, dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "每页记录数", required = false, dataType = "Integer")
    })
    @GetMapping("/getActitemDetaltsForPage")
    public RESTfulResult getActitemDetaltsForPage(@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);
        }
        if(parmas.get("energytypeid") != null && !parmas.get("energytypeid").toString().isEmpty()){
            String energytypeid = parmas.get("energytypeid").toString();
            if(!energytypeid.startsWith("'")){
                energytypeid = "'" + energytypeid.replaceAll(",", "','").replaceAll("，", "','") + "'";
            }
            parmas.put("energytypeid", energytypeid);
        }
    	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.get("itemid")!=null && !parmas.get("itemid").toString().isEmpty()) {
    		String itemid = parmas.get("itemid").toString();
    		if(!itemid.startsWith("'")) {
    			itemid="'"+itemid.replaceAll(",", "','").replaceAll(",", ",")+"'";
    		}
    		parmas.put("itemid", itemid);
    	}
    	if(parmas.containsKey("startDate") && parmas.get("startDate") != null && !"".equals(parmas.get("startDate").toString()) &&
        		parmas.containsKey("endDate") && parmas.get("endDate") != null && !"".equals(parmas.get("endDate").toString())){
            String begin = parmas.get("startDate").toString();
            String end = parmas.get("endDate").toString();
            parmas.put("clock", begin);
            parmas.put("clocke", end);
        }
        PageList<Map<String, Object>> actitemDetaltsForPage = tRmActItemService.getActitemDetaltsForPage(parmas, pageNum, pageSize);
        return  success(actitemDetaltsForPage);
    }

    @ApiOperation(value = "查询计划项目维护结果区",notes = "计划项目数据维护页面")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "查询页数", required = false, dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "每页记录数", required = false, dataType = "Integer")
    })
    @GetMapping("/getPlanitemDetalts")
    public RESTfulResult getPlanitemDetalts(@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);
        }
    	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);
        }
        PageList<Map<String, Object>> planitemDetalts = tRmActItemService.getPlanitemDetalts(parmas, pageNum, pageSize);
        return  success(planitemDetalts);
    }
    
    @ApiOperation(value = "查询平衡数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "查询页数", required = false, dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "每页记录数", required = false, dataType = "Integer")
    })
    @GetMapping("/getBalanceData")
    public RESTfulResult getBalanceData(@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);
        }
    	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);
        }
    	if(parmas.containsKey("startDate") && parmas.get("startDate") != null && !"".equals(parmas.get("startDate").toString()) &&
        		parmas.containsKey("endDate") && parmas.get("endDate") != null && !"".equals(parmas.get("endDate").toString())){
            String begin = parmas.get("startDate").toString();
            String end = parmas.get("endDate").toString();
            parmas.put("clock", begin);
            parmas.put("clocke", end);
        }
        PageList<Map<String, Object>> blist = tRmActItemService.getBalanceDataForPage(parmas, pageNum, pageSize);
        return  success(blist);
    }
    
    @ApiOperation(value="重新计算项目数据")
    @GetMapping(value = "/reData")
    public RESTfulResult reData(@RequestParam HashMap<String, Object> parmas, String clock, String clocke, String timegranid, String itemtype){
        if (clock==null || clock.isEmpty()) {
            return failed(null, "请传入起始时间");
        }
        if (clocke==null || clocke.isEmpty()) {
            return failed(null, "请传入结束时间");
        }
        if (timegranid==null || timegranid.isEmpty()) {
            return failed(null, "请传入时间粒度");
        }
        if (itemtype==null || itemtype.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", itemtype);
        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,clocke);
            }else{
                formulaService.reItemVal(l.get(i).getItemid(),clock,timegranid,clocke);
            }
            logger.info("剩下要处理的项目数：" + (size-1-i) + "(" + size + ")");
        }
        if(!res.isEmpty()){
            return success(null, res);
        }
        return success();
    }

    @ApiOperation(value="获取上报项目列表", notes="分页模糊查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "查询页数", required = false, dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "每页记录数", required = false, dataType = "Integer")
    })
    //@RequiresPermissions("trmactitem:view")
    @GetMapping(value = "/likew/")
    public RESTfulResult listLikew(@RequestParam HashMap<String, Object> parmas,Integer pageNum, Integer pageSize){
    	if(parmas.containsKey("energyid") && parmas.get("energyid") != null && !"".equals(parmas.get("energyid").toString())){
            String energyid = parmas.get("energyid").toString();
            if(energyid.indexOf(",") == -1){
                parmas.put("energyid", "and t.energyid = '" + energyid + "'");
            } else {
            	energyid = "and t.energyid in ('" + energyid.replaceAll(",", "','") + "')";
                parmas.put("energyid", energyid);
            }
        }
    	if(parmas.containsKey("workprocid") && parmas.get("workprocid") != null && !"".equals(parmas.get("workprocid").toString())){
            String workprocid = parmas.get("workprocid").toString();
            if(workprocid.indexOf(",") == -1){
                parmas.put("workprocid", "and t.workprocid = '" + workprocid + "'");
            } else {
            	workprocid = "and t.workprocid in ('" + workprocid.replaceAll(",", "','") + "')";
                parmas.put("workprocid", workprocid);
            }
        }
    	if(parmas.containsKey("propertyid") && parmas.get("propertyid") != null && !"".equals(parmas.get("propertyid").toString())){
            String propertyid = parmas.get("propertyid").toString();
            if(propertyid.indexOf(",") == -1){
                parmas.put("propertyid", "and t.propertyid = '" + propertyid + "'");
            } else {
            	propertyid = "and t.propertyid in ('" + propertyid.replaceAll(",", "','") + "')";
                parmas.put("propertyid", propertyid);
            }
        }
    	  if(parmas.get("itemid") != null && !parmas.get("itemid").toString().isEmpty()){
              String itemid = parmas.get("itemid").toString();
              if(!itemid.startsWith("'")){
              	itemid = "'" + itemid.replaceAll(",", "','").replaceAll("，", "','") + "'";
              }
              parmas.put("itemid", itemid); 
          }
    	
        PageList<TRmActItem> list = tRmActItemService.queryLikewForPage(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("trmactitem:view")
    @GetMapping(value = "/likef/")
    public RESTfulResult listLikef(@RequestParam HashMap<String, Object> parmas,Integer pageNum, Integer pageSize){
    	if(parmas.containsKey("energyid") && parmas.get("energyid") != null && !"".equals(parmas.get("energyid").toString())){
            String energyid = parmas.get("energyid").toString();
            if(energyid.indexOf(",") == -1){
                parmas.put("energyid", "and t.energyid = '" + energyid + "'");
            } else {
            	energyid = "and t.energyid in ('" + energyid.replaceAll(",", "','") + "')";
                parmas.put("energyid", energyid);
            }
        }
    	if(parmas.containsKey("workprocid") && parmas.get("workprocid") != null && !"".equals(parmas.get("workprocid").toString())){
            String workprocid = parmas.get("workprocid").toString();
            if(workprocid.indexOf(",") == -1){
                parmas.put("workprocid", "and t.workprocid = '" + workprocid + "'");
            } else {
            	workprocid = "and t.workprocid in ('" + workprocid.replaceAll(",", "','") + "')";
                parmas.put("workprocid", workprocid);
            }
        }
    	if(parmas.containsKey("propertyid") && parmas.get("propertyid") != null && !"".equals(parmas.get("propertyid").toString())){
            String propertyid = parmas.get("propertyid").toString();
            if(propertyid.indexOf(",") == -1){
                parmas.put("propertyid", "and t.propertyid = '" + propertyid + "'");
            } else {
            	propertyid = "and t.propertyid in ('" + propertyid.replaceAll(",", "','") + "')";
                parmas.put("propertyid", propertyid);
            }
        }
    	  if(parmas.get("itemid") != null && !parmas.get("itemid").toString().isEmpty()){
              String itemid = parmas.get("itemid").toString();
              if(!itemid.startsWith("'")){
              	itemid = "'" + itemid.replaceAll(",", "','").replaceAll("，", "','") + "'";
              }
              parmas.put("itemid", itemid); 
          }
    	
        PageList<TRmActItem> list = tRmActItemService.queryLikefForPage(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("trmactitem:view")
    @GetMapping(value = "/listpv/")
    public RESTfulResult listpv(@RequestParam HashMap<String, Object> parmas,String clock, String clocke,Integer pageNum, Integer pageSize){
    	if(!parmas.containsKey("clock") || parmas.get("clock").toString().isEmpty()){
    		return failed(null, "请传入起始时间");
        }
    	if(!parmas.containsKey("clocke") || parmas.get("clocke").toString().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);
		}
    	List<Map<String, Object>> its = tRmActItemService.getProItems();
    	Map<String, Object> mp = new HashMap<String, Object>();
    	String cpid = "";
    	String yid = "";
    	String aid = "";
    	for(Map<String, Object> m:its){
    		String itemid = m.get("ITEMID").toString();
    		mp.put(itemid, m.get("RATE")==null?"":m.get("RATE").toString());
    		if(itemid.substring(5).indexOf("CP")>=0){
    			cpid += "'" + itemid + "',";
    		}else if(itemid.substring(5).indexOf("Y")>=0){
    			yid += "'" + itemid + "',";
    		}else{
    			aid += "'" + itemid + "',";
    		}
    	}
    	if(!cpid.isEmpty()){
    		cpid = cpid.substring(0,cpid.length()-1);
    		parmas.put("cpid", cpid);
    		if(!yid.isEmpty()){
    			parmas.put("yid", yid.substring(0,yid.length()-1));
    		}
    		if(!aid.isEmpty()){
    			parmas.put("aid", aid.substring(0,aid.length()-1));
    		}
    		List<Map<String, Object>> re = tRmActItemService.listpv(parmas);
    		for(Map<String, Object> m:re){
    			String itemid = m.get("ITEMID").toString();
    			String ck = m.get("CLOCK").toString();
    			if(mp.containsKey(itemid) && !mp.get(itemid).toString().isEmpty()){
    				String js = m.get("APPORTVALUE").toString() + mp.get(itemid).toString();
    				ScriptEngineManager manager = new ScriptEngineManager();
    				ScriptEngine engine = manager.getEngineByName("JavaScript");
    				String apv = "";
    				try {
    					Object result = engine.eval(js);
    					apv = new BigDecimal(result.toString()).setScale(0, BigDecimal.ROUND_HALF_UP).toPlainString();
    				} catch (Exception e) {
    					logger.error("计算错误：" + js + ",itemid:" + itemid + ",clock:" + ck);
    					apv = "0";
    				}
    				m.put("APPORTVALUE", apv);
    			}
    		}
    		return success(re);
    	}else{
    		return success();
    	}
    }

}
