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

import com.steerinfo.framework.mapper.IBaseMapper;
import com.steerinfo.framework.service.impl.BaseServiceImpl;
import com.steerinfo.rtdb.Client;
import com.steerinfo.rtdb.ClientConfig;
import com.steerinfo.rtdb.ClientImpl;
import com.steerinfo.rtdb.SingleSocketChannelProviderImpl;
import com.steerinfo.rtdb.SocketChannelProvider;
import com.steerinfo.ems.emsetiming.model.EmsETiming;
import com.alibaba.fastjson.JSONObject;
import com.steerinfo.ems.Utils.EmsEAiUtil;
import com.steerinfo.ems.emseaihoursumtab1.mapper.EmsEAiHourSumTab1Mapper;
import com.steerinfo.ems.emseaihoursumtab1.model.EmsEAiHourSumTab1;
import com.steerinfo.ems.emseaihoursumtab1org.mapper.EmsEAiHourSumTab1OrgMapper;
import com.steerinfo.ems.emseaihoursumtab1org.model.EmsEAiHourSumTab1Org;
import com.steerinfo.ems.emsetiming.mapper.EmsETimingMapper;
import com.steerinfo.ems.emsetiming.service.IEmsETimingService;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * EmsETiming服务实现：
 * @author generator
 * @version 1.0-SNAPSHORT 2019-11-25 04:04
 * 类描述
 * 修订历史：
 * 日期：2019-11-25
 * 作者：generator
 * 参考：
 * 描述：EmsETiming服务实现
 * @see null
 * @Copyright 湖南视拓信息技术股份有限公司. All rights reserved.
 */
@Service(value = "emsETimingService")
public class EmsETimingServiceImpl extends BaseServiceImpl<EmsETiming, String> implements IEmsETimingService {

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

	@Autowired
    private EmsETimingMapper emsETimingMapper;

    @Autowired
    private EmsEAiHourSumTab1Mapper emsEAiHourSumTab1Mapper;

    @Autowired
    private EmsEAiHourSumTab1OrgMapper emsEAiHourSumTab1OrgMapper;

    @Override
    protected IBaseMapper<EmsETiming, String> getMapper() {
        return emsETimingMapper;
    }

    @Override
	@Transactional(rollbackFor=Exception.class)
	public void getData() {
    	logger.info(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "-计量点电数据定时获取任务执行开始");
		ClientConfig config = new ClientConfig();
		config.username = "guest";
    	config.password = "";
    	// 需要新增的对象
    	Map<String,EmsETiming> ins = new HashMap<String,EmsETiming>();
    	// 需要修改的对象
    	Map<String,EmsETiming> ups = new HashMap<String,EmsETiming>();
    	// 从数据库查询过的对象
    	Map<String,EmsETiming> ss = new HashMap<String,EmsETiming>();
    	try {
    		SocketChannelProvider socketChannel = new SingleSocketChannelProviderImpl("172.16.100.139:2013");
    		Client client = new ClientImpl(socketChannel, config);
			List<ArrayList> res1 = (List<ArrayList>) client.syncOps().call("db.space.Live:select", Collections.emptyList());
			List l = res1.get(0);
			client.close();
			logger.info("获得数值长度" + l.size());
			if(l!=null && l.size()>0){
				for(int i = 0;i<l.size();i++){
					String s = l.get(i).toString();
					//['device/iec102-56-202/8101/totalpower', '{"反向有功":0,"容性无功":0.66,"感性无功":6841.85,"正向有功":11540.54}',    1612751060, '21-02-08 10:16:01']
					String head = s.substring(1,s.indexOf(","));//device/iec102-56-202/8214/totalpower
					String line = "";
					if(head.split("/").length!=4){
						logger.error(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "-数据格式错误");
						return;
					}
					if(head.split("/")[1].endsWith("13-200")){
						line = "1";
					}else if(head.split("/")[1].endsWith("56-201")){
						line = "2";
					}else if(head.split("/")[1].endsWith("56-202")){
						line = "3";
					}else if(head.split("/")[1].endsWith("32-158")){
						line = "4";
					}else if(head.split("/")[1].endsWith("42-158")){
						line = "5";
					}else if(head.split("/")[1].endsWith("42-159")){
						line = "6";
					}else if(head.split("/")[1].endsWith("42-160")){
						line = "7";
					}else{
						continue;
					}
					String code = line + head.split("/")[2];
					if(head.endsWith("totalpower")){
						String tim = "20" + s.substring(s.length()-18,s.length()-1);
						Date d = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(tim);
						Calendar cal = Calendar.getInstance();
						cal.setTime(d);
						cal.set(Calendar.SECOND, 0);
						int mimute = (cal.get(Calendar.MINUTE) + 1)/15 * 15;
						cal.set(Calendar.MINUTE, mimute);
						String clock = new SimpleDateFormat("yyyy-MM-dd HH:mm").format(cal.getTime());
						String val = s.substring(s.indexOf("{"),s.indexOf("}") + 1);
						JSONObject jo = JSONObject.parseObject(val);
						EmsETiming e;
						// 是否已经查找过该对象
						if(ss.containsKey(clock)){
							e = ss.get(clock);
						}else{
							e = emsETimingMapper.selectByPrimaryKey(clock);
						}
						if (e == null) {
							if(!ss.containsKey(clock)){
								ss.put(clock, null);
							}
							if(ins.containsKey(clock)){
								e = ins.get(clock);
							}else{
								e = new EmsETiming();
								e.setInsertTime(new Date());
								e.setClock(clock);
								ins.put(clock, e);
							}
						}else{
							if(!ss.containsKey(clock)){
								ss.put(clock, e);
							}
							Date dt = new SimpleDateFormat("yyyy-MM-dd HH:mm").parse(clock);
							dt.setTime(dt.getTime() + 3600*1000);
							// 1小时之前的已有时间数据不加入更新
							if(new Date().after(dt)){
								continue;
							}
							if(ups.containsKey(clock)){
								e = ups.get(clock);
							}else{
								ups.put(clock, e);
							}
						}
						e.setVal(code, jo.getString("正向有功"), "f");
						e.setVal(code, jo.getString("反向有功"), "r");
					}
				}
			}
			// 新增
			for(EmsETiming ee : ins.values()){
				emsETimingMapper.insert(ee);
			}
			// 更新
			for(EmsETiming ee : ups.values()){
				emsETimingMapper.updateByPrimaryKeySelective(ee);
			}
			// 1小时30分钟后，更新前一小时表数据(采集器有延时)
			Calendar cal = Calendar.getInstance();
			int minute = cal.get(Calendar.MINUTE);
			if(minute>=30){
				// 2019-11-20 09
				String clke = new SimpleDateFormat("yyyy-MM-dd HH").format(cal.getTime());
				cal.add(Calendar.HOUR_OF_DAY, -1);
				// 2019-11-20 08
				String clk = new SimpleDateFormat("yyyy-MM-dd HH").format(cal.getTime());
				EmsEAiHourSumTab1 eh = emsEAiHourSumTab1Mapper.selectByPrimaryKey(clk);
				if (eh==null){
					// String minuClock = clk+":00"; // 2019-11-20 08:00
					String minuClocke = clke+":00"; // 2019-11-20 09:00
					// 从EMS_E_TIMING读取小时准点值
					Map<String, Object> mp = emsETimingMapper.getHourPointVal(minuClocke);
					// 整点数据
					EmsEAiHourSumTab1Org eeho = new EmsEAiHourSumTab1Org();
                    if(mp!=null && mp.size()>0){
                        eeho.setClock(clke);
                        eeho.setInsertTime(new Date());
                        eeho = EmsEAiUtil.setValByMap(eeho, mp);
                        emsEAiHourSumTab1OrgMapper.insert(eeho);
                    }
					// 小时累计值 = 当前小时准点值 - 前1小时小时准点值
					EmsEAiHourSumTab1Org eehol = emsEAiHourSumTab1OrgMapper.selectByPrimaryKey(clk);
					if(eehol==null || eehol.getClock()==null || eehol.getClock().isEmpty() || eeho.getClock()==null || eeho.getClock().isEmpty()){
						logger.error("数据表EMS_E_AI_HOUR_SUM_TAB1_ORG缺少数据：" + clk);
					}else{
						EmsEAiHourSumTab1 eeh = new EmsEAiHourSumTab1();
						eeh.setClock(clk);
						eeh.setInsertTime(new Date());
						eeh = EmsEAiUtil.setVal(eeh, eeho, eehol);
						emsEAiHourSumTab1Mapper.insert(eeh);
					}
                }
            }
            logger.info(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "-计量点电数据定时获取任务执行完毕");
            // System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "-计量点电数据定时获取任务执行完毕");
        } catch (Exception e) {
            //e.printStackTrace();
            throw new RuntimeException("出错了:" + e.getMessage());
        }
    }
}