package com.steerinfo.ems.trmindexitem.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.Utils.DateUtils;
import com.steerinfo.ems.formula.model.Formula;
import com.steerinfo.ems.formula.service.IFormulaService;
import com.steerinfo.ems.trmindexitem.mapper.TRmIndexItemMapper;
import com.steerinfo.ems.trmindexitem.model.TRmIndexItem;
import com.steerinfo.ems.trmindexitem.service.ITRmIndexItemService;
import com.steerinfo.ems.trmindexvalue.mapper.TRmIndexValueMapper;
import com.steerinfo.ems.trmindexvalue.model.TRmIndexValue;
import com.steerinfo.ems.trmworkprocproductvalue.service.ITRmWorkprocProductValueService;

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.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

    @Autowired
    ITRmIndexItemService tRmIndexItemService;
    
    @Autowired
    private TRmIndexValueMapper tRmIndexValueMapper;
    
    @Autowired
    private TRmIndexItemMapper tRmIndexItemMapper;
    
    @Autowired
    private ITRmWorkprocProductValueService tRmWorkprocProductValueService;
    
    @Autowired
    IFormulaService formulaService;

    @ApiOperation(value="获取列表", notes="分页查询")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "pageNum", value = "查询页数", required = false, dataType = "Integer"),
        @ApiImplicitParam(name = "pageSize", value = "每页记录数", required = false, dataType = "Integer")
    })
    //@RequiresPermissions("trmindexitem:view")
    @GetMapping(value = "/")
    public RESTfulResult list(@RequestParam HashMap<String, Object> parmas,Integer pageNum, Integer pageSize){
        PageList<TRmIndexItem> list = tRmIndexItemService.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("trmindexitem:view")
    @GetMapping(value = "/like/")
    public RESTfulResult listLike(@RequestParam HashMap<String, Object> parmas,Integer pageNum, Integer pageSize){
    	if(parmas.get("itemtype")!=null && !parmas.get("itemtype").toString().isEmpty()){
			String itemtype = parmas.get("itemtype").toString();
			if(!itemtype.startsWith("'")){
				itemtype = "'" + itemtype.replaceAll(",", "','").replaceAll("，", "','") + "'";
			}
			parmas.put("itemtype", itemtype);
		}
    	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<TRmIndexItem> list = tRmIndexItemService.queryLikeForPage(parmas, pageNum, pageSize);
        return success(list);
    }
    
    @ApiOperation(value="创建", notes="根据TRmIndexItem对象创建")
    @ApiImplicitParam(name = "tRmIndexItem", value = "详细实体tRmIndexItem", required = true, dataType = "TRmIndexItem")
    //@RequiresPermissions("trmindexitem:create")
    @PostMapping(value = "/")
    public RESTfulResult add(@RequestBody TRmIndexItem model) {
        if (null ==model.getParentid()) {
             model.setItemflag("1");
            if(null ==tRmIndexItemService.getMaxId(model)){
                model.setItemid(model.getIndextype() + "001");
            } else {
                String maxId = tRmIndexItemService.getMaxId(model);
                maxId = String.format("%0" + maxId.length() + "d", Integer.parseInt(maxId) + 1);
                model.setItemid(model.getIndextype() + maxId);
            }
        } else {
            if(null ==tRmIndexItemService.getMaxId(model)){
                model.setItemflag("2");
                model.setItemid(model.getParentid() + "001");
            }else {
                String maxId = tRmIndexItemService.getMaxId(model);
                maxId = String.format("%0" + maxId.length() + "d", Integer.parseInt(maxId) + 1);
                model.setItemid(model.getIndextype() + maxId);
                model.setItemflag("2");
            }
        }
        TRmIndexItem  tRmIndexItem= tRmIndexItemService.add(model);
        return success(tRmIndexItem);
    }

    @ApiOperation(value = "创建3级菜单",notes = "根据Map集合来创建实体对象")
    @ApiImplicitParam(name = "Map" ,value = "集合Map", required = true, dataType = "map")
    @PostMapping("/add3")
    public RESTfulResult add3(@RequestBody  Map<String,Object> params){
    	if(params.get("parentid")==null || params.get("parentid").toString().isEmpty()){
    		return  failed(null,"请传入父项目编号");
    	}
    	if(params.get("yongtu")==null || params.get("yongtu").toString().isEmpty()){
    		return  failed(null,"请选择用途");
    	}
    	if(params.get("trmindextype")==null || params.get("trmindextype").toString().isEmpty()){
    		return  failed(null,"请选择指标类型");
    	}
    	if(params.get("trmenergy")==null || params.get("trmenergy").toString().isEmpty()){
    		return  failed(null,"请选择能介");
    	}
    	if(params.get("trmworkproc")==null || params.get("trmworkproc").toString().isEmpty()){
    		return  failed(null,"请选择工序");
    	}
    	if(params.get("trmfactory")==null || params.get("trmfactory").toString().isEmpty()){
    		return  failed(null,"请选择工厂");
    	}
    	if(params.get("mintimegranid")==null || params.get("mintimegranid").toString().isEmpty()){
    		return  failed(null,"请传入时间粒度");
    	}
        Map trmfactory = (Map)params.get("trmfactory");
        // 工厂名称
        String trmfactoryName = (String)trmfactory.get("name");
        // 工厂id
        String factoryid = (String)trmfactory.get("id");
        // 工序
        Map trmworkproc = (Map)params.get("trmworkproc");
        //工序名
        String trmworkprocName = (String)trmworkproc.get("name");
        //工序id
        String workprocid = (String)trmworkproc.get("id");
        // 能介
        Map trmenergy = (Map)params.get("trmenergy");
        //能介名称
        String trmenergyName = (String)trmenergy.get("name");
        //能介id
        String energyid = (String)trmenergy.get("id");
        //用途类型
        String yongtu = (String)params.get("yongtu");
        Map trmindextype = (Map)params.get("trmindextype");
        //指标名称
        String indexName = (String)trmindextype.get("indexname");
        //项目描述
        String itemdesc = (String)params.get("itemdesc");
        //指标类型id
        String indexId = (String)trmindextype.get("indexid");
        //用途编码
        String itemtype = (String)params.get("itemtype");
        //指标类型1
        String type1 = (String)params.get("type1");
        //指标类型2
        String type2 = (String)params.get("type2");
        //指标类型3
        String type3 = (String)params.get("type3");
        //指标类型4
        String type4 = (String)params.get("type4");
        //单位
        String unitid  = (String)params.get("unitid");
        //数值精度
        String digits = params.get("digits") == null || params.get("digits").toString().isEmpty() ? "2" :params.get("digits").toString();
        //显示顺序
        // String seqno = params.get("seqno") == null ? "10" :(String)params.get("seqno");
        //父级id
        String parentid = (String) params.get("parentid");
        //属性
        String propertyid = params.get("propertyid")==null?"":params.get("propertyid").toString();
        // 同指标类型、同用途、同能介、同工序、同工厂不允许重复增加
        HashMap<String, Object> parmas = new HashMap<String, Object>();
    	parmas.put("itemtype", itemtype);
    	parmas.put("indextype", indexId);
    	parmas.put("energyid", energyid);
    	parmas.put("workprocid", workprocid);
    	parmas.put("factoryid", factoryid);
    	parmas.put("parentid", parentid);
    	parmas.put("propertyid", propertyid);
    	List<TRmIndexItem> lm = tRmIndexItemMapper.selectByParameters(parmas);
    	if(lm!=null && lm.size()>0){
			return failed(null, "同指标类型、同用途、同能介、同工序、同工厂不允许重复增加");
		}
        //项目id
        TRmIndexItem tRmIndexItem = new TRmIndexItem();
        tRmIndexItem.setItemdesc(itemdesc);
        tRmIndexItem.setItemtype(itemtype);
        tRmIndexItem.setIndextype(indexId);
        tRmIndexItem.setType1(type1);
        tRmIndexItem.setType2(type2);
        tRmIndexItem.setType3(type3);
        tRmIndexItem.setType4(type4);
        tRmIndexItem.setEnergyid(energyid);
        tRmIndexItem.setWorkprocid(workprocid);
        tRmIndexItem.setFactoryid(factoryid);
        tRmIndexItem.setUseflag("1");
        tRmIndexItem.setUnitid(unitid);
        tRmIndexItem.setDigits(Short.parseShort(digits));
        tRmIndexItem.setSeqno(10);
        tRmIndexItem.setParentid(parentid);
        tRmIndexItem.setItemflag("3");
        tRmIndexItem.setPropertyid(propertyid);
        tRmIndexItem.setMintimegranid(params.get("mintimegranid").toString().trim());
        if(params.get("warnvalue")!=null && !params.get("warnvalue").toString().isEmpty()){
        	tRmIndexItem.setWarnvalue(Short.parseShort(params.get("warnvalue").toString()));
        }
        String itemid = "";
        String maxId = tRmIndexItemService.getMaxId(tRmIndexItem);
        if(maxId==null || maxId.isEmpty()){
        	int idx = tRmIndexItem.getParentid().indexOf("0");
        	itemid= itemtype + "_" + tRmIndexItem.getParentid().substring(0, idx) + "_" + tRmIndexItem.getParentid().substring(idx) + "0001";
        }else {
            maxId = String.format("%0" + maxId.length() + "d", Long.parseLong(maxId) + 1);
            itemid = itemtype + "_" + indexId + "_" + maxId;
        }
        tRmIndexItem.setItemid(itemid);
        tRmIndexItem.setItemname(trmfactoryName+trmworkprocName+trmenergyName+yongtu+indexName);
        TRmIndexItem add = tRmIndexItemService.add(tRmIndexItem);
		// 增加公式
		Formula formula = new Formula();
		formula.setClock(DateUtils.getCurrentTime("yyyyMM"));
		formula.setCode(itemid);
		formula.setDescription(trmfactoryName+trmworkprocName+trmenergyName+yongtu+indexName);
		formula.setSourcecode("R(T_RM_INDEX_VALUE," + itemid + ")");
		formula.setIsavailable("1");
		formula.setRevisetime(DateUtils.getCurrentTime("yyyy-MM-dd HH:mm:ss"));
		formula.setTablename("T_RM_INDEX_VALUE");
		formulaService.add(formula);
        return success(add);
    }

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

    @ApiOperation(value="更新详细信息", notes="根据url的id来指定更新对象，并根据传过来的tRmIndexItem信息来更新详细信息")
    @ApiImplicitParams({
        @ApiImplicitParam(paramType = "path", name = "id", value = "ID", required = true, dataType = "String"),
        @ApiImplicitParam(name = "tRmIndexItem", value = "详细实体tRmIndexItem", required = true, dataType = "TRmIndexItem")
    })
    //@RequiresPermissions("trmindexitem:update")
    @PutMapping(value = "/{id}", produces  = "application/json;charset=UTF-8")
    public RESTfulResult update(@PathVariable String id, @RequestBody TRmIndexItem model){
        model.setId(id);
        TRmIndexItem tRmIndexItem = tRmIndexItemService.modify(model);
        return success(tRmIndexItem);
    }
    
    @ApiOperation(value="获得工序能耗对比分析数据", notes="能源综合分析-供需实绩分析-工序能耗对比分析页面，分页查询")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "pageNum", value = "查询页数", required = false, dataType = "Integer"),
        @ApiImplicitParam(name = "pageSize", value = "每页记录数", required = false, dataType = "Integer")
    })
    @GetMapping(value = "/getDate613ForPage")
    public RESTfulResult getDate613ForPage(@RequestParam HashMap<String, Object> parmas,Integer pageNum, Integer pageSize){
    	if (parmas == null) {
    		return failed(null, "请传入参数");
    	}
    	if (parmas.get("clock") == null || parmas.get("clock").toString().isEmpty()) {
    		return failed(null, "请选择比较时间");
    	}
    	if(parmas.get("timegranid") == null || parmas.get("timegranid").toString().isEmpty()){
    		return failed(null, "请选择时间粒度");
    	}
    	if(parmas.get("indexid")!=null && !parmas.get("indexid").toString().isEmpty()){
			String indexid = parmas.get("indexid").toString();
			if(!indexid.startsWith("'")){
				indexid = "'" + indexid.replaceAll(",", "','").replaceAll("，", "','") + "'";
			}
			parmas.put("indexid", indexid);
		}
    	PageList<Map<String, Object>> list = tRmIndexItemService.getDate613ForPage(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 = "/getDate614ForPage")
    public RESTfulResult getDate614ForPage(@RequestParam HashMap<String, Object> parmas,Integer pageNum, Integer pageSize,Integer pageNum2, Integer pageSize2){
    	if (parmas == null) {
    		return failed(null, "请传入参数");
    	}
    	if (parmas.get("clock") == null || parmas.get("clock").toString().isEmpty()) {
    		return failed(null, "请选择起始时间");
    	}
    	if (parmas.get("clocke") == null || parmas.get("clocke").toString().isEmpty()) {
    		return failed(null, "请选择起始结束时间");
    	}
    	if(parmas.get("timegranid") == null || parmas.get("timegranid").toString().isEmpty()){
    		return failed(null, "请选择时间粒度");
    	}
    	if(parmas.get("indexid")!=null && !parmas.get("indexid").toString().isEmpty()){
			String indexid = parmas.get("indexid").toString();
			if(!indexid.startsWith("'")){
				indexid = "'" + indexid.replaceAll(",", "','").replaceAll("，", "','") + "'";
			}
			parmas.put("indexid", indexid);
		}
    	List<Map<String, Object>> list = tRmIndexItemService.getDate6141ForPage(parmas, pageNum, pageSize);
    	List<Map<String, Object>> list2 = tRmIndexItemService.getDate6142ForPage(parmas, pageNum2, pageSize2);
    	Map<String, Object> m = new HashMap<String, Object>();
    	m.put("result1", list);
    	m.put("result2", list2);
        return success(m);
    }
    
    @ApiOperation(value="获得吨钢综合能耗跟踪及趋势分析数据", notes="能源综合分析-吨钢综合能耗分析-吨钢综合能耗跟踪及趋势分析页面，分页查询")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "pageNum", value = "查询页数", required = false, dataType = "Integer"),
        @ApiImplicitParam(name = "pageSize", value = "每页记录数", required = false, dataType = "Integer")
    })
    @GetMapping(value = "/getDate631ForPage")
    public RESTfulResult getDate631ForPage(@RequestParam HashMap<String, Object> parmas,Integer pageNum, Integer pageSize){
    	List<Map<String, Object>> list = tRmIndexItemService.getDate6311ForPage(parmas);
    	List<Map<String, Object>> list2 = tRmIndexItemService.getDate6312ForPage(parmas);
    	Map<String, Object> m = new HashMap<String, Object>();
    	m.put("result1", list);
    	m.put("result2", list2);
        return success(m);
    }
    
    @ApiOperation(value="获得吨钢综合能耗影响因素分析数据", notes="能源综合分析-吨钢综合能耗分析-吨钢综合能耗影响因素分析页面")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "pageNum", value = "查询页数", required = false, dataType = "Integer"),
        @ApiImplicitParam(name = "pageSize", value = "每页记录数", required = false, dataType = "Integer")
    })
    @GetMapping(value = "/getDate632ForPage")
    public RESTfulResult getDate632ForPage(@RequestParam HashMap<String, Object> parmas,Integer pageNum, Integer pageSize){
    	if (parmas == null || parmas.get("clock") == null || parmas.get("clock").toString().isEmpty()) {
    		return failed(null, "请选择比较时间");
    	}
    	if (parmas.get("timegranid")== null || parmas.get("timegranid").toString().isEmpty()) {
    		return failed(null, "请选择时间粒度");
    	}
    	if (parmas.get("compareclock")== null || parmas.get("compareclock").toString().isEmpty()) {
    		return failed(null, "请选择被比时间");
    	}
    	// 先查询出钢产量
    	HashMap<String, Object> parma = new HashMap<String, Object>();
    	parma.put("workprocid", "ZY0000");
    	parma.put("timegranid", parmas.get("timegranid").toString());
    	parma.put("isprimary", "1");
    	parma.put("clock", parmas.get("clock").toString());
    	Double p1 = tRmWorkprocProductValueService.getProductvalue(parma);
    	if (p1==null || p1<=0){
    		return failed(null, parmas.get("clock").toString() + " 钢产量数据错误");
    	}
    	parmas.put("p1", p1); // 比较日期钢产量
    	parma.put("clock", parmas.get("compareclock").toString());
    	Double p2 = tRmWorkprocProductValueService.getProductvalue(parma);
    	if (p2==null || p2<=0){
    		return failed(null, parmas.get("compareclock").toString() + " 钢产量数据错误");
    	}
    	parmas.put("p2", p2); // 被比日期钢产量
    	List<Map<String, Object>> list = tRmIndexItemService.getDate632ForPage(parmas, pageNum, pageSize);
        return success(list);
    }

    @ApiOperation(value = "加载动态树",notes = "能源综合分析-指标管理-指标分析")
    @GetMapping("/getTrees")
    public RESTfulResult getTrees(@RequestParam HashMap<String, Object> parmas,Integer pageNum, Integer pageSize) {
        PageList<Map<String, Object>> trees = tRmIndexItemService.getTrees(parmas, pageNum, pageSize);
        return success(trees);
    }

    @ApiOperation(value = "查询",notes = "能源综合分析-经济指标分析-能耗指标自身对比")
    @GetMapping(value = "/getIdAndNameByIndextype")
    public RESTfulResult getIdAndNameByIndextype(String indextype){
        List<TRmIndexItem> idAndNameByIndextype = tRmIndexItemService.getIdAndNameByIndextype(indextype);
        return success(idAndNameByIndextype);
    }

    @ApiOperation(value="查询", notes="能源综合分析-经济指标分析-能耗指标自身对比(分页查询)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "查询页数", required = false, dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "每页记录数", required = false, dataType = "Integer"),
    })
    @GetMapping("/getIndexItems")
    public RESTfulResult getIndexItems(@RequestParam HashMap<String, Object> parmas,Integer pageNum, Integer pageSize){
    	if (parmas == null || parmas.get("timegranid") == null || parmas.get("timegranid").toString().isEmpty()) {
    		return failed(null, "请选择时间粒度");
    	}
    	if (parmas.get("clock")== null || parmas.get("clock").toString().isEmpty()) {
    		return failed(null, "请选择比较时间");
    	}
    	if (parmas.get("compareclock")== null || parmas.get("compareclock").toString().isEmpty()) {
    		return failed(null, "请选择被比时间");
    	}
    	if (parmas.get("itemid")== null || parmas.get("itemid").toString().isEmpty()) {
    		return failed(null, "请选择指标");
    	}else{
    		String itemid = parmas.get("itemid").toString();
			if(!itemid.startsWith("'")){
				itemid = "'" + itemid.replaceAll(",", "','").replaceAll("，", "','") + "'";
			}
			parmas.put("itemid", itemid);
    	}
    	List<Map<String, Object>> indexItems = tRmIndexItemService.getDate641ForPage(parmas, pageNum, pageSize);
        return success(indexItems);
    }

    @ApiOperation(value="查询", notes="能源综合分析-经济指标分析-能耗指标跟踪分析")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "查询页数", required = false, dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "每页记录数", required = false, dataType = "Integer"),
    })
    @GetMapping("/getIndexitemDetailByPage")
    public RESTfulResult getIndexitemDetailByPage(@RequestParam HashMap<String, Object> parmas,Integer pageNum, Integer pageSize){
    	if (parmas == null || parmas.get("timegranid") == null || parmas.get("timegranid").toString().isEmpty()) {
    		return failed(null, "请选择时间粒度");
    	}
    	if (parmas.get("clock")== null || parmas.get("clock").toString().isEmpty()) {
    		return failed(null, "请选择起始时间");
    	}
    	if (parmas.get("clocke")== null || parmas.get("clocke").toString().isEmpty()) {
    		return failed(null, "请选择结束时间");
    	}
    	if (parmas.get("itemid")== null || parmas.get("itemid").toString().isEmpty()) {
    		return failed(null, "请选择指标");
    	}else{
    		String itemid = parmas.get("itemid").toString();
			if(!itemid.startsWith("'")){
				itemid = "'" + itemid.replaceAll(",", "','").replaceAll("，", "','") + "'";
			}
			parmas.put("itemid", itemid);
    	}
    	List<Map<String, Object>> indexitemDetails = tRmIndexItemService.getDate643ForPage(parmas, pageNum, pageSize);
        return success(indexitemDetails);
    }
    
    @ApiOperation(value="批量更新详细信息", notes="根据url的id来指定更新对象，并根据传过来的TRmIndexItem信息来更新详细信息")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "TRmIndexItem", value = "详细实体TRmIndexItem", required = true, dataType = "TRmIndexItem")
    })
    //@RequiresPermissions("emscalpointvalue:update")
    @PutMapping(value = "/batchupdate", produces  = "application/json;charset=UTF-8")
    public RESTfulResult update(@RequestBody TRmIndexItem[] model){
    	int failnum = 0;
        String failmsg = "";
        ArrayList<String> warnmsg = new ArrayList<String>();
    	for (int i = 0; i< model.length; i++) {
    		// 同指标类型、同用途、同能介、同工序、同工厂不允许重复增加
    		TRmIndexItem t = tRmIndexItemService.getById(model[i].getItemid());
    		String oldMintimegranid = t.getMintimegranid();
    		if(model[i].getItemid().indexOf("DFBZ_NYDF") == -1){
                HashMap<String, Object> parmas = new HashMap<String, Object>();
                parmas.put("itemtype", t.getItemtype());
                parmas.put("indextype", t.getIndextype());
                parmas.put("energyid", t.getEnergyid());
                parmas.put("workprocid", model[i].getWorkprocid());
                parmas.put("factoryid", model[i].getFactoryid());
                parmas.put("parentid", t.getParentid());
                parmas.put("propertyid", model[i].getPropertyid());
                List<TRmIndexItem> lm = tRmIndexItemMapper.selectByParameters(parmas);
                if (lm != null && lm.size() > 0) {
                    if (lm.size() > 1 || !lm.get(0).getItemid().equalsIgnoreCase(model[i].getItemid())) {
                        // return failed(null, "同指标类型、同用途、同能介、同工序、同工厂不允许重复");
                        failmsg += model[i].getItemid() + "-同指标类型、同用途、同能介、同工序、同工厂不允许重复;";
                        failnum++;
                        continue;
                    }
                }
            }
        	// 禁用
        	if("0".equals(model[i].getUseflag())){
        		List<Formula> formulaList = formulaService.getAssociatedFormula(model[i].getItemid());
        		if(formulaList.size() > 0) {
        			String ids = "";
                    for (Formula forms : formulaList){
                        ids += forms.getCode() + ",";
                    }
                    failmsg += model[i].getItemid()+"-该项目被" + formulaList.size() + "条公式所使用,公式名:" + ids+";";
                    failnum++;
        			continue;
        		}
            }
        	// 启用
        	if("1".equals(model[i].getUseflag()) && t.getUseflag().equals("0")){
        		Map<String, Object> formulaparam = new HashMap<>();
                formulaparam.put("clock", DateUtils.getCurrentTime("yyyyMM"));
                formulaparam.put("code", model[i].getItemid());
                Formula fm = formulaService.getByParams(formulaparam);
                String ck = formulaService.checkFormula(fm);
                if(ck !=""){
                	failmsg += model[i].getItemid()+"-公式不合法:" + ck +";";
                    failnum++;
        			continue;
                }
            }
        	// 修改时间粒度
        	if(!oldMintimegranid.equalsIgnoreCase(model[i].getMintimegranid())){
        		Map<String, Object> formulaparam = new HashMap<>();
                formulaparam.put("clock", DateUtils.getCurrentTime("yyyyMM"));
                formulaparam.put("code", model[i].getItemid());
                Formula fm = formulaService.getByParams(formulaparam);
                String ck = formulaService.checkFormulaMint(fm,model[i].getMintimegranid());
                if(ck !=""){
                	warnmsg.add(model[i].getId() + ":" + ck);
                }
            }
        	model[i].setUpdateman(JwtUtil.getUseridByToken());
        	model[i].setUpdatetime(DateUtils.dateStr(new Date(),"yyyy-MM-dd HH:mm:ss"));
            tRmIndexItemService.modify(model[i]);
            Map<String, Object> pm = new HashMap<>();
            pm.put("code", model[i].getItemid());
            pm.put("description", model[i].getItemname());
            pm.put("isavailable", model[i].getUseflag());
            formulaService.updateDesBycode(pm);
    	}
    	String wmsg = "";
    	if(warnmsg.size()>0){
    		wmsg = "(" + warnmsg.toString() + ")";
    	}
    	if(!failmsg.isEmpty()){
    		failmsg = failmsg.substring(0,failmsg.length()-1);
    		return success("51","本次共修改" + model.length + "条数据,其中成功" + (model.length - failnum) + "条"+wmsg+",失败" + failnum + "条:[" + failmsg + "]");
    	}
    	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")
    //@RequiresPermissions("trmindexitem:delete")
    @DeleteMapping(value = "/{id}")
    public RESTfulResult delete(@PathVariable String id){
    	String[] ids = id.split(",");
    	String userId = JwtUtil.getUseridByToken();
    	for (int i = 0; i < ids.length; i++) {
        	List<Formula> list = formulaService.getFormulaByCode("[" + ids[i] + "]");
        	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 + " 公式中包含项目 " + ids[i] + "，请先处理");
        	}
        	HashMap<String, Object> parmas = new HashMap<String, Object>();
        	parmas.put("itemid", ids[i]);
        	List<TRmIndexValue> l = tRmIndexValueMapper.selectByParameters(parmas);
        	if(l!=null && l.size()>0){
				return failed(null, "[" + ids[i] + "]指标已有数据，不能删除");
			}
        	HashMap<String, Object> parmas2 = new HashMap<String, Object>();
        	parmas2.put("parentid", ids[i]);
        	List<TRmIndexItem> lm = tRmIndexItemMapper.selectByParameters(parmas2);
        	if(lm!=null && lm.size()>0){
				return failed(null, "[" + ids[i] + "]下有子项，不能删除");
			}
        }
    	if(ids.length >= 1){
    		logger.info("T_RM_INDEX_ITEM表的数据发生删除(操作人ID：" + userId + ")，id:" + id);
    		tRmIndexItemService.delIndexItem(ids);
            return success();
        }else{
        	return failed(null, "请选择要删除的项目编号");
        }
    }
    
    @ApiOperation(value = "创建上报指标项目",notes = "根据Map集合来创建实体对象")
    @ApiImplicitParam(name = "Map" ,value = "集合Map", required = true, dataType = "map")
    @PostMapping("/add3w")
    public RESTfulResult add3w(@RequestBody  Map<String,Object> params){
    	if(params.get("trmenergy")==null || params.get("trmenergy").toString().isEmpty()){
    		return  failed(null,"请选择能介");
    	}
    	if(params.get("trmworkproc")==null || params.get("trmworkproc").toString().isEmpty()){
    		return  failed(null,"请选择工序");
    	}
    	if(params.get("property")==null || params.get("property").toString().isEmpty()){
    		return  failed(null,"请选择属性");
    	}
    	// 属性
        Map property = (Map)params.get("property");
        // 工序
        Map trmworkproc = (Map)params.get("trmworkproc");
        // 能介
        Map trmenergy = (Map)params.get("trmenergy");
        if (property.get("id")==null || trmworkproc.get("id")==null || trmenergy.get("id")==null ||
        		property.get("name")==null || trmworkproc.get("name")==null || trmenergy.get("name")==null) {
        	return  failed(null,"请填写完整数据");
        }
        // 属性
        String propertyid = property.get("id").toString();
        String propertyname = property.get("name").toString();
        // 能介
        String energyid = trmenergy.get("id").toString();
        String energyname = trmenergy.get("name").toString();
        // 工序
        String workprocid = (String)trmworkproc.get("id");
        String trmworkprocName = (String)trmworkproc.get("name");
        
        // 用途编码, 上报（T_RM_INDEX_ITEM）
        String itemtype = "DWBZ";
        // 指标类型id （T_RM_INDEX_TYPE）
        String indextype = "NYDW";
        // 工厂id,中阳钢铁
        String factoryid = "ZY0000";
        // 父级id
        String parentid = "NYDW001001";
        // 指标名称,上报指标
        String indexName = "上报指标";
        // 显示顺序
        Integer code = params.get("code") == null || params.get("code").toString().trim().isEmpty() ? null :Integer.valueOf(params.get("code").toString());
        // 数值精度
        String digits = params.get("digits") == null || params.get("digits").toString().isEmpty() ? "2" :params.get("digits").toString();
        // 波动系数
        Integer fluvalue = params.get("fluvalue") == null || params.get("fluvalue").toString().trim().isEmpty() ? null :Integer.valueOf(params.get("fluvalue").toString());
        // 同指标类型、同用途、同能介、同工序、同工厂不允许重复增加
        HashMap<String, Object> parmas = new HashMap<String, Object>();
    	parmas.put("itemtype", itemtype);
    	parmas.put("indextype", indextype);
    	parmas.put("energyid", energyid);
    	parmas.put("workprocid", workprocid);
    	parmas.put("factoryid", factoryid);
    	parmas.put("parentid", parentid);
    	parmas.put("propertyid", propertyid);
    	List<TRmIndexItem> lm = tRmIndexItemMapper.selectByParameters(parmas);
    	if(lm!=null && lm.size()>0){
			return failed(null, "该工序下此指标已经存在");
		}
        //项目id
        TRmIndexItem tRmIndexItem = new TRmIndexItem();
        tRmIndexItem.setItemtype(itemtype);
        tRmIndexItem.setIndextype(indextype);
        tRmIndexItem.setEnergyid(energyid);
        tRmIndexItem.setWorkprocid(workprocid);
        tRmIndexItem.setFactoryid(factoryid);
        tRmIndexItem.setUseflag("1");
        tRmIndexItem.setDigits(Short.parseShort(digits));
        tRmIndexItem.setFluvalue(fluvalue);
        tRmIndexItem.setFluitemid(params.get("fluitemid") == null?"":params.get("fluitemid").toString());
        tRmIndexItem.setSeqno(10);
        tRmIndexItem.setParentid(parentid);
        tRmIndexItem.setItemflag("3");
        tRmIndexItem.setCode(code);
        tRmIndexItem.setPropertyid(propertyid);
        tRmIndexItem.setCreateman(JwtUtil.getUseridByToken());
        tRmIndexItem.setCreatetime(DateUtils.dateStr(new Date(),"yyyy-MM-dd HH:mm:ss"));
        tRmIndexItem.setMintimegranid("MONTH");
        String itemid = "";
        String maxId = tRmIndexItemService.getMaxId(tRmIndexItem);
        if(maxId==null || maxId.isEmpty()){
        	int idx = tRmIndexItem.getParentid().indexOf("0");
        	itemid= itemtype + "_" + tRmIndexItem.getParentid().substring(0, idx) + "_" + tRmIndexItem.getParentid().substring(idx) + "0001";
        }else {
            maxId = String.format("%0" + maxId.length() + "d", Long.parseLong(maxId) + 1);
            itemid = itemtype + "_" + indextype + "_" + maxId;
        }
        tRmIndexItem.setItemid(itemid);
        tRmIndexItem.setItemname(trmworkprocName+energyname+propertyname+indexName);
        TRmIndexItem add = tRmIndexItemService.add(tRmIndexItem);
		// 增加公式
		Formula formula = new Formula();
		formula.setClock("202001");
		formula.setCode(itemid);
		formula.setDescription(trmworkprocName+energyname+propertyname+indexName);
		formula.setSourcecode("R(T_RM_INDEX_VALUE," + itemid + ")");
		formula.setIsavailable("1");
		formula.setRevisetime(DateUtils.getCurrentTime("yyyy-MM-dd HH:mm:ss"));
		formula.setTablename("T_RM_INDEX_VALUE");
		formulaService.add(formula);
        return success(add);
    }
    
    @ApiOperation(value = "创建上报指标项目",notes = "根据Map集合来创建实体对象")
    @ApiImplicitParam(name = "Map" ,value = "集合Map", required = true, dataType = "map")
    @PostMapping("/add3f")
    public RESTfulResult add3f(@RequestBody  Map<String,Object> params){
    	if(params.get("trmenergy")==null || params.get("trmenergy").toString().isEmpty()){
    		return  failed(null,"请选择能介");
    	}
    	if(params.get("trmworkproc")==null || params.get("trmworkproc").toString().isEmpty()){
    		return  failed(null,"请选择工序");
    	}
    	if(params.get("property")==null || params.get("property").toString().isEmpty()){
    		return  failed(null,"请选择属性");
    	}
    	// 属性
        Map property = (Map)params.get("property");
        // 工序
        Map trmworkproc = (Map)params.get("trmworkproc");
        // 能介
        Map trmenergy = (Map)params.get("trmenergy");
        if (property.get("id")==null || trmworkproc.get("id")==null || trmenergy.get("id")==null ||
        		property.get("name")==null || trmworkproc.get("name")==null || trmenergy.get("name")==null) {
        	return  failed(null,"请填写完整数据");
        }
        // 属性
        String propertyid = property.get("id").toString();
        String propertyname = property.get("name").toString();
        // 能介
        String energyid = trmenergy.get("id").toString();
        String energyname = trmenergy.get("name").toString();
        // 工序
        String workprocid = (String)trmworkproc.get("id");
        String trmworkprocName = (String)trmworkproc.get("name");
        
        // 用途编码, 上报（T_RM_INDEX_ITEM）
        String itemtype = "DFBZ";
        // 指标类型id （T_RM_INDEX_TYPE）
        String indextype = "NYDF";
        // 工厂id,中阳钢铁
        String factoryid = "ZY0000";
        // 父级id
        String parentid = "NYDF001001";
        // 指标名称,上报指标
        String indexName = "财务指标";
        // 显示顺序
        Integer code = params.get("code") == null || params.get("code").toString().trim().isEmpty() ? null :Integer.valueOf(params.get("code").toString());
        // 数值精度
        String digits = params.get("digits") == null || params.get("digits").toString().isEmpty() ? "2" :params.get("digits").toString();
        // 波动系数
        Integer fluvalue = params.get("fluvalue") == null || params.get("fluvalue").toString().trim().isEmpty() ? null :Integer.valueOf(params.get("fluvalue").toString());
        // 同指标类型、同用途、同能介、同工序、同工厂不允许重复增加
        HashMap<String, Object> parmas = new HashMap<String, Object>();
    	parmas.put("itemtype", itemtype);
    	parmas.put("indextype", indextype);
    	parmas.put("energyid", energyid);
    	parmas.put("workprocid", workprocid);
    	parmas.put("factoryid", factoryid);
    	parmas.put("parentid", parentid);
    	parmas.put("propertyid", propertyid);
    	List<TRmIndexItem> lm = tRmIndexItemMapper.selectByParameters(parmas);
    	/*
    	if(lm!=null && lm.size()>0){
			return failed(null, "该工序下此指标已经存在");
		}
		*/
        //项目id
        TRmIndexItem tRmIndexItem = new TRmIndexItem();
        tRmIndexItem.setItemtype(itemtype);
        tRmIndexItem.setIndextype(indextype);
        tRmIndexItem.setEnergyid(energyid);
        tRmIndexItem.setWorkprocid(workprocid);
        tRmIndexItem.setFactoryid(factoryid);
        tRmIndexItem.setUseflag("1");
        tRmIndexItem.setDigits(Short.parseShort(digits));
        tRmIndexItem.setFluvalue(fluvalue);
        tRmIndexItem.setFluitemid(params.get("fluitemid") == null?"":params.get("fluitemid").toString());
        tRmIndexItem.setSeqno(10);
        tRmIndexItem.setParentid(parentid);
        tRmIndexItem.setItemflag("3");
        tRmIndexItem.setCode(code);
        tRmIndexItem.setPropertyid(propertyid);
        tRmIndexItem.setCreateman(JwtUtil.getUseridByToken());
        tRmIndexItem.setCreatetime(DateUtils.dateStr(new Date(),"yyyy-MM-dd HH:mm:ss"));
        tRmIndexItem.setMintimegranid("DAY");
        String itemid = "";
        String maxId = tRmIndexItemService.getMaxId(tRmIndexItem);
        if(maxId==null || maxId.isEmpty()){
        	int idx = tRmIndexItem.getParentid().indexOf("0");
        	itemid= itemtype + "_" + tRmIndexItem.getParentid().substring(0, idx) + "_" + tRmIndexItem.getParentid().substring(idx) + "0001";
        }else {
            maxId = String.format("%0" + maxId.length() + "d", Long.parseLong(maxId) + 1);
            itemid = itemtype + "_" + indextype + "_" + maxId;
        }
        tRmIndexItem.setItemid(itemid);
        tRmIndexItem.setItemname(trmworkprocName+energyname+propertyname+indexName);
        TRmIndexItem add = tRmIndexItemService.add(tRmIndexItem);
		// 增加公式
		Formula formula = new Formula();
		formula.setClock("202001");
		formula.setCode(itemid);
		formula.setDescription(trmworkprocName+energyname+propertyname+indexName);
		formula.setSourcecode("R(T_RM_INDEX_VALUE," + itemid + ")");
		formula.setIsavailable("1");
		formula.setRevisetime(DateUtils.getCurrentTime("yyyy-MM-dd HH:mm:ss"));
		formula.setTablename("T_RM_INDEX_VALUE");
		formulaService.add(formula);
        return success(add);
    }
    
    @ApiOperation(value="获取上报指标列表", notes="分页模糊查询")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "pageNum", value = "查询页数", required = false, dataType = "Integer"),
        @ApiImplicitParam(name = "pageSize", value = "每页记录数", required = false, dataType = "Integer")
    })
    //@RequiresPermissions("trmindexitem:view")
    @GetMapping(value = "/likew/")
    public RESTfulResult listLikew(@RequestParam HashMap<String, Object> parmas,Integer pageNum, Integer pageSize){
    	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("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);
		}
        PageList<TRmIndexItem> list = tRmIndexItemService.queryLikewForPage(parmas, pageNum, pageSize);
        return success(list);
    }
}
