import os
import sys
import time
import django
local_path = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
print(local_path)
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, MongoDeviceConfig
from smartfarming.models.worm_forecast import MongoBZYphoto, MongoCBDphoto
import json
import requests
import pymongo
from urllib import parse


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",
"866547058627400",
"866547058637276",
"866547058633663",
"866547058613921",
"861551055315402",
"861551056086671",
"861551056088693",
"861551056088479",
"861551056088719",
"861551055313365",
"861551056086614",
"861551056093800",
"861551056095367",
"861551056102502",
"861551056096621",
"861551056101785",
"861551056086549",
"861551055354120",
"861551055353536",
"861551056092018",
"861551055319586",
"861551056088875",
"861551055324651",
"861551055313423",
"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_config

    for i in scd_device:
        device_info = collection.find_one({'device_id':i})
        device_id = device_info['id']
        data = {'d_id': device_id}
        cursor = collection1.find(data,{'_id':0,'id':0})
        try:
            device_id = MongoDevice.objects.get(device_id=i).id 
            for i in cursor:
                MongoDeviceConfig.objects.get_or_create(
                    d_id=device_id,
                    defaults={
                        "d_id": device_id,
                        "device_config": i['device_config'],
                        "cmd": i['cmd'],
                        "addtime": int(time.time()),
                        "uptime": int(time.time())
                    }
                )
                print(f"设备: {i} {device_id} 数据量  {cursor.count()}")
        except Exception as e:
            print(i)
    return True


if __name__ == "__main__":
    dsj_qxz_conf_info()