package com.gyee.wisdom.backwork;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.gyee.wisdom.common.data.timeseries.*;
import com.gyee.wisdom.dao.timeseries.ILatestDao;
import com.gyee.wisdom.domain.timeseries.TsPointService;
import com.gyee.wisdom.taos.WriteRealValue;
import lombok.extern.slf4j.Slf4j;

import java.text.SimpleDateFormat;
import java.time.DayOfWeek;
import java.util.*;

@Slf4j
public class ReadAndWrite extends Thread {
    public TsPointService getTsPointService() {
        return tsPointService;
    }

    public void setTsPointService(TsPointService tsPointService) {
        this.tsPointService = tsPointService;
    }

    public ILatestDao getLatestDao() {
        return latestDao;
    }

    public void setLatestDao(ILatestDao latestDao) {
        this.latestDao = latestDao;
    }

    private TsPointService tsPointService;
    private ILatestDao latestDao;


    public WriteRealValue getWriteHistoryValue() {
        return writeHistoryValue;
    }

    public void setWriteHistoryValue(WriteRealValue writeHistoryValue) {
        this.writeHistoryValue = writeHistoryValue;
    }

    private WriteRealValue writeHistoryValue;

    List<TsPoint> lst = new ArrayList<>();
    Map<String, TsData> map = new HashMap<>();
    Map<String, TsData> result = Maps.newHashMap();
    @Override
    public void run() {
        try {
            while (true) {
                Thread.sleep(1000);
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
                String date = df.format(new Date());
                //获取所有测点
                lst = tsPointService.getAllTsPointToCache();
                //读取redis
                Date readRedisST=new Date();
                Map<String, TsData> tsDataMap = latestDao.getTsDataLatest(lst);
                Date readRedisET=new Date();
              //  log.error("读取redis成功！！！时间为："+(readRedisET.getTime()-readRedisST.getTime()));
                //获取差集
                tsDataMap.entrySet().removeAll(map.keySet());
                //写入taos
                Date writeTaosST=new Date();
                int b = writeHistoryValue.writeValue(tsDataMap);
                Date writeTaosET=new Date();
               // log.error("写入taos时间"+(writeTaosET.getTime()-writeTaosST.getTime()));
                if(b>0) {
                    for (String key : result.keySet()) {
                        map.put(key, result.get(key));
                    }
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}