import logging
import pandas as pd
from datetime import datetime

from celery import shared_task
from common.upload.services import download_from_cos
from common.utils.os_utils import clear_file

from console.monitor.models import MonitorDevices, MonitorDevicesImportRecord

logger = logging.getLogger("")


@shared_task(name="conole.monitor.import_devices")
def import_devices(record_id, url, enterprise_id):
    task_id = import_devices.request.id
    record = MonitorDevicesImportRecord.objects.get(id=record_id)
    record.task_id = task_id
    complete_time = datetime.now()
    local_path = download_from_cos(url)
    df = pd.read_excel(local_path, sheet_name=0, header=1)
    df = df.where(df.notnull(), None)
    df["enterprise_id"] = enterprise_id
    devices = df.to_dict(orient="records")
    device_list = []
    for device in devices:
        device_list.append(MonitorDevices(**device))
    try:
        MonitorDevices.objects.bulk_create(device_list)
        record.status = 1
        record.complete_time = complete_time
        record.save()
        clear_file(local_path)
    except Exception as e:
        logger.debug(e)
        record.status = 2
        record.save()
        clear_file(local_path)
