package com.steerinfo.ems.trmdfvalue.service.impl;

import com.steerinfo.framework.mapper.IBaseMapper;
import com.steerinfo.framework.service.impl.BaseServiceImpl;
import com.steerinfo.framework.service.pagehelper.PageHelper;
import com.steerinfo.framework.service.pagehelper.PageList;
import com.steerinfo.ems.trmdfvalue.model.TRmDfValue;
import com.steerinfo.auth.utils.JwtUtil;
import com.steerinfo.ems.Utils.BigDecimalUtil;
import com.steerinfo.ems.Utils.DateUtils;
import com.steerinfo.ems.Utils.TimegranidUtils;
import com.steerinfo.ems.formula.model.Formula;
import com.steerinfo.ems.formula.service.IFormulaService;
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.trmactvalue.service.impl.TRmActValueServiceImpl;
import com.steerinfo.ems.trmdfvalue.mapper.TRmDfValueMapper;
import com.steerinfo.ems.trmdfvalue.service.ITRmDfValueService;
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.model.TRmIndexValue;
import com.steerinfo.ems.trmindexvalue.service.ITRmIndexValueService;
import com.steerinfo.ems.trmworkprocproductvalue.service.ITRmWorkprocProductValueService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

import java.math.BigDecimal;
import java.text.SimpleDateFormat;

/**
 * TRmDfValue服务实现：
 * @author generator
 * @version 1.0-SNAPSHORT 2020-10-30 10:34
 * 类描述
 * 修订历史：
 * 日期：2020-10-30
 * 作者：generator
 * 参考：
 * 描述：TRmDfValue服务实现
 * @see null
 * @Copyright 湖南视拓信息技术股份有限公司. All rights reserved.
 */
@Service(value = "tRmDfValueService")
public class TRmDfValueServiceImpl extends BaseServiceImpl<TRmDfValue, HashMap<String, Object>> implements ITRmDfValueService {
	
	private static final Logger logger = LoggerFactory.getLogger(TRmActValueServiceImpl.class);

    @Autowired
    private TRmDfValueMapper tRmDfValueMapper;
    @Autowired
    private ITRmActItemService tRmActItemService;
    @Autowired
    private IFormulaService formulaService;
    @Autowired
    ITRmIndexItemService tRmIndexItemService;
    @Autowired
    ITRmIndexValueService tRmIndexValueService;
    @Autowired
    private TRmIndexItemMapper tRmIndexItemMapper;
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    protected IBaseMapper<TRmDfValue, HashMap<String, Object>> getMapper() {
        return tRmDfValueMapper;
    }
    
	@Override
	public PageList<Map<String, Object>> getProjectwDataForPage(HashMap<String, Object> parmas, Integer pageNum,
			Integer pageSize) {
		PageHelper.startPage(pageNum, pageSize);
        List<Map<String, Object>> actitemDetalts = tRmDfValueMapper.getProjectwData(parmas);
        PageList<Map<String,Object>> plist = new PageList<Map<String,Object>>(actitemDetalts);
        return plist;
	}
	
	@Override
	public void state(Date d) {
    	// 获取上报项目
        List<TRmActItem> wt = tRmActItemService.getitems("F");
        Calendar c = Calendar.getInstance();
        c.setTime(d);
        c.add(Calendar.DAY_OF_MONTH, -1);
        String clockd = new SimpleDateFormat("yyyy-MM-dd").format(c.getTime());
        c.add(Calendar.DAY_OF_MONTH,  1);
        c.add(Calendar.MONTH, -1); // 减1月获得上月
        String clockm = new SimpleDateFormat("yyyy-MM").format(c.getTime());
        c.add(Calendar.MONTH, 1); // 回到当前月
        c.add(Calendar.YEAR, -1); // 去年
        String clocky = new SimpleDateFormat("yyyy").format(c.getTime());
        // 每日9，10生成前1天生成上月数据
     	if(c.get(Calendar.HOUR_OF_DAY) == 9 || c.get(Calendar.HOUR_OF_DAY) == 0){
     		for (TRmActItem tRmActItem : wt) {
     			this.restatData(tRmActItem.getItemid(), clockd, "DAY", "系统", null, "");
     		}
     	}
 		// 每月前3天生成上月数据
		if(c.get(Calendar.DAY_OF_MONTH) <= 3){
			for (TRmActItem tRmActItem : wt) {
				this.restatData(tRmActItem.getItemid(), clockm, "MONTH", "系统", null, "");
			}
		}
		// 每年前3天生成去年数据
		if(c.get(Calendar.DAY_OF_YEAR) <= 3){
			for (TRmActItem tRmActItem : wt) {
				this.restatData(tRmActItem.getItemid(), clocky, "YEAR", "系统", null, "");
			}
		}
		logger.info("财务数据定时任务结束....");
	}
	
	@Override
	public String restatData(String itemid, String clock, String timegranid, String opuser, Double dwcl, String bz) {
		if(!itemid.endsWith("F")){
			return "项目编号错误";
		}
		TRmActItem t = tRmActItemService.getById(itemid);
		if(t!=null){
			Integer zh = t.getDefaultvalue()==null || t.getDefaultvalue()==0?1:t.getDefaultvalue(); // 单位转换系数（除法），上报最终值转换单位
			Short digits = t.getDigits() == null ? 2 : t.getDigits();
			int digits2 = digits < 3 ? 3 : digits; // 单耗精度最少为3
			HashMap<String, Object> id = new HashMap<String, Object>();
    		id.put("clock", clock);
    		id.put("timegranid", timegranid);
    		id.put("itemid", itemid);
    		// 关联能耗编号
    		String assid = t.getAssociateid();
    		// 系统最终值
    		Double apval = null;
    		// 系统最终值-换算
    		BigDecimal apportvalue = null;
    		// 财务上报值
    		BigDecimal apportwvalue = null;
    		// 系统折标值
    		BigDecimal stdvalue = null;
    		//指标项目特殊处理
    		String eneryIdSource = "Y181";
    		String eneryIdDest = t.getEnergyid();
    		// 公式内容
			String fs = formulaService.getFormula(itemid, clock);
			if(fs==null){
				return "公式错误";
			}
			// 系统最终值
    		if(assid!=null && !assid.isEmpty()){
                apval = formulaService.readValByItemid(assid,timegranid, clock, 0);
                // 系统折标值读取
				// Double std = formulaService.readValByItemid(assid,timegranid,
				// clock, 2);
				// if(std!=null){
				// stdvalue = new BigDecimal(std).setScale(digits,
				// BigDecimal.ROUND_HALF_UP);
				// }
    		}
			
    		
    		// 系统产品产量
    		Double pval=null;
    		// 系统产品产量-精度
    		BigDecimal productvalue = null;
    		BigDecimal ucvalue = null;
    		
    		if(eneryIdDest != null && eneryIdSource.equalsIgnoreCase(eneryIdDest)) {  //指标项目
    			String clocknew = clock;
    			String timegranidNew = timegranid;
    			if(timegranid.equalsIgnoreCase("DAY")) {
    				clocknew = clock.substring(0,7);
    				timegranidNew = "MONTH";
    			}
    			
    			String zbID = t.getFid();
    			
    			if(zbID != null && zbID.isEmpty() == false) {
    				String sql = "SELECT a.APPORTVALUE FROM T_RM_INDEX_VALUE a" +
  		                  " where a.itemid = '" + zbID + "'  and a.timegranid = '" + timegranidNew + "' and a.clock = '" + clocknew + "' order by a.clock";
    				
    				try {
        				//pval = jdbcTemplate.queryForObject(sql, Double.class);
        				Map<String, Object> map = jdbcTemplate.queryForMap(sql);
        				pval = Double.valueOf(map.get("APPORTVALUE").toString());
        			}catch(Exception e) {
        				pval = null;
        			}
        			if(pval != null) {
        				productvalue = new BigDecimal(pval);
        			}
        			
        			apportvalue = new BigDecimal(formulaService.getValByItemid(itemid, timegranid, clock, 0));
    			}
    		} else {
	    		//解决多个指标问题
				String fids = t.getFid(); 
				if(fids!=null && !fids.isEmpty()){
					if(fids.indexOf(',') >= 0) { 
						String fidArray[] = fids.split(",");
						Double pvalTmp = null;
						for(int i = 0; i< fidArray.length; i++) {
							if(fidArray[i] != null && !fidArray[i].isEmpty()) {
								pvalTmp = formulaService.readValByItemid(fidArray[i],timegranid, clock, 0);
								if(pvalTmp != null) {
									if(pval == null) {
										pval = pvalTmp;
									}else {
										pval += pvalTmp;
									}
								}
							}
						}
					}else {
						pval = formulaService.readValByItemid(fids,timegranid, clock, 0);
					}
					
					if(pval!=null){
						//productvalue = new BigDecimal(pval).setScale(0, BigDecimal.ROUND_HALF_UP);  //不处理精度问题
						productvalue = new BigDecimal(pval);
		            }
		            // 产量--系统最终值（等于产品产量）
		            if(assid==null || assid.isEmpty()){
		            	apval = pval;
		            }
				}
	    		
	    		
	    		// 系统单耗值
				/*
				 * BigDecimal ucvalue = null; if(pval!=null && apval!=null && pval!=0){ ucvalue
				 * = BigDecimalUtil.divide(apval, pval, digits2); }
				 */
	    		// 系统最终值-换算单位
	    		if(apval!=null){
	    			apportvalue = BigDecimalUtil.divide(apval, zh.doubleValue(), digits.intValue());
	    		}
    		}
    		
    		TRmDfValue tv = tRmDfValueMapper.selectByPrimaryKey(id);
			if(tv != null){
				// 系统最终值
				tv.setApportvalue(apportvalue);
	            // 系统折标值
	            tv.setStdvalue(stdvalue);
	            // 系统单耗值
	            tv.setUcvalue(ucvalue);
	            // 系统产品产量
	            tv.setProductvalue(productvalue);
	            //财务最终值，特定情况下修改
	            if(eneryIdDest != null && eneryIdSource.equalsIgnoreCase(eneryIdDest)) {
	            	tv.setApportwvalue(apportwvalue);
	            }
	            
				if(timegranid != "DAY") {
					tv.setApportwvalue(new BigDecimal(formulaService.getValByItemid(itemid, timegranid, clock, 0)));
				}
				tRmDfValueMapper.updateByPrimaryKeySelective(tv);
			}else{
				tv = new TRmDfValue();
				tv.setId(id);
				// 系统最终值
				tv.setApportvalue(apportvalue);
	            // 系统折标值
	            tv.setStdvalue(stdvalue);
	            // 系统单耗值
	            tv.setUcvalue(ucvalue);
	            // 系统产品产量
	            tv.setProductvalue(productvalue);
	            //财务最终值，特定情况下修改
	            if(eneryIdDest != null && eneryIdSource.equalsIgnoreCase(eneryIdDest))  {
	            	tv.setApportwvalue(apportwvalue);
	            }
	            tv.setCreateman(opuser);
	            tv.setRecTime(DateUtils.dateStr(new Date(),"yyyy-MM-dd HH:mm:ss"));
				tv.setUpuser(opuser);
				tv.setBz(bz);
				tv.setUptime(DateUtils.dateStr(new Date(),"yyyy-MM-dd HH:mm:ss"));
				if(timegranid != "DAY") {
					tv.setApportwvalue(new BigDecimal(formulaService.getValByItemid(itemid, timegranid, clock, 0)));
				}
				tRmDfValueMapper.insert(tv);
			}
			// 如果是产量变化，联动计算相关项目
			
			if(fs.startsWith("R")){
				formulaService.reCalculate(itemid, clock, timegranid, clock);
				// 产量确认，联动计算指标（根据波动关联对象fluitemid关联）
				Map<String, Object> m = new HashMap<String, Object>();
				m.put("useflag", "1");
				m.put("itemflag", "3");
		    	m.put("parentid", "NYDF001001");
				m.put("fluitemid", itemid);
				List<TRmIndexItem> l = tRmIndexItemMapper.selectByParasForFla(m);
				for(TRmIndexItem tii:l){
					tRmIndexValueService.restatData(tii.getItemid(), clock, timegranid, opuser);
				}
			}
			
		}
		return null;
	}

	@Override
	public void modifyByApv(TRmDfValue model) {
		TRmActItem t = tRmActItemService.getById(model.getItemid());
		// 上报产量
		BigDecimal productwvalue = model.getProductwvalue();
		// 上报最终值
		BigDecimal apportwvalue = model.getApportwvalue();
		// 单位换算
		Integer rate = t.getDefaultvalue()==null?1:t.getDefaultvalue();
		// 单耗
		BigDecimal ucwvalue = BigDecimalUtil.divide(BigDecimalUtil.mul(apportwvalue.doubleValue(), rate.doubleValue()).doubleValue(), productwvalue.doubleValue(), 6);
		model.setMftime(DateUtils.dateStr(new Date(),"yyyy-MM-dd HH:mm:ss"));
		model.setMfuser(JwtUtil.getUseridByToken());
		// 修改单耗指标数据与指标
		HashMap<String, Object> parmas = new HashMap<String, Object>();
    	parmas.put("energyid", t.getEnergyid());
    	parmas.put("workprocid", t.getWorkprocid());
    	parmas.put("propertyid", t.getPropertyid());
    	parmas.put("parentid", "NYDF001001");
    	
    	TRmIndexItem tii = tRmIndexItemService.getByParams(parmas);
    	int digits = 2;
    	if(tii!=null){
    		digits =  tii.getDigits()==null?2:tii.getDigits().intValue();
    		HashMap<String, Object> id = new HashMap<String, Object>();
    		id.put("clock", model.getClock());
    		id.put("timegranid", "MONTH");
    		id.put("itemid", tii.getItemid());
    		TRmIndexValue tv = tRmIndexValueService.getById(id);
    		if(tv!=null){
    			tv.setApportvalue(ucwvalue.setScale(digits, BigDecimal.ROUND_HALF_UP));
    			if(tv.getActualvalue()!=null){
    				tv.setCorrectvalue(ucwvalue.subtract(tv.getActualvalue()));
    			}
    			tv.setUpman(JwtUtil.getUseridByToken());
    			tv.setUptime(DateUtils.dateStr(new Date(),"yyyy-MM-dd HH:mm:ss"));
    			tRmIndexValueService.modify(tv);
    		}else{
    			tv = new TRmIndexValue();
    			tv.setId(id);
    			tv.setActualvalue(ucwvalue);
    			tv.setApportvalue(ucwvalue);
    			tv.setCorrectvalue(BigDecimal.ZERO);
    			tv.setRecTime(DateUtils.dateStr(new Date(),"yyyy-MM-dd HH:mm:ss"));
    			tv.setRecUser(JwtUtil.getUseridByToken());
    			tRmIndexValueService.add(tv);
    		}
    		// 如果是修改上月数据，增加或者修改公式
//    		Calendar c = Calendar.getInstance();
//    		c.add(Calendar.MONTH, -1);
//    		if(new SimpleDateFormat("yyyy-MM").format(c.getTime()).equals(model.getClock())){
//    			Formula f = formulaService.getFormulaLatest(tii.getItemid());
//    			String clk = model.getClock().split("-")[0] + model.getClock().split("-")[1];
//    			if(f!=null && f.getClock().equals(clk)){
//    				// 修改
//    				f.setSourcecode(ucwvalue.toPlainString());
//    				f.setRevisetime(DateUtils.getCurrentTime("yyyy-MM-dd HH:mm:ss"));
//    				f.setRevisor(JwtUtil.getUseridByToken());
//    				formulaService.modify(f);
//    			}else{
//    				// 新增公式
//    				f = new Formula();
//    				f.setClock(clk);
//    				f.setCode(tii.getItemid());
//    				f.setDescription(tii.getItemname());
//    				f.setSourcecode(ucwvalue.toPlainString());
//    				f.setIsavailable("1");
//    				f.setRevisetime(DateUtils.getCurrentTime("yyyy-MM-dd HH:mm:ss"));
//    				f.setTablename("T_RM_INDEX_VALUE");
//    				f.setRevisor(JwtUtil.getUseridByToken());
//    				formulaService.add(f);
//    			}
//    		}
    	}
    	model.setUcwvalue(ucwvalue.setScale(digits, BigDecimal.ROUND_HALF_UP));
    	tRmDfValueMapper.updateByPrimaryKeySelective(model);
	}
	
	@Override
	public int getCount(Map<String, Object> params) {
		return tRmDfValueMapper.getCount(params);
	}
}
