# -*- coding:utf-8 -*-
# @Time    : 2020/8/25 9.45 上午
# @Author  : Creat by cao
import operator
import json
import time
import os
import requests
import datetime
import uuid 
import ast
from django.conf import settings

from smartfarming.api.views.forecast.all_dict import insect_dict, attract_discern
from smartfarming.models.sim_card import MongoMsg_Conf
from smartfarming.models.device import MongoDevice
from smartfarming.models.worm_forecast import MongoCBDphoto, MongoCBDphoto_B, MongoCBDphoto_C
from kedong.decoration import kedong_deco, PortError
from .common import *
from django.db.models import Q
config_dict = settings.CONFIG


@kedong_deco(login_required=True)
def time_folder(request):
    """
    测报灯/色诱/吸虫塔/性诱3.0隐藏时间文件夹接口
    device_id               必传(str)               设备id
    identify_model          必传(str)               识别模型AB

    返回值：
    "data":[
        {
        "2021":{
        "10":[
        "14",
        "13",

        ],
        "09":[
        "30",
        "29",
        "28",
        "27",
        "16",
        "06"
        ]
        }
        }
        ],
    """
    device_id = request.POST.get('device_id')
    if not device_id:
        raise PortError("device_id", "未传设备号")
    
    try:
        device = MongoDevice.objects.get(device_id=device_id)
    except:
        raise PortError("", "设备号不对")

    myuser_type = request.user_type

    if device.device_type_id == 3:
        identify_model = request.POST.get("identify_model","A")
        if identify_model=="A":
            models = MongoCBDphoto
        elif identify_model=="B":
            models = MongoCBDphoto_B
        if not myuser_type == 1 and device.device_expire == "1":
            photo_list = models.objects.filter(device_id=device.id,photo_status=1,addtime__lte=int(device.device_expire_time)).order_by("-id")
        else:
            photo_list = models.objects.filter(device_id=device.id,photo_status=1).order_by("-id")
    else:
        raise PortError("","暂不支持的设备类型")
    
    repeat_data = []
    for i in photo_list:
        othertime = time.strftime("%Y-%m-%d", time.localtime(i.addtime))
        year,month,day = othertime.split("-")
        time_tup =  year,month,day
        repeat_data.append(time_tup)
    data = list(set(repeat_data))
    data.sort(key=repeat_data.index)

    time_data = []
    year_list = []
    month_list = []
    crowbar = -1      #使用撬棍进行列表下标标识,因为数据时经过去重和排序的,所以可以进行。
    for time_i in data:
        year_time = time_i[0]
        month_time = time_i[1]
        day_time = time_i[2]
        if year_time in year_list:
            if year_time+month_time in month_list:
                time_data[crowbar][year_time][month_time].append(day_time)
            else:
                time_data[crowbar][year_time][month_time] = [day_time]
                month_list.append(year_time+month_time)
        else:
            year_list.append(year_time)
            month_list.append(year_time+month_time)
            month_dict = {month_time:[day_time]}
            time_data.append({year_time:month_dict})
            crowbar+=1
    return(time_data)


@kedong_deco(login_required=True)
def device_photo_details(request):
    """
    色诱测报灯/测报灯/吸虫塔/性诱3.0/图片详情接口
    img_id                           必传(str)              图片id
    cmd                              非必传(str)             cmd有值并且为sy时,是色诱测报图片列表接口,
                                                            为xct时,是吸虫塔图片列表, 
                                                            为cbd是,是测报灯图片列表,
                                                            为xy_three 时, 是性诱3.0图片列表
    identify_model                   非必传("A","B")         cmd为cbd时,A是A模型,B是B模型



    返回值：
    "data": {
        "device_id": "2631",
        "addtime": 1632413928,
        "addr": "http://bigdata-all.oss-accelerate.aliyuncs.com/Basics/cbd/867435059571471/2021/9/24/20210924001848354843.jpg",
        "ids": 86524,
        "mark": "",
        "label": "",
        "indentify_photo": "http://bigdata-all.oss-accelerate.aliyuncs.com/Result/cbd/867435059571471/2021/9/24/20210924001848354843.jpg",
        "indentify_result": "158,38#670,26#672,4"
    },
    """
    img_id = request.POST.get("img_id")
    try:
        imgs = MongoCBDphoto.objects.get(id=img_id)
    except:
        raise PortError("img_id", "未找到该图片id")
    label = imgs.label
    indentify_photo = imgs.indentify_photo
    indentify_result = imgs.indentify_result
    img_url = imgs.addr
    mark = imgs.mark
    if mark:
        mark = json.loads(mark)
    else:
        mark = []
    data= {
        "device_id":imgs.device_id,
        "addtime":imgs.addtime,
        "addr":img_url,
        "ids":imgs.id,
        "mark":mark,
        "indentify_photo":indentify_photo,
        "indentify_result":indentify_result,
        "label":label}
    return data


@kedong_deco(login_required=True)
def device_photo_list(request):
    """
    测报灯图片展示接口
    device_id                        必传(str)              设备id
    page                             非必传(str)            页数
    page_number                      非必传(num)            页面显示数据总数,默认10条
    time_begin                       非必传(时间戳)          开始时间
    time_end                         非必传(时间戳)          结束时间


    返回值：
    "data": {
        "disable":0 禁用识别的状态    1 开启识别的状态,
        {
	'2021-04-09': [{
		'device_id': '836',
		'addtime': 1617936849,
		'describe': '',
		'addr': 'http://182.92.193.64:8003/Basics/cbd/866262046927462/2021/4/9/20210409105402642179.jpg',
		'mark': None,
		'id': 5877,
		'add_time': '2021-04-09'
	}],
	'2021-04-08': [{
		'device_id': '836',
		'addtime': 1617867971,
		'describe': '',
		'addr': 'http://182.92.193.64:8003/Basics/cbd/866262046927462/2021/4/8/20210408154604657028.jpg',
		'mark': None,
		'id': 5810,
		'add_time': '2021-04-08'
	}
    }
    """
    deviceas = request.POST
    device_id = deviceas.get("device_id")
    page = int(deviceas.get("page",1))
    
    time_begin = deviceas.get("time_begin")
    time_end = deviceas.get("time_end")
    page_number = int(deviceas.get("page_number",12))
    if not device_id:
        raise PortError("device_id", "未传设备号")
    try:
        device = MongoDevice.objects.get(device_id=device_id)
    except:
        raise PortError("", "设备号不对")
    data = []
    image_path = config_dict["image_url"]["image"] 
    photo_list = MongoCBDphoto.objects.filter(device_id=device.id,photo_status=1).order_by("-id")
    if time_begin and time_begin.isdigit() and time_end.isdigit():
        photo_list = photo_list.filter(addtime__range=(int(time_begin),int(time_end)))

    num = photo_list.count()
    for i in photo_list[(page_number*(page-1)):(page*page_number)]:
        # 判断是否有手动标注结果
        if i.is_mark == 1:
            try:
                mark = ast.literal_eval(i.mark)
            except:
                mark = json.loads(i.mark)
            pest_counts = len(mark)
        else:
            indentify_result = "" if i.indentify_result == "0" else i.indentify_result
            pest_counts = sum([int(i.split(",")[1]) for i in indentify_result.split("#")]) if indentify_result else 0

        # TODO 展示图片暂时处理
        if str(i.addr).startswith('http'):
            img_url = i.addr
        else:
            img_url = image_path + i.addr

        if str(i.indentify_photo).startswith('http'):
            indentify_photo = i.indentify_photo
        else:
            indentify_photo = image_path + i.indentify_photo
        data.append({
            "device_id":i.device_id,
            "addtime":i.addtime,
            "describe":i.describe,
            "addr":img_url,
            "ids":i.id,
            "mark":i.mark,
            "pest_counts":pest_counts,
            "indentify_photo":indentify_photo,
            "indentify_result":i.indentify_result
            })

    return {"disable":device.disable,"data":data,"num":num}


@kedong_deco(login_required=True)
def equip_photo_del(request):
    """
    测报灯/孢子仪/性诱/吸虫塔/性诱3.0图片删除接口
    参数
        device_id                必传(str)                      设备号
        addrlist                 非必传(str)                    图片列表
        
        addrlist没值删除所有的图片,有值就删除里面的值 
    """
    deviceas = request.POST
    device_id = deviceas.get("device_id")
    img_list = deviceas.get("addrlist")
    if not device_id:
        raise PortError("", "未传设备号")
    try:
        device_ids = MongoDevice.objects.get(device_id=device_id)
    except:
        raise PortError("", "设备号不存在")
    img_list = eval(img_list)
    if device_ids.device_type_id == 3:
        modules = MongoCBDphoto
    
    if img_list:
        for i in img_list:
            try:
                modules.objects.filter(id=i).update(photo_status=4)
            except:
                raise PortError("device_id", "删除失败")
    else:
        try:
            modules.objects.filter(device_id=device_ids.id).update(photo_status=4)
        except:
            raise PortError("device_id", "删除失败")
    return True


# 测报灯短信配置
@kedong_deco(login_required=True)
def cbd_msg_conf(request):
    """
    测报灯害虫预警短信配置接口：
    参数：
    device_id               必传(str)                设备号
    conf                    非必传(str)              害虫配置信息

    不传conf: 当前短信预警配置
    传conf：修改短信预警配置

    """
    device_id = request.POST.get("device_id")
    if not device_id:
        raise PortError("device_id", "参数不对")
    uptime = int(time.time())
    conf = request.POST.get("conf")
    if conf:
        try:
            if MongoMsg_Conf.objects.filter(device_id=device_id).exists():
                msgconf = MongoMsg_Conf.objects.get(device_id=device_id)
                msgconf.conf = conf
                msgconf.save()
            else:
                MongoMsg_Conf.objects.create(device_id=device_id,conf=conf,uptime=uptime)
        except:
            raise PortError(" ", "保存失败")
        return True
    else:
        try:
            msgconf = MongoMsg_Conf.objects.get(device_id=device_id)
            data = msgconf.conf
        except:
            data = ""
        return data



@kedong_deco(login_required=True)
def equip_photo_discern(request):
    # 测报灯、吸虫塔、色诱测报害虫重新图片识别\详情\手动标注接口
    img_id = request.POST.get("img_id")
    ret = request.POST.get("ret")
    if ret == "again":
        # 手动标注
        # 获取该图片对象
        photo_obj = MongoCBDphoto.objects.filter(id=img_id)
        photo_obj = photo_obj.first() if photo_obj else None 
        date = []
        if photo_obj:
            # 当图片对象存在
            addr = photo_obj.addr
            if addr:
                # 该图片对应设备的信息
                device = MongoDevice.objects.filter(id=photo_obj.device_id)
                device = device.first() if device else None 
                # 获取图片本地路径
                img_content_url = f'{config_dict.get("image_url").get("image")}/media'
                media = f'{config_dict.get("media")}'
                if addr.startswith("http"):
                    addr = addr.replace(img_content_url,media)
                else:
                    addr = addr.replace("/media",media)
                print(addr, "--------")
                pass 
                # 重新调用识别接口
                identify_url = config_dict.get("image_url").get("identify_url")
                if device.lng and device.lat:
                    request_data = {
                        "longitude": device.lng,
                        "latitude": device.lat
                    }
                else:
                    request_data = {
                        "longitude": "126.40548",
                        "latitude": "47.82857"
                    }
                if os.path.exists(addr):
                    imageFile = {
                        "imageFile": ('pic.jpg', open(addr, "rb"), 'image/jpeg')
                    }
                    res = requests.post(url=identify_url, data=request_data, files=imageFile, timeout=(10, 20))
                    image_result = json.loads(res.text)
                    try:
                        if image_result.get("returnResult").get("returnStatus") != "0":
                            returnString = image_result["returnResult"]["returnString"]
                            returnImageUrl = image_result["returnResult"]["returnImageUrl"]
                            returnCode = image_result["returnResult"].get("returnCode","")
                            remote_content = requests.get(returnImageUrl).content
                            indentify_photo = photo_obj.indentify_photo
                            # 如果第一次识别图片存在
                            if photo_obj:
                                if indentify_photo.startswith("http"):
                                    indentify_photo = indentify_photo.replace(img_content_url,media)
                                else:
                                    indentify_photo = indentify_photo.replace("/media",media)
                            else:
                                # 如果第一次识别图片不存在
                                inden_path = os.path.join(media, f"result/cbd/{device.device_id}")
                                os.makedirs(inden_path) if not os.path.exists(inden_path) else None 
                                stamp = int(datetime.now().timestamp())
                                unique_id = uuid.uuid4()
                                combined_id = str(stamp) + "-" + str(unique_id)
                                indentify_photo = os.path.join(inden_path, f"{combined_id}.jpg")
                            # 把原本地图片覆盖
                            with open(indentify_photo, "wb") as f:
                                f.write(remote_content)
                            # 更新结果
                            cbd_img = indentify_photo.replace(media, img_content_url)
                            photo_obj.indentify_photo = cbd_img
                            photo_obj.indentify_result = returnString
                            photo_obj.label = returnCode
                            photo_obj.save()
                            pest_list = returnString.split("#")
                            for i in pest_list:
                                if i:
                                    res = i.split(",")
                                    nums = res[1] #数量
                                    number = res[0] #编号
                                    try:
                                        result_list = insect_dict[number]
                                    except:
                                        result_list = attract_discern[number]
                                    date.append({"nums":nums,"result_list":result_list,"number":number})
                            dat = {"image":cbd_img,"result":date, "label": returnCode}
                            print(dat)
                            return dat
                        else:
                            return {"code": 2, "msg": "无识别结果"}
                    except Exception as e:
                        return {"code": 2, "msg": "无识别结果"}
    else:
        return {"code": 2, "msg": "参数范围越界"}


@kedong_deco(login_required=True)
def cbdphoto_receive(request):
    # 测报灯/色诱/吸虫塔/害虫图片手动添加标注接口：
    img_id = request.POST.get('img_id')
    mark = request.POST.get('mark')
    photo_obj = MongoCBDphoto.objects.get(id=img_id)
    photo_obj.is_mark = 1
    photo_obj.mark = mark
    photo_obj.save()
    return json.loads(mark)
