# -*- coding:utf-8 -*-
# @Time    : 2020/8/25 9.45 上午
# @Author  : Creat by cao
import operator
import json
import time
import os
import requests
import random
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
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('/'):
            img_url = image_path + i.addr
        else:
            img_url = image_path + "/" + i.addr
        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":i.indentify_photo,
            "indentify_result":i.indentify_result
            })

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




from .common import *
from django.db.models import Q


@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



def disable_cbd_discern(request):
    """
    禁用测报灯害虫识别功能

    device_id            必传(str)                    设备号
    ret                  必传(str)                    ret=disable时禁用识别功能, ret=enable,时启用识别统计功能, ret =count 计数功能

    """
    device_id = request.POST.get("device_id")
    ret = request.POST.get("ret")

    try:
        device_list = Device.objects.get(device_id=device_id)
    except:
        raise PortError("device_id", "找不到该设备")
    if ret == "disable":
        device_list.disable = 0
        device_list.save()
    elif ret == "enable":
        device_list.disable = 1
        device_list.save()
    elif ret == "count":
        device_list.disable = 2
        device_list.save()
    else:
        raise PortError("device_id", "参数超出范围")
    return True



def cbd_pest_type_ranking(request):
    """
    筛选最近识别害虫列表接口
    参数：
    start_time      非必传          开始时间 时间戳
    end_time        非必传          结束时间 时间戳、
    page            非必传          页数
    page_size       非必传          一页默认10条数据
    ret             必传            为num害虫排名,  为type列表详情数据, 
    identify_model  必传            识别模型A,识别模型B

    type时返回值：
     "data": {
        "num": 2,                                       条数
        "cbd_photo_data": [
            {
                "device_id": "867814040006799",         设备号
                "pest_num": 18,                         害虫种类数据
                "pest_name": [
                    {
                        "pest_name": "水龟虫",          害虫种类
                        "num": 518                      害虫总数
                    },
                    {
                        "pest_name": "蝼蛄",
                        "num": 128
                    },
        num 时返回值：
        "data": [
            {
                "水龟虫": 539      害虫名称    害虫数量
            },
            {
                "蝼蛄": 153
            },
            {
                "铜绿丽金龟": 62
            },
            {
                "负子蝽": 42
            },
            {
                "暗黑鳃金龟": 21
            },
            {
                "夜蛾": 15
            }
        ],
    """
    page = int(request.POST.get("page",1))
    page_size = int(request.POST.get("page_size",10))
    start_time = request.POST.get("start_time")
    end_time = request.POST.get("end_time")
    ret = request.POST.get("ret")
    recive_pest_name = request.POST.get("pest_name")
    identify_model = request.POST.get("identify_model","A")
    if identify_model=="A":
        models = CBDphoto
    elif identify_model=="B":
        models = CBDphoto_B
    myuser = request.myuser
    pest_num_data = []
    date = []
    devices = Device.devices(uid=myuser.uid, myuser=myuser)
    print("user_type",myuser.user_type)
    if myuser.user_type != 4 or myuser.user_type != 1:
        devices = devices.filter(disable=1)
    for i in devices:
        if not myuser.user_type == 1 and i.device_expire == "1":
            cbd_data = models.objects.filter(~Q(indentify_photo=None),device_id=i.id,photo_status=1,addtime__lte=int(i.device_expire_time)).values()
            if end_time and int(end_time) > int(i.device_expire_time):
                end_time = i.device_expire_time
                cbd_data = cbd_data.filter(addtime__range=(int(start_time),int(end_time)))
        else:
            cbd_data = models.objects.filter(~Q(indentify_photo=None),device_id=i.id,photo_status=1).values()
            if start_time:
                cbd_data = cbd_data.filter(addtime__range=(int(start_time),int(end_time)))
        for x in cbd_data:
            if x["indentify_result"]:
                xx_result =  x["indentify_result"].split("#")
                print(xx_result)
                for yy in xx_result:
                    yy_result = yy.split(",")
                    try:
                        date.append({
                                "device_id": i.device_id,
                                "device_name": i.device_name,
                                "device_add": i.province+i.city+i.district,
                                "pest_num" : int(yy_result[1]),
                                "pest_name" : insect_dict[yy_result[0]]})
                    except:
                        continue
    data = {}
    pest = {}
    if ret == "type":
        for item in date:
            device_id, pest_name,pest_num,device_name,device_add= item['device_id'], item['pest_name'],item['pest_num'],item['device_name'],item['device_add']
            key = '{},{},{}'.format(device_id,device_name,device_add)
            if key in data:
                data[key] += [pest_name]
            else:
                data[key] = [pest_name]
            keys = '{},{}'.format(device_id,pest_name)
            if keys in pest:
                pest[keys] += pest_num

            else:
                pest[keys] = pest_num
        sort_data = sorted(data.items(), key=lambda d:len(d[1]), reverse = True )
        for y in sort_data:
            device_id,device_name, device_addr = y[0].split(',')
            pest_data = []
            for x in y[1]:
                x = {"pest_name":x,"num":pest[device_id +","+x]}
                if x not in pest_data:
                    pest_data.append(x)
            sorted_x = sorted(pest_data, key=operator.itemgetter('num'),reverse = True)
            if recive_pest_name:
                for pt_name in sorted_x:
                    if recive_pest_name in pt_name["pest_name"]:
                        pest_num_data.append({
                            "device_id" : device_id,
                            "pest_num": len(pest_data),
                            "pest_name": sorted_x,
                            "device_name" : device_name,
                            "device_addr": device_addr
                        })
                    else:
                        pass
            else:
                pest_num_data.append({
                    "device_id" : device_id,
                    "pest_num": len(pest_data),
                    "pest_name": sorted_x,
                    "device_name" : device_name,
                    "device_addr": device_addr
                })
        num = len(pest_num_data)
        cbd_photo_data = pest_num_data[(page_size*(page-1)):(page*page_size)]
        cbd_pset = {"num":num,"cbd_photo_data":cbd_photo_data}
        return cbd_pset
    elif ret == "num":
        for item in date:
            pest_num,pest_name = item['pest_num'],item["pest_name"]
            key = '{}'.format(pest_name)
            if key in data:
                data[key] += pest_num
            else:
                data[key] = pest_num
        sort_data = sorted(data.items(), key=lambda d:d[1], reverse = True )[:6]
        for y in sort_data:
            pest_num_data.append({
                y[0] : y[1]
            })
        return pest_num_data
    else:
        raise PortError("ret", "参数超出范围")
        





def cbd_pest_line_chart(request):
    """
    筛选总设备害虫折线图
    参数：
    start_time              非必传(string 时间戳)           开始时间    (用于时间搜索)
    end_time                非必传(string 时间戳)           结束时间    (用于时间搜索)
    pest_name               非必传(str)                     害虫名称
    ret                     必传                            等于day_month 24小时数据、近一个月数据, 等于：half_year 半年、一年数据
    identify_model          必传                            识别模型A,识别模型B
    
    等于day_month返回值：
     "data": [
        {
            "addtime": "2021-03-09 11:28:08",                   时间
            "pest_name": "夜蛾",                                害虫名
            "pest_num": 5                                       数量
        },
        {
            "addtime": "2021-03-09 18:51:07",
            "pest_name": "夜蛾",
            "pest_num": 4
        },
    等于half_year返回值：
     "data": [
        {
            "addtime": "2021-03",                           月份
            "pest_name": "夜蛾",                            害虫名
            "pest_num": 54                                  数量
        },
        {
            "addtime": "2021-04",
            "pest_name": "夜蛾",
            "pest_num": 44
        }
    ],
    "pest_name":{
        "水龟虫"：20
    }
    """

    start_time = request.POST.get("start_time")
    end_time = request.POST.get("end_time")
    ret = request.POST.get("ret")
    pest_name = request.POST.get("pest_name")
    identify_model = request.POST.get("identify_model","A")
    if identify_model=="A":
        models = CBDphoto
    elif identify_model=="B":
        models = CBDphoto_B
    myuser = request.myuser
    print(myuser.uid)
    date = [] 
    devices = Device.devices(uid=myuser.uid, myuser=myuser)
    if myuser.user_type != 4 or myuser.user_type != 1:
        devices = devices.filter(disable=1)
    for i in devices:
        if not myuser.user_type == 1 and i.device_expire == "1":
            cbd_data = models.objects.filter(~Q(indentify_photo=None),device_id=i.id,photo_status=1).filter(addtime__lte=int(i.device_expire_time))
            if end_time:
                if int(end_time) > int(i.device_expire_time):
                    end_time = i.device_expire_time
                cbd_data = cbd_data.filter(addtime__range=(int(start_time),int(end_time)))
        else:
            cbd_data = models.objects.filter(~Q(indentify_photo=None),device_id=i.id,photo_status=1)
            if start_time:
                cbd_data = cbd_data.filter(addtime__range=(int(start_time),int(end_time)))
        for x in cbd_data:
            photo_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(x.addtime))
            if x.indentify_result:
                xx_result =  x.indentify_result.split("#")
                for yy in xx_result:
                    yy_result = yy.split(",")
                    try:
                        if pest_name == insect_dict[yy_result[0]]:
                            date.append({
                                    "photo_time" : photo_time,
                                    "pest_num" : int(yy_result[1]),
                                    "pest_name" : insect_dict[yy_result[0]]})
                        if not pest_name:
                            date.append({
                                    "photo_time" : photo_time,
                                    "pest_num" : int(yy_result[1]),
                                    "pest_name" : insect_dict[yy_result[0]]})
                    except:
                        continue
    data = {}
    if ret == "day_month":
        print("24小时数据---近一个月数据")
        for item in date:
            photo_time, pest_name, pest_num = item['photo_time'], item['pest_name'], item['pest_num']
            key = '{},{}'.format(photo_time, pest_name)
            if key in data:
                data[key] += pest_num
            else:
                data[key] = pest_num
        result = []
        for key, value in data.items():
            photo_time,pest_name = key.split(',')
            result.append({
                "addtime" : photo_time,
                "pest_name" : pest_name,
                "pest_num" : data[key]

            })
        list2 = sorted(result, key=operator.itemgetter('addtime'))
    elif ret == "half_year":
        print("近半年_近一年")
        for item in date:
            photo_time, pest_name, pest_num = item['photo_time'], item['pest_name'], item['pest_num']
            addtime = photo_time.split("-")[0] + "-" + photo_time.split("-")[1]
            key = '{},{}'.format(addtime, pest_name)
            if key in data:
                data[key] += pest_num
            else:
                data[key] = pest_num
        result = []
        for key, value in data.items():
            addtime,pest_name = key.split(',')
            result.append({
                "addtime" : addtime,
                "pest_name" : pest_name,
                "pest_num" : data[key]

            })
        list2 = sorted(result, key=operator.itemgetter('addtime'))
    else:
        raise PortError("ret", "参数超出范围")
    datp = {}
    pest_num_data = []
    for item in date:
        pest_num,pest_name = item['pest_num'],item["pest_name"]
        key = '{}'.format(pest_name)
        if key in datp:
            datp[key] += pest_num
        else:
            datp[key] = pest_num
    sort_data = sorted(datp.items(), key=lambda d:d[1], reverse = True )[:6]
    for y in sort_data:
        pest_num_data.append({
            y[0] : y[1]
        })
    da = {
        "data":list2,
        "pest_name":pest_num_data
    }
    return da

