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, MongoSCDData
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 = {
    "865328061465380",
    "865328061478136",
    "865328061471529",
    "865328061466933",
    "865328061428701",
    "865328061466404",
    "865328061449913",
    "865328061455027",
    "865328061271879",
    "865328061253190",
    "865328061460159",
    "865328061438890",
    "865328061429451",
    "869298052295540",
    "865328061465679",
    "865328061450044"
}


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_scd_data

    for d_id in scd_device:
        device = collection.find_one({"device_id": d_id}, {"id": 1, "_id": 0})
        start = "2023-12-06 15:34:02"
        end = "2023-12-08 15:19: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.get("id"), 'addtime':{'$gt':start, "$lt": end}}
        cursor = collection1.find(data,{'_id':0,'id':0,'device_id':0})
        device_id = MongoDevice.objects.get(device_id=d_id).id
        print("数据量", cursor.count())
        for i in tqdm(list(cursor)):
            MongoSCDData.objects.create(
                device_id=device_id,
                device_data=i["device_data"],
                addtime=i['addtime'],
                device_status=i['device_status']
            )
        
    return True


if __name__ == "__main__":
    dsj_qxz_conf_info()