package com.steerinfo.ems.trmworkprocproductvalue.controller;

import com.steerinfo.auth.utils.JwtUtil;
import com.steerinfo.ems.Utils.DateUtils;
import com.steerinfo.ems.formula.service.IFormulaService;
import com.steerinfo.ems.ifmesemsswapfile.service.IIfMesEmsSwapfileService;
import com.steerinfo.ems.trmworkprocproduct.mapper.TRmWorkprocProductMapper;
import com.steerinfo.ems.trmworkprocproduct.model.TRmWorkprocProduct;
import com.steerinfo.ems.trmworkprocproduct.service.ITRmWorkprocProductService;
import com.steerinfo.feigen.model.LgWeight;
import com.steerinfo.feigen.service.LgWeightFeigenService;
import com.steerinfo.framework.controller.BaseRESTfulController;
import com.steerinfo.framework.controller.RESTfulResult;
import com.steerinfo.framework.service.pagehelper.PageList;
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.math.BigDecimal;
import java.util.*;

/**
 * TRmWorkprocProductValue RESTful接口：
 * @author generator
 * @version 1.0-SNAPSHORT 2019-10-17 04:31
 * 类描述
 * 修订历史：
 * 日期：2019-10-17
 * 作者：generator
 * 参考：
 * 描述：TRmWorkprocProductValue RESTful接口
 * @see null
 * @Copyright 湖南视拓信息技术股份有限公司. All rights reserved.
 */
@RestController
@RequestMapping("/${api.version}/trmworkprocproductvalues")
public class TRmWorkprocProductValueController extends BaseRESTfulController {

    private static final Logger logger = LoggerFactory.getLogger(TRmWorkprocProductValueController.class);

    @Autowired
    private   ITRmWorkprocProductValueService tRmWorkprocProductValueService;

    @Autowired
    private  ITRmWorkprocProductService tRmWorkprocProductService;
    
    @Autowired
    private TRmWorkprocProductMapper tRmWorkprocProductMapper;
    
    @Autowired
    IFormulaService formulaService;
    
    @Autowired
    IIfMesEmsSwapfileService ifMesEmsSwapfileService;
    @Autowired
    LgWeightFeigenService lgWeightFeigen;

    @ApiOperation(value="获取列表", notes="分页查询")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "pageNum", value = "查询页数", required = false, dataType = "Integer"),
        @ApiImplicitParam(name = "pageSize", value = "每页记录数", required = false, dataType = "Integer")
    })
    //@RequiresPermissions("trmworkprocproductvalue:view")
    @GetMapping(value = "/")
    public RESTfulResult list(@RequestParam HashMap<String, Object> parmas,Integer pageNum, Integer pageSize){
        tRmWorkprocProductValueService.setDate(new Date());
    	if(parmas.containsKey("productid") && parmas.get("productid") != null && !"".equals(parmas.get("productid").toString())){
            String productid = parmas.get("productid").toString();
            if(productid.indexOf(",") == -1){
                parmas.put("productid", "and wp.productid = '" + productid + "'");
            } else {
            	productid = "and wp.productid in ('" + productid.replaceAll(",", "','") + "')";
                parmas.put("productid", productid);
            }
        }
    	
    	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 wp.workprocid = '" + workprocid + "'");
            } else {
            	workprocid = "and wp.workprocid in ('" + workprocid.replaceAll(",", "','") + "')";
                parmas.put("workprocid", workprocid);
            }
        }
        PageList<Map<String, Object>> list = tRmWorkprocProductValueService.getDate53ForPage(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("trmworkprocproductvalue:view")
    @GetMapping(value = "/like/")
    public RESTfulResult listLike(@RequestParam HashMap parmas,Integer pageNum, Integer pageSize){
        PageList<TRmWorkprocProductValue> list = tRmWorkprocProductValueService.queryLikeForPage(parmas, pageNum, pageSize);
        return success(list);
    }
    
    @ApiOperation(value="创建", notes="根据TRmWorkprocProductValue对象创建")
    @ApiImplicitParam(name = "tRmWorkprocProductValue", value = "详细实体tRmWorkprocProductValue", required = true, dataType = "TRmWorkprocProductValue")
    @PostMapping(value = "/")
    public RESTfulResult add(@RequestBody Map<String,Object> maps){
        //获取产品编号
        String productid =   (String)maps.get("productid");
        //获取工序编号
        String  workprocid = (String)maps.get("workprocid");
        //获取项目类型
        String itemtype  =    (String)maps.get("itemtype");
       //获取时间
        String nowTime    =    (String )maps.get("clock");
        //获取时间粒度
        String timegranid = (String)maps.get("timegranid");
        String itemid = workprocid+productid+itemtype;
        String Compositekeys =itemid+itemtype+nowTime+timegranid;
        Set<String> byCompositekeys = tRmWorkprocProductValueService.getByCompositekeys();
        for (String byCompositekey : byCompositekeys) {
            if(byCompositekey.equals(Compositekeys)){
                return  failed(500,"该数据已经存在,请勿重复添加");
            }
        }
        //判断项目是否存在关联关系

        TRmWorkprocProduct tRmWorkprocProduct = tRmWorkprocProductService.getById(itemid);
        if(null == tRmWorkprocProduct){
            return  failed(500,"该数据请先配置关联关系");
        }
        //获取计算值
        String  actualvalue = (String)maps.get("actualvalue");

        TRmWorkprocProductValue tRmWorkprocProductValue = new TRmWorkprocProductValue();
        //获取用户id
        String userid = (String)maps.get("userid");


        tRmWorkprocProductValue.setItemid(itemid);
        tRmWorkprocProductValue.setTimegranid(timegranid);
        tRmWorkprocProductValue.setItemtype(itemtype);
        tRmWorkprocProductValue.setClock(nowTime);
        tRmWorkprocProductValue.setActualvalue(new BigDecimal(actualvalue));
        tRmWorkprocProductValue.setSumvalue(new BigDecimal("0"));
        tRmWorkprocProductValue.setCorrectvalue(new BigDecimal("0"));
        tRmWorkprocProductValue.setApportvalue(new BigDecimal(actualvalue));
        tRmWorkprocProductValue.setUserid(userid);
        tRmWorkprocProductValue.setBz("手动增加"+DateUtils.dateStr(new Date(),"yyyy-MM-dd HH:mm:ss"));
        TRmWorkprocProductValue tRmWorkprocProductvalue = tRmWorkprocProductValueService.insert(tRmWorkprocProductValue);
        logger.info("用户id为"+tRmWorkprocProductvalue.getUserid() + "在时间为"+DateUtils.dateStr(new Date(),"yyyy-MM-dd HH:mm:ss") + "进行了增加操作!!!");
        return success(tRmWorkprocProductValue);
    }

    @ApiOperation(value="获取详细信息", notes="根据主键(itemid, clock, timegranid, itemtype)来指定对象")
    @ApiImplicitParam(paramType = "path", name = "id", value = "ID", required = true, dataType = "String")
    //@RequiresPermissions("trmworkprocproductvalue:view")
    @PostMapping(value = "/info", produces  = "application/json;charset=UTF-8")
    public RESTfulResult get(@RequestBody TRmWorkprocProductValue model){
        if(model.getClock() == null || model.getClock().isEmpty()){
            return failed(null, "请传入时间");
        }
        if(model.getTimegranid() == null || model.getTimegranid().isEmpty()){
            return failed(null, "请传入时间粒度");
        }
        if(model.getItemid() == null || model.getItemid().isEmpty()){
            return failed(null, "请传入项目编号");
        }
        if(model.getItemtype() == null || model.getItemtype().isEmpty()){
            return failed(null, "请传入数据类型");
        }
        HashMap<String, Object> m = new HashMap<String, Object>();
        m.put("clock", model.getClock());
        m.put("timegranid", model.getTimegranid());
        m.put("itemid", model.getItemid());
        m.put("itemtype", model.getItemtype());
        model.setId(m);
        TRmWorkprocProductValue tRmWorkprocProductValue = tRmWorkprocProductValueService.getById(m);
        return success(tRmWorkprocProductValue);
    }

    @ApiOperation(value="更新详细信息", notes="根据主键(itemid, itemtype, clock, timegranid)来指定更新对象，并根据传过来的tRmWorkprocProductValue信息来更新详细信息")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "tRmWorkprocProductValue", value = "详细实体tRmWorkprocProductValue", required = true, dataType = "TRmWorkprocProductValue")
    })
    //@RequiresPermissions("trmworkprocproductvalue:update")
    @PutMapping(value = "/updateForUKey/", produces  = "application/json;charset=UTF-8")
    public RESTfulResult update(@RequestBody TRmWorkprocProductValue model){
    	if (model == null) {
    		return failed(null, "请传入主键参数");
    	}
    	if (model.getItemid()== null || model.getItemid().isEmpty()) {
    		return failed(null, "请传入主键参数itemid");
    	}
    	if (model.getItemtype()== null || model.getItemtype().isEmpty()) {
    		return failed(null, "请传入主键参数itemtype");
    	}
    	if (model.getClock() == null || model.getClock().isEmpty()) {
    		return failed(null, "请传入主键参数clock");
    	}
    	if (model.getTimegranid() == null || model.getTimegranid().isEmpty()) {
    		return failed(null, "请传入主键参数timegranid");
        }
        HashMap<String, Object> m = new HashMap<String, Object>();
        m.put("clock", model.getClock());
        m.put("timegranid", model.getTimegranid());
        m.put("itemid", model.getItemid());
        m.put("itemtype", model.getItemtype());
        logger.info("T_RM_WORKPROC_PRODUCT_VALUE表的数据发生修改:");
        logger.info("修改前数据是" + tRmWorkprocProductValueService.getById(m).toString());
        model.setUpman(JwtUtil.getUseridByToken());
        model.setUptime(DateUtils.getCurrentTimetoDate("yyyy-MM-dd HH:mm:ss"));
        TRmWorkprocProductValue tRmWorkprocProductValue = tRmWorkprocProductValueService.updateForUKey(model);
        logger.info("修改后数据是" + tRmWorkprocProductValue.toString());
        return success(tRmWorkprocProductValue);
    }

    @ApiOperation(value="批量更新详细信息", notes="根据传过来的usageData数组信息来更新详细信息")
    @ApiImplicitParam(name = "usageData", value = "详细实体usageData", required = true, dataType = "usageData")
    @PutMapping(value = "/batchUpdate", produces  = "application/json;charset=UTF-8")
    public RESTfulResult batchupdate(@RequestBody TRmWorkprocProductValue[] model){
        for (int i = 0; i < model.length; i++) {
            TRmWorkprocProductValue model1 = model[i];
            if (model1==null){
                return failed(null, "请传入主键参数");
            }
            TRmWorkprocProductValue tRmWorkprocProductValue =tRmWorkprocProductValueService.updateForUKey(model1);
        }
//        int failnum = 0;
//        ArrayList<String> failmsgs = new ArrayList<String>();
//        String userId = JwtUtil.getUseridByToken();
//        for(int i = 0;i < model.length;i++){
//            HashMap<String, Object> m = new HashMap<String, Object>();
//            m.put("clock", model[i].getClock());
//            m.put("timegranid", model[i].getTimegranid());
//            m.put("itemid", model[i].getItemid());
//            m.put("itemtype", model[i].getItemtype());
//            m.put("correctvalue",model[i].getCorrectvalue());
//            try {
//                logger.info("T_RM_WORKPROC_PRODUCT_VALUE表的数据发生修改(操作人ID：" + userId + "):");
//                logger.info("修改前数据是" + tRmWorkprocProductValueService.getById(m).toString());
//                model[i].setUpman(userId);
//                model[i].setUptime(DateUtils.getCurrentTimetoDate("yyyy-MM-dd HH:mm:ss"));
//                TRmWorkprocProductValue usageData = tRmWorkprocProductValueService.updateForUKey(model[i]);
//                logger.info("修改后数据是" + usageData.toString());
//            }
//            catch(Exception e){
//                failnum++;
//                failmsgs.add(m.toString());
//                logger.error("T_RM_WORKPROC_PRODUCT_VALUE表的数据修改出现错误,错误原因是" + e + ",id是" + m.toString());
//            }
//        }
//        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("trmworkprocmaterialvalue:delete")
    @DeleteMapping(value = "/delete", produces  = "application/json;charset=UTF-8")
    public RESTfulResult delete(@RequestBody TRmWorkprocProductValue model){
        if(model.getUserid().equals("1")){
            return  failed("该项目来源于mes,无法进行删除！！！");
        }
        if(model.getClock() == null || model.getClock().isEmpty()){
            return failed(null, "请传入时间");
        }
        if(model.getTimegranid() == null || model.getTimegranid().isEmpty()){
            return failed(null, "请传入时间粒度");
        }
        if(model.getItemid() == null || model.getItemid().isEmpty()){
            return failed(null, "请传入项目编号");
        }
        HashMap<String, Object> m = new HashMap<String, Object>();
        m.put("clock", model.getClock());
        m.put("timegranid", model.getTimegranid());
        m.put("itemid", model.getItemid());
        m.put("itemtype",model.getItemtype());
        model.setId(m);
        logger.info("T_RM_WORKPROC_PRODUCT_VALUE表的数据发生了删除(操作人ID：" + JwtUtil.getUseridByToken() + "):");
        logger.info("删除的数据是" + tRmWorkprocProductValueService.getById(m).toString());
        tRmWorkprocProductValueService.delete(m);
        return success();
    }

    @ApiOperation(value="批量删除", notes="根据url的id来指定删除对象")
    @ApiImplicitParam(paramType = "path", name = "id", value = "ID", required = true, dataType = "String")
    @DeleteMapping(value = "/batchDel")
    public RESTfulResult batchDel(@RequestBody TRmWorkprocProductValue[] model){
        int failnum = 0;
        ArrayList<String> failmsgs = new ArrayList<String>();
        String userId = JwtUtil.getUseridByToken();
        for(int i = 0;i < model.length;i++){
            HashMap<String, Object> m = new HashMap<String, Object>();
            m.put("clock", model[i].getClock());
            m.put("timegranid", model[i].getTimegranid());
            m.put("itemid", model[i].getItemid());
            m.put("itemtype", model[i].getItemtype());
            if(model[i].getUserid().equals("1")){
                failnum++;
                failmsgs.add(m.toString());
                logger.info(tRmWorkprocProductValueService.getById(m).toString() + "是来自mes的数据，不允许删除。");
                break;
            }
            try {
                logger.info("USAGE_DATA表的数据发生了删除(操作人ID：" + userId + "):");
                logger.info("删除的数据是" + tRmWorkprocProductValueService.getById(m).toString());
                tRmWorkprocProductValueService.delete(m);
            }
            catch(Exception e){
                failnum++;
                failmsgs.add(m.toString());
                logger.error("T_RM_WORKPROC_PRODUCT_VALUE表的数据修改出现错误,错误原因是" + e + ",id是" + m.toString());
            }
        }
        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 ="查询时间粒度,时间,产品,工序获取数据(能源计划管理-计划项目数据维护)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "查询页数", required = false, dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "每页记录数", required = false, dataType = "Integer")
      })
    @GetMapping("/getWorkprocProductValues")
    public RESTfulResult getWorkprocProductValues(@RequestParam HashMap<String, Object> parmas,Integer pageNum, Integer pageSize){
    	if(parmas.containsKey("productid") && parmas.get("productid") != null && !"".equals(parmas.get("productid").toString())){
            String productid = parmas.get("productid").toString();
            if(productid.indexOf(",") == -1){
                parmas.put("productid", "and TWM.productid = '" + productid + "'");
            } else {
            	productid = "and TWM.productid in ('" + productid.replaceAll(",", "','") + "')";
                parmas.put("productid", productid);
            }
        }
    	
    	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 TWM.workprocid = '" + workprocid + "'");
            } else {
            	workprocid = "and TWM.workprocid in ('" + workprocid.replaceAll(",", "','") + "')";
                parmas.put("workprocid", workprocid);
            }
        }
    	
        PageList<Map<String, Object>> workprocProductValueForPage = tRmWorkprocProductValueService.getWorkprocProductValueForPage(parmas, pageNum, pageSize);
        return  success(workprocProductValueForPage);
    }

    @ApiOperation(value="立即获取MES产品信息", notes="将IF_MES_EMS_SWAPFILE中未读取的数据进行处理，将数据保存至T_RM_WORKPROC_MATERIAL_VALUE")
    @GetMapping(value = "/synchronousData")
    public RESTfulResult synchronousData(){
        tRmWorkprocProductValueService.synchronousData();
        return success();
    }

    @ApiOperation(value="立即获取MES计划产品信息", notes="将IF_MES_EMS_PRODUCTORDER中未读取的数据进行处理，将数据保存至T_RM_WORKPROC_MATERIAL_VALUE")
    @GetMapping(value = "/synchronousOrderData")
    public RESTfulResult synchronousOrderData(){
        tRmWorkprocProductValueService.synchronousOrderData();
        return success();
    }

    @GetMapping("/getDate")
    public  RESTfulResult getDate(){
        tRmWorkprocProductValueService.setDate(new Date());
        return success();
    }
    
    @GetMapping("/createMRData")
	public RESTfulResult createMRData(@RequestParam HashMap<String,Object> parmas) {
    	if (parmas == null) {
    		return failed(null, "请传入参数");
    	}
		if (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("itmegranidSource")==null || parmas.get("itmegranidSource").toString().isEmpty()) {
    		return failed(null, "请传入时间来源");
    	}
		String timegranid = parmas.get("timegranid").toString();
		String clock = parmas.get("clock").toString();
		String itmegranidSource = parmas.get("itmegranidSource").toString();
    	tRmWorkprocProductValueService.createRData(timegranid,clock,itmegranidSource);
		return success();
	}
    
    @GetMapping("/restatAllRData1")
    public  RESTfulResult getDate(@RequestParam HashMap<String,Object> parmas){
    	if (parmas == null) {
    		return failed(null, "请传入参数");
    	}
		if (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, "请传入时间");
    	}
		String timegranid = parmas.get("timegranid").toString();
		String clock = parmas.get("clock").toString();
        tRmWorkprocProductValueService.restatAllRData1(clock, timegranid);
        return success();
    }
    
    @ApiOperation(value="重新计算或生成项目数据-(月、年)")
    @GetMapping(value = "/restatWpv")
    public RESTfulResult restatWpv(@RequestParam HashMap<String, Object> parmas, String clock, String clocke, String timegranid){
		if (clock==null || clock.isEmpty()) {
    		return failed(null, "请传入起始时间");
    	}
		if (timegranid==null || timegranid.isEmpty()) {
    		return failed(null, "请传入时间粒度");
    	}
		parmas.put("useflag", "1");
		ifMesEmsSwapfileService.synchronousMesAnEmsData();
		tRmWorkprocProductValueService.synchronousData();
		tRmWorkprocProductValueService.synchronousOrderData();
		// 查询需要统计的项目
		List<TRmWorkprocProduct> l = tRmWorkprocProductMapper.selectByParameters(parmas);
		String res = "";
		for(int i = 0; i<l.size(); i++){
			TRmWorkprocProduct t = l.get(i);
			res = formulaService.reItemVal(t.getItemid(),clock,timegranid,clocke);
		}
		if(!res.isEmpty()){
			return failed(null, res);
		}
        return success();
    }
    
    @ApiOperation(value="批量重新计算", notes="")
    @ApiImplicitParam(name = "TRmWorkprocProductValue", value = "详细实体TRmWorkprocProductValue", required = true, dataType = "TRmWorkprocProductValue")
    @PutMapping(value = "/batchCompute", produces  = "application/json;charset=UTF-8")
    public RESTfulResult batchCompute(@RequestBody TRmWorkprocProductValue[] model){
    	if(model.length<1){
    		return failed(null, "请勾选数据");
    	}
    	for (int i = 0; i< model.length; i++) {
    		TRmWorkprocProductValue tv = model[i];
    		tRmWorkprocProductValueService.restatData(tv.getItemid(), tv.getClock(), tv.getTimegranid());
    	}
    	return success();
    }
}
