package com.steerinfo.ems.trmdwvalue.controller;

import com.steerinfo.ems.trmdfvalue.model.TRmDfValue;
import com.steerinfo.ems.trmdfvalue.service.ITRmDfValueService;
import com.steerinfo.ems.trmworkprocproduct.mapper.TRmWorkprocProductMapper;
import com.steerinfo.ems.trmworkprocproduct.model.TRmWorkprocProduct;
import com.steerinfo.ems.trmworkprocproduct.service.ITRmWorkprocProductService;
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.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.trmactvalue.model.TRmActValue;
import com.steerinfo.ems.trmdwvalue.model.TRmDwValue;
import com.steerinfo.ems.trmdwvalue.service.ITRmDwValueService;
import com.steerinfo.ems.trmindexitem.model.TRmIndexItem;
import com.steerinfo.ems.trmworkprocproductvalue.model.TRmWorkprocProductValue;
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.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.math.BigDecimal;
import java.util.ArrayList;

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

    @Autowired
    ITRmDwValueService tRmDwValueService;
    
    @Autowired
    ITRmActItemService tRmActItemService;
    
    @Autowired
    private TRmActItemMapper tRmActItemMapper;
    
    @Autowired
    private IFormulaService formulaService;
    
    @Autowired
    private ITRmWorkprocProductValueService tRmWorkprocProductValueService;
    @Autowired
    private ITRmWorkprocProductService tRmWorkprocProductService;
  @Autowired
  private ITRmDfValueService tRmDfValueService;

    @ApiOperation(value="获取列表", notes="分页查询")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "pageNum", value = "查询页数", required = false, dataType = "Integer"),
        @ApiImplicitParam(name = "pageSize", value = "每页记录数", required = false, dataType = "Integer")
    })
    //@RequiresPermissions("trmdwvalue:view")
    @GetMapping(value = "/")
    public RESTfulResult list(@RequestParam HashMap<String, Object> parmas,Integer pageNum, Integer pageSize){
        PageList<TRmDwValue> list = tRmDwValueService.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("trmdwvalue:view")
    @GetMapping(value = "/like/")
    public RESTfulResult listLike(@RequestParam HashMap<String, Object> parmas,Integer pageNum, Integer pageSize){
        PageList<TRmDwValue> list = tRmDwValueService.queryLikeForPage(parmas, pageNum, pageSize);
        return success(list);
    }
    
    @ApiOperation(value="创建", notes="根据TRmDwValue对象创建")
    @ApiImplicitParam(name = "tRmDwValue", value = "详细实体tRmDwValue", required = true, dataType = "TRmDwValue")
    //@RequiresPermissions("trmdwvalue:create")
    @PostMapping(value = "/")
    public RESTfulResult add(@ModelAttribute TRmDwValue model){
        TRmDwValue tRmDwValue = tRmDwValueService.add(model);
        return success(tRmDwValue);
    }
    
    @ApiOperation(value="更新详细信息", notes="根据url的id来指定更新对象，并根据传过来的TRmDwValue信息来更新详细信息")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "TRmDwValue", value = "详细实体tRmDwValue", required = true, dataType = "TRmDwValue")
    })
    //@RequiresPermissions("trmactvalue:update")
    @PutMapping(value = "/batchUpdate", produces  = "application/json;charset=UTF-8")
    public RESTfulResult batchUpdate(@RequestBody TRmDwValue[] models){
    	int failnum = 0;
        ArrayList<String> failmsgs = new ArrayList<String>();
        for (int i = 0; i< models.length; i++) {
        	TRmDwValue 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());
    		TRmDwValue td = tRmDwValueService.getById(id);
    		if(td==null || td.getProductwvalue()==null){
    			continue;
    		}
        	try {
        		model.setProductwvalue(td.getProductwvalue());
	            tRmDwValueService.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 = tRmDwValueService.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();
            String rtpitemid = m.get("rtpitemid") == null ? "" : m.get("rtpitemid").toString();
            String timegranid = "MONTH";
            Double dwcl = null;
            if (!productwvalue.isEmpty()) {
                dwcl = Double.valueOf(productwvalue);
            } else if (!apportvalue.isEmpty()) {
                dwcl = Double.valueOf(apportvalue);
            }
            // 修改产品项目的 上报关联编号
            TRmWorkprocProduct tRmWorkprocProduct = tRmWorkprocProductService.getById(itemid);
            if(tRmWorkprocProduct!=null){
            	tRmWorkprocProduct.setrtpitemid(rtpitemid);
                tRmWorkprocProductService.modify(tRmWorkprocProduct);
            }
            // 根据fid，重新计算能源上报项目数据
            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) {
                tRmDwValueService.restatData(it.getItemid(), clock, timegranid, JwtUtil.getUseridByToken(), dwcl, bz);
            }
            // 修改确认产量、确认人、确认时间
            HashMap<String, Object> id = new HashMap<String, Object>();
            id.put("clock", clock);
            id.put("timegranid", "MONTH");
            id.put("itemid", itemid);
            id.put("itemtype", "R");
            TRmWorkprocProductValue wpv = tRmWorkprocProductValueService.getById(id);
            wpv.setRtpvalue(new BigDecimal(Double.toString(dwcl)));
            wpv.setBz2(bz);
            wpv.setQrman(JwtUtil.getUseridByToken());
            wpv.setQrtime(DateUtils.dateStr(new Date(), "yyyy-MM-dd HH:mm:ss"));
            tRmWorkprocProductValueService.modify(wpv);
            // 确认焦化工序焦炭产量，维护精煤产量，生成洗煤数据
            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", timegranid, clock, 0);
                if (jm != null && jm > 0) {
                    for (TRmActItem it : l) {
                        tRmDwValueService.restatData(it.getItemid(), clock, timegranid, JwtUtil.getUseridByToken(), jm, bz);
                    }
                }
            }
        }
    	return success();
    }
    
    @ApiOperation(value="批量重新计算", notes="根据url的id来指定更新对象，并根据传过来的TRmDwValue信息来更新详细信息")
    @ApiImplicitParam(name = "TRmDwValue", value = "详细实体TRmDwValue", required = true, dataType = "TRmDwValue")
    //@RequiresPermissions("trmcalpointvalue:update")
    @PutMapping(value = "/batchCompute", produces  = "application/json;charset=UTF-8")
    public RESTfulResult batchCompute(@RequestBody TRmDwValue[] model){
    	if(model.length<1){
    		return failed(null, "请勾选数据");
    	}
    	for (int i = 0; i< model.length; i++) {
    		TRmDwValue tv = model[i];
    		tRmDwValueService.restatData(tv.getItemid(), tv.getClock(), tv.getTimegranid(), JwtUtil.getUseridByToken(), null, "");
    	}
    	return success();
    }
    
    @ApiOperation(value="根据上报产量关联编号获取上报产量数据", notes="根据上报产量关联编号获取上报产量数据")
    //@RequiresPermissions("emscalpointvalue:update")
    @PutMapping(value = "/getPwData", produces  = "application/json;charset=UTF-8")
    public RESTfulResult getPwData(@RequestBody List<Map<String,Object>> mapList){
    	List<Map<String, Object>> rows = new ArrayList<Map<String, Object>>();
    	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 timegranid = "MONTH";
            String rtpitemid = m.get("rtpitemid") == null ? "" : m.get("rtpitemid").toString().replaceAll("，", ",");
            // 上报产量
            BigDecimal rtpvalue = BigDecimal.ZERO;
            if(!rtpitemid.isEmpty()){
            	// 遍历 上报产量关联编号
            	String[] ids = rtpitemid.split(",");
            	for (int j = 0; j < ids.length; j++) {
            		Double val = formulaService.readValByItemid(ids[j].trim(),timegranid, clock, 0);
            		if(val!=null){
            			rtpvalue = rtpvalue.add(new BigDecimal(Double.toString(val)));
            		}
            	}
            }
            Map<String, Object> mp = new HashMap<String, Object>();
            mp.put("key", itemid+"-"+clock);
            mp.put("val", rtpvalue.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString());
            rows.add(mp);
        }
    	return success(rows);
    }
}
