import os
import sys
import datetime
import django
local_path = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
if local_path not in sys.path:
    sys.path.append(local_path)
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "kedong.settings")
django.setup()
from django.conf import settings
from smartfarming.models.device import MongoDevice, MongoXYCBData
import json
import requests
import pymongo
from urllib import parse
from tqdm import tqdm


my_client = pymongo.MongoClient(host="8.136.98.49", port=27017, username="root", password="yfkj@6020")
my_col = my_client['smartfarming']['sa_device']

scd_device = {
"866250061217240",
"863569067039065"
}


def dsj_qxz_conf_info():
    user = parse.quote_plus("root")
    passwd = parse.quote_plus("yfkj@6020")
    # 账号密码方式连接MongoDB | "mongodb://用户名:密码@公网ip:端口/"
    myclient = pymongo.MongoClient("mongodb://{0}:{1}@8.136.98.49:57017/".format(user,passwd))
    # myclient = pymongo.MongoClient("mongodb://127.0.0.1:12514/")
    # 指定数据库
    db = myclient.smartfarming
    # 指定集合
    collection = db.sa_device
    collection1 = db.sa_device_xycb_data

    for d_id in scd_device:
        device_info = collection.find_one({'device_id':d_id})
        device_id = device_info['id']
        start = "2023-10-22 13:27:25"
        end = "2023-12-08 15:10:01"
        start = int(datetime.datetime.strptime(start, "%Y-%m-%d %H:%M:%S").timestamp())
        end = int(datetime.datetime.strptime(end, "%Y-%m-%d %H:%M:%S").timestamp())
        data = {'device_id': device_id, 'addtime':{'$gt':start, "$lt": end}}
        cursor = collection1.find(data,{'_id':0,'id':0,'device_id':0})
        device_ids = MongoDevice.objects.get(device_id=d_id).id
        for i in tqdm(list(cursor)):
            MongoXYCBData.objects.create(
                device_id=device_ids,
                device_data=i["device_data"],
                addtime=i['addtime']
            )
        print(f"设备: {i} {device_id} 数据量  {cursor.count()}")
    return True


if __name__ == "__main__":
    dsj_qxz_conf_info()