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

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.common.DateTypeEnum;
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.trmworkprocproductvalue.service.ITRmWorkprocProductValueService;
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.trmbalancevalue.model.TRmBalanceValue;
import com.steerinfo.ems.trmbalancevalue.mapper.TRmBalanceValueMapper;
import com.steerinfo.ems.trmbalancevalue.service.ITRmBalanceValueService;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import com.steerinfo.rtdb.logging.Logger;
import com.steerinfo.rtdb.logging.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

    @Override
    protected IBaseMapper<TRmBalanceValue, HashMap<String, Object>> getMapper() {
        return tRmBalanceValueMapper;
    }
    @Autowired
    private ITRmActItemService tRmActItemService;

    @Autowired
    private IFormulaService formulaService;
    @Autowired
    private ITRmWorkprocProductValueService tRmWorkprocProductValueService;

    @Override
	public PageList<Map<String, Object>> getBalanceitemForPage(Map<String, Object> parameters, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Map<String, Object>> rows = tRmBalanceValueMapper.getBalanceitemList(parameters);
        PageList<Map<String, Object>> pageInfo = new PageList<Map<String, Object>>(rows);
        return pageInfo;
    }

    @Override
    public void state(){
    	//获取平衡项目
        List<TRmActItem> bs = tRmActItemService.getitems("B");
        Calendar c = Calendar.getInstance();
        c.add(Calendar.DAY_OF_YEAR, -1); // 减1天昨天
        String clockd = new SimpleDateFormat("yyyy-MM-dd").format(c.getTime());
        c.add(Calendar.DAY_OF_YEAR, 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());
        c.add(Calendar.YEAR, 1); // 回到现在
        // 生成昨日数据
 		for (TRmActItem tRmActItem : bs) {
 			if(tRmActItem.getMintimegranid().equalsIgnoreCase("DAY")) {
 				this.restatData(tRmActItem.getItemid(), clockd, "DAY");
 			}
 		}
 		// 每月前3天生成上月数据
		if(c.get(Calendar.DAY_OF_MONTH) <= 3){
			for (TRmActItem tRmActItem : bs) {
				if(TimegranidUtils.getTimegranidList(tRmActItem.getMintimegranid()).contains("MONTH")){
					this.restatData(tRmActItem.getItemid(), clockm, "MONTH");
				}
			}
		}
		// 每年前3天生成去年数据
		if(c.get(Calendar.DAY_OF_YEAR) <= 3){
			for (TRmActItem tRmActItem : bs) {
				this.restatData(tRmActItem.getItemid(), clocky, "YEAR");
			}
		}
		logger.info("平衡维护数据定时任务结束....");
    }
    
	@Override
	public TRmBalanceValue updateForUKey(TRmBalanceValue tRmBalanceValue) {
        this.getMapper().updateByPrimaryKeySelective(tRmBalanceValue);
        return tRmBalanceValueMapper.selectByUPrimaryKey(tRmBalanceValue);
	}

    @Override
    public List<Map<String, Object>> getBalanceitemList(Map<String, Object> parameters) {
        return tRmBalanceValueMapper.getBalanceitemList(parameters);
    }

    public Double getSumvalue(String clock,String itemid) {
    	HashMap<String, Object>maps = new HashMap<String, Object>();
    	 maps.put("clock", clock);
    	 maps.put("itemid", itemid);
    	 Double sumvalue = tRmBalanceValueMapper.getSumvalue(maps);
    	 if(null == sumvalue) {
    		 return 0.0;
    	 }
    	 return sumvalue;
    }

	@Override
	public List<Map<String, Object>> getItem(HashMap<String, Object> parameters) {
		// TODO Auto-generated method stub
		return tRmBalanceValueMapper.getItem(parameters);
	}

	@Override
	public String restatData(String itemid, String clock, String timegranid) {
		if(!itemid.endsWith("B")){
			return "项目编号错误";
		}
		TRmActItem t = tRmActItemService.getById(itemid);
		if(t!=null){
			Short digits = t.getDigits() == null ? 2 : t.getDigits();
			HashMap<String, Object> id = new HashMap<String, Object>();
    		id.put("clock", clock);
    		id.put("timegranid", timegranid);
    		id.put("itemid", itemid);
            // 计算值
            Double actualvalue = 0d;
            if(!TimegranidUtils.getTimegranidList(t.getMintimegranid()).contains(timegranid.toUpperCase())){
            	return "时间粒度错误";
            }else if(t.getMintimegranid().equalsIgnoreCase(timegranid)){
            	actualvalue = formulaService.getValByItemid(t.getItemid(), timegranid, clock, 0);
			}else{
            	// 此时计算值为小粒度累加
            	HashMap<String, Object> maps = new HashMap<>();
            	if(timegranid.equalsIgnoreCase("MONTH")){
    	            maps.put("itemid", itemid);
    	            maps.put("clock", clock);
    	            maps.put("timegranid", "DAY");
            	}else if(timegranid.equalsIgnoreCase("YEAR")){
            		maps.put("itemid", itemid);
    	            maps.put("clock", clock);
    	            maps.put("timegranid", "MONTH");
            	}
            	actualvalue = tRmBalanceValueMapper.getSumvalue(maps);
            }
            // 折标系数
            Double zbxs = formulaService.getValByItemid(t.getEnergyid(),timegranid, clock, 0);
            if (zbxs==null){
                zbxs=0.0;
            }
            Map<String, BigDecimal> dh = tRmWorkprocProductValueService.getOutPut(t.getWorkprocid(), clock, timegranid,"R");
            //实绩产量
            Double  sjcl  = dh.get("SJCL").doubleValue();
            //累计产量
            //Double  ljcl = dh.get("LJCL").doubleValue();
            try{
	    		// 数据是否已存在
	    		TRmBalanceValue tv = tRmBalanceValueMapper.selectByPrimaryKey(id);
	    		if(tv!=null){
		            tv.setActualvalue(new BigDecimal(actualvalue));
		            tv.setApportvalue(BigDecimalUtil.add(tv.getCorrectvalue()!=null?tv.getCorrectvalue().doubleValue():0d, actualvalue).setScale(digits, BigDecimal.ROUND_HALF_UP));
		            // 折标值
		            tv.setStdvalue(BigDecimalUtil.mul(zbxs, actualvalue).setScale(digits, BigDecimal.ROUND_HALF_UP));
		            //单耗值
		            tv.setUcvalue(BigDecimalUtil.divide(actualvalue, sjcl, digits.intValue()));
		            tv.setUptime(DateUtils.dateStr(new Date(),"yyyy-MM-dd HH:mm:ss"));
		            tv.setUserid(JwtUtil.getUseridByToken());
		            tRmBalanceValueMapper.updateByPrimaryKeySelective(tv);
	    		}else{
	    			tv = new TRmBalanceValue();
	    			tv.setItemid(itemid);
	    			tv.setClock(clock);
	    			tv.setTimegranid(timegranid);
		            //计算值
	    			tv.setActualvalue(new BigDecimal(actualvalue));
		            //修正值
	    			tv.setCorrectvalue(new BigDecimal(0));
		            //最终值
	    			tv.setApportvalue(new BigDecimal(actualvalue));
		            //折标值
	    			tv.setStdvalue(BigDecimalUtil.mul(zbxs, actualvalue).setScale(digits, BigDecimal.ROUND_HALF_UP));
		            //单耗值
	    			tv.setUcvalue(BigDecimalUtil.divide(actualvalue, sjcl, digits.intValue()));
	    			tv.setRecTime(DateUtils.dateStr(new Date(),"yyyy-MM-dd HH:mm:ss"));
	    			tv.setCrman(JwtUtil.getUseridByToken());
		            //修改次数
		            // trm.setModifyflag(new Short("0"));
		            tRmBalanceValueMapper.insert(tv);
	    		}
            } catch (Exception e) {
				logger.error("平衡数据计算错误：itemid-" + itemid + ",clock-" + clock);
				logger.error("--:" + e.getMessage());
				e.printStackTrace();
			}
		}
		return null;
	}
	
	@Override
	public int getCount(Map<String, Object> params) {
		return tRmBalanceValueMapper.getCount(params);
	}

}
