package com.steerinfo.ems.trmdfvalue.controller;

import com.steerinfo.auth.utils.JwtUtil;
import com.steerinfo.ems.formula.service.IFormulaService;
import com.steerinfo.ems.trmactitem.mapper.TRmActItemMapper;
import com.steerinfo.ems.trmactitem.model.TRmActItem;
import com.steerinfo.ems.trmactitem.service.ITRmActItemService;
import com.steerinfo.ems.trmdfvalue.model.TRmDfValue;
import com.steerinfo.ems.trmdfvalue.service.ITRmDfValueService;
import com.steerinfo.framework.controller.BaseRESTfulController;
import com.steerinfo.framework.controller.RESTfulResult;
import com.steerinfo.framework.service.pagehelper.PageList;
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.HashMap;
import java.util.List;
import java.util.Map;

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

    @Autowired
    ITRmDfValueService tRmDfValueService;
    
    @Autowired
    ITRmActItemService tRmActItemService;
    
    @Autowired
    private TRmActItemMapper tRmActItemMapper;
    
    @Autowired
    private IFormulaService formulaService;

    @ApiOperation(value="获取列表", notes="分页查询")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "pageNum", value = "查询页数", required = false, dataType = "Integer"),
        @ApiImplicitParam(name = "pageSize", value = "每页记录数", required = false, dataType = "Integer")
    })
    //@RequiresPermissions("trmdfvalue:view")
    @GetMapping(value = "/")
    public RESTfulResult list(@RequestParam HashMap<String, Object> parmas,Integer pageNum, Integer pageSize){
        PageList<TRmDfValue> list = tRmDfValueService.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("trmdfvalue:view")
    @GetMapping(value = "/like/")
    public RESTfulResult listLike(@RequestParam HashMap<String, Object> parmas,Integer pageNum, Integer pageSize){
        PageList<TRmDfValue> list = tRmDfValueService.queryLikeForPage(parmas, pageNum, pageSize);
        return success(list);
    }
    
    @ApiOperation(value="创建", notes="根据TRmDfValue对象创建")
    @ApiImplicitParam(name = "tRmDfValue", value = "详细实体tRmDfValue", required = true, dataType = "TRmDfValue")
    //@RequiresPermissions("trmdfvalue:create")
    @PostMapping(value = "/")
    public RESTfulResult add(@ModelAttribute TRmDfValue model){
        TRmDfValue tRmDfValue = tRmDfValueService.add(model);
        return success(tRmDfValue);
    }
    
    @ApiOperation(value="更新详细信息", notes="根据url的id来指定更新对象，并根据传过来的TRmDfValue信息来更新详细信息")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "TRmDfValue", value = "详细实体tRmDfValue", required = true, dataType = "TRmDfValue")
    })
    //@RequiresPermissions("trmactvalue:update")
    @PutMapping(value = "/batchUpdate", produces  = "application/json;charset=UTF-8")
    public RESTfulResult batchUpdate(@RequestBody TRmDfValue[] models){
    	int failnum = 0;
        ArrayList<String> failmsgs = new ArrayList<String>();
        for (int i = 0; i< models.length; i++) {
        	TRmDfValue model = models[i];
        	if (model.getApportwvalue()==null){
        		continue;
        	}
        	HashMap<String, Object> id = new HashMap<String, Object>();
    		id.put("clock", model.getClock());
    		id.put("timegranid", model.getTimegranid());
    		id.put("itemid", model.getItemid());
    		TRmDfValue td = tRmDfValueService.getById(id);
    		if(td==null || td.getProductwvalue()==null){
    			continue;
    		}
        	try {
        		model.setProductwvalue(td.getProductwvalue());
	            tRmDfValueService.modifyByApv(model);
	            formulaService.reCalculate(model.getItemid(), model.getClock(), model.getTimegranid(), model.getClock());
        	}catch(Exception e){
                failnum++;
                failmsgs.add(model.getItemid());
                logger.error("数据修改出现错误,错误原因是" + e + ",id是" + model.getItemid());
            }
        	if(failnum > 0){
                logger.info("本次共修改" + models.length + "条数据,其中成功" + (models.length - failnum) + "条,失败" + failnum + "条");
                return success(failmsgs, "101","本次共修改" + models.length + "条数据,其中成功" + (models.length - failnum) + "条,失败" + failnum + "条,失败的id:" + failmsgs.toString());
            }
    	}
        return success();
    }

    @ApiOperation(value = "查询上报产量数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "查询页数", required = false, dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "每页记录数", required = false, dataType = "Integer")
    })
    @GetMapping("/getProjectwData")
    public RESTfulResult getProjectwData(@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 = tRmDfValueService.getProjectwDataForPage(parmas, pageNum, pageSize);
        return  success(blist);
    }
    
    @ApiOperation(value="批量确认产量", notes="根据url的id来指定更新对象，并根据传过来的TRmIndexItem信息来更新详细信息")
    //@RequiresPermissions("emscalpointvalue:update")
    @PutMapping(value = "/batchqr", produces  = "application/json;charset=UTF-8")
    public RESTfulResult update(@RequestBody List<Map<String,Object>> mapList){
    	for (int i = 0; i< mapList.size(); i++) {
    		Map<String, Object> m = mapList.get(i);
    		String itemid = m.get("itemid").toString();
    		String clock = m.get("clock").toString();
    		String apportvalue = m.get("apportvalue")==null?"":m.get("apportvalue").toString();
    		String productwvalue = m.get("productwvalue")==null?"":m.get("productwvalue").toString();
    		String bz = m.get("bz")==null?"":m.get("bz").toString();
    		Double dwcl = null;
    		if(!productwvalue.isEmpty()){
    			dwcl = Double.valueOf(productwvalue);
    		}else if(!apportvalue.isEmpty()){
    			dwcl = Double.valueOf(apportvalue);
    		}
    		Map<String, Object> parma = new HashMap<String, Object>();
    		parma.put("itemtype", "W");
    		parma.put("fid", itemid);
    		parma.put("useflag", "1");
    		List<TRmActItem> tl = tRmActItemMapper.selectActr(parma);
    		for(TRmActItem it:tl){
    			tRmDfValueService.restatData(it.getItemid(), clock, "MONTH", JwtUtil.getUseridByToken(), dwcl, bz);
    		}
    		// 确认焦化工序焦炭产量，维护精煤产量，生成洗煤数据
    		if("ZY4000CP07R".equalsIgnoreCase(itemid)){
    			Map<String, Object> parma2 = new HashMap<String, Object>();
    			parma2.put("itemtype", "W");
        		parma2.put("useflag", "1");
        		parma2.put("workprocid", "'ZY3000'");
        		List<TRmActItem> l = tRmActItemMapper.selectActr(parma2);
        		// 精煤上报产量
        		Double jm = formulaService.getValByItemid("ZY3000X0052W", "MONTH", clock, 0);
        		if(jm!=null && jm>0){
        			for(TRmActItem it:l){
            			tRmDfValueService.restatData(it.getItemid(), clock, "MONTH", JwtUtil.getUseridByToken(), jm, bz);
            		}
        		}
    		}
    		// tRmDfValueService.restatData(itemid, clock, "MONTH", JwtUtil.getUseridByToken(), null);
    	}
    	return success();
    }
    
    @ApiOperation(value="批量重新计算", notes="根据url的id来指定更新对象，并根据传过来的TRmDfValue信息来更新详细信息")
    @ApiImplicitParam(name = "TRmDfValue", value = "详细实体TRmDfValue", required = true, dataType = "TRmDfValue")
    //@RequiresPermissions("trmcalpointvalue:update")
    @PutMapping(value = "/batchCompute", produces  = "application/json;charset=UTF-8")
    public RESTfulResult batchCompute(@RequestBody TRmDfValue[] model){
    	if(model.length<1){
    		return failed(null, "请勾选数据");
    	}
    	for (int i = 0; i< model.length; i++) {
    		TRmDfValue tv = model[i];
    		tRmDfValueService.restatData(tv.getItemid(), tv.getClock(), tv.getTimegranid(), JwtUtil.getUseridByToken(), null, "");
    	}
    	return success();
    }
}
