import copy
# Create your views here.
import datetime
import json
import os
import re
import time
import urllib.request

import requests
from django.http import FileResponse
from django.http.response import HttpResponse
from django.shortcuts import render
from django.views.generic import ListView
from django.views.generic.base import View
from django.contrib.auth.hashers import make_password, check_password
from PIL import Image
from django.utils import timezone
import xmltodict
from django.contrib.auth import get_user_model
from apps.AppInfo.models import (
    Article, CKArticle, Equip, Equip_type, FarmList, FarmUser, GardenManage,
    Hotel_Info, Hotel_Photo, JKdata, MyUser, Pick_Pub, Product, QXZdata,
    QXZdata_New, QXZstatus, QXZstatus_New, QXZswitchdata, QXZswitchstatus,
    Video_data,GardenArea,Store_Manage,Areacrop,Sell_Manage,Person_Pick,QXZAutoswitch,Sightsee_Info,Pic_Info)
from apps.Equipment.all_dict import qxz_dict


# 地图
class Map_Test(View):
    def get(self,request):
        # current_user = request.session.get('username')
        current_user = MyUser.objects.get(username="admin")
        # print("current_user:", current_user)
        # current_user = MyUser.objects.get(username=current_user)
        pic_list = Pic_Info.objects.get(pic_user=current_user)
        return render(request, 'backstageNet/map/map.html', context={"pic_list":pic_list})
    def post(self,request):
        pass


# 测试接口
class Equip_Test(View):
    def get(self,request):
        pass
    def post(self,request):
        qxz_data = QXZstatus.objects.get(equip_id="16054381")
        json_obj = qxz_data.qxz_status.replace("'", "\"")
        xml = xmltodict.unparse({'request':json_obj})
        return HttpResponse(xml)




# 监控界面
class JKview(ListView):
    def get(self,request):
        equip_id = request.GET.get('equip_id')
        return render(request, 'backstageNet/jk/equipmanage_jk.html', context={"equip_id":equip_id})
    def post(self,request):
        pass



# 监控列表
class JKlist(ListView):
    def get(self,request):
        # current_user = request.user.username
        # print("current_user:", current_user)
        current_user = MyUser.objects.get(username="admin")
        page = request.GET.get('page')
        page = int(page)
        f_id = request.GET.get('f_id')
        print("f_id:", f_id)
        if current_user.is_superuser != True and current_user.is_staff != True:
            # 用户
            if f_id != "":
                equip_list = Equip.objects.filter(equip_type=6, equip_user=current_user, equip_id__contains=f_id)
            else:
                equip_list = Equip.objects.filter(equip_type=6, equip_user=current_user)
        else:
            # 管理员
            if f_id != "":
                equip_list = Equip.objects.filter(equip_type=6, equip_id__contains=f_id)
            else:
                equip_list = Equip.objects.filter(equip_type=6)
        e_ids = []
        for x in equip_list:
            n_d = {"equip_name":x.equip_name, "equip_id":x.equip_id}
            e_ids.append(n_d)
        nums = len(e_ids)
        # print(nums)
        ids = e_ids[(10*(page-1)):(page*10)]
        data = {'ids': ids, 'nums': nums}
        data = json.dumps(data)
        return HttpResponse(data)

    def post(self,request):
        pass


# 视频详情
class JKManage_View(ListView):
    def get(self, request):
        live_list = []
        j_id = request.GET.get("id")
        jk_list = JKdata.objects.filter(equip_id=j_id)
        for x in jk_list:
            # 用token和设备id获取直播地址
            live_url = 'https://open.ys7.com/api/lapp/live/address/get'
            live_data = {"accessToken":x.jk_token,
                        "source":"%s:1"%x.equip_id}
            print("=================live_data:",live_data)
            live_res = requests.post(live_url,data=live_data)
            # print("-------------------------------:",type(live_res.text))
            live_res = eval(live_res.text)
            print("live_res:",live_res)
            # 如果返回200 则返回直播地址
            if live_res['code'] == "200":
                print("token获取成功")
                live_list.append(live_res)

            # 如果返回其他 则调用获取token之后重新获取直播地址并返回
            else:
                print("token过期重新获取")
                token_url = 'https://open.ys7.com/api/lapp/token/get'
                token_data = {"appKey":"e8ec0d52b4b14628a3daf4b88cbcca2a",
                        "appSecret":"d4565abea1cd0b90b59917111dcb37bd"}
                token_res = requests.post(token_url,data=token_data)
                print("token_res1:",token_res.text)
                token_res = eval(token_res.text)
                if token_res["code"] == "200":
                    token_res["data"]["accessToken"]
                    x.jk_token = token_res["data"]["accessToken"]
                    x.upl_time = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
                    x.save()
                    token = x.jk_token
                    print("-----------------token保存成功")
                live_url = 'https://open.ys7.com/api/lapp/live/address/get'
                live_data = {"accessToken":x.jk_token,
                            "source":"%s:1"%x.equip_id}
                live_res = requests.post(live_url,data=live_data)
                live_res = eval(live_res.text)
                print("live_res2:",live_res)
                live_list.append(live_res)
        data = json.dumps(live_list)
        return HttpResponse(data)
        # return render(request, 'backstageNet/jk/equipmanage_jk.html', context={"data":data})


    def post(self, request):
        jk_id = request.POST.get('id')
        ctrl = request.POST.get('ctrl')
        imei = request.POST.get('imei')
        accessToken = JKdata.objects.get(equip_id=jk_id).jk_token
        print("accessToken:",accessToken)
        if imei:
            if Equip.objects.filter(equip_id=imei).exists():
                return HttpResponse("0")

            else:
                # 得到设备类型实例：
                equip_t = Equip_type.objects.get(type_id=6)
                try:
                    e_id = Equip.objects.create(equip_id=imei, equip_type=equip_t)
                    print("<-----监控设备添加成功!----->")
                    return HttpResponse("1")
                except:
                    print("<-----监控设备添加失败!----->")
        
        if ctrl == "takephoto":
            url = 'https://open.ys7.com/api/lapp/device/capture'
            channelNo = '1'
            data = {'accessToken':accessToken, 'deviceSerial':jk_id, 'channelNo':channelNo}
            res = requests.post(url,data=data)
            print("截图返回结果为:",json.loads(res.text))
            return HttpResponse(res.text)

        # 操作命令：0-上，1-下，2-左，3-右，4-左上，5-左下，6-右上，7-右下，8-放大，9-缩小，10-近焦距，11-远焦距
        if ctrl == "move":
            print("-------球机云台控制开始！")
            dire = request.POST.get('movenum')
            ctrl_url = 'https://open.ys7.com/api/lapp/device/ptz/start'
            channelNo = '1'
            speed = '1'
            data = {'accessToken':accessToken, 'deviceSerial':jk_id, 'channelNo':channelNo, 'speed':speed, 'direction':dire}
            res1 = requests.post(ctrl_url,data=data)
        elif ctrl == "stop":
            print("-------球机云台控制结束！")
            ctrl_url = 'https://open.ys7.com/api/lapp/device/ptz/stop'
            channelNo = '1'
            data = {'accessToken':accessToken, 'deviceSerial':jk_id, 'channelNo':channelNo}
            res2 = requests.post(ctrl_url,data=data)
        return HttpResponse("1")


# 新闻列表
class Newslist_View(ListView):
    def get(self,request):
        con = request.GET.get("condition")
        page = int(request.GET.get("page"))
        art_type = int(request.GET.get("type"))
        art_list = CKArticle.objects.filter(art_type=art_type)
        if con:
            art_list = CKArticle.objects.filter(art_type=art_type,title__contains=con)
        nums = art_list.count()
        art = art_list[(5*(page-1)):(page*5)]
        return render(request, 'outerNet/newsList.html', context={'art':art,"nums":nums,"con":con,"page":page})
    def post(self,request):
        art_list = CKArticle.objects.all()
        data = []
        for i in art_list:
            data.append({"id":i.id,"title":i.title,"content":i.content,"upl_time":i.upl_time.strftime('%Y-%m-%d %H:%M:%S')})
        data = json.dumps(data)
        return HttpResponse(data)


# 新闻详情
class News_View(ListView):
    def get(self,request):
        f_id = request.GET.get("id")
        objs = CKArticle.objects.all().order_by("id")
        art = objs.get(id=f_id)
        on_art = objs.filter(id__lt=f_id,art_type=art.art_type)
        up_art = objs.filter(id__gt=f_id,art_type=art.art_type)
        return render(request, 'outerNet/newsDetail.html', context={"art":art,"on_art":on_art,"up_art":up_art})
    def post(self,request):
        art_list = Article.objects.all()
        for i in art_list:
            print(i.title)
        return HttpResponse("1")


# 产品展厅列表
class Equip_Show_List(ListView):
    def get(self,request):
        page = int(request.GET.get("page"))
        product_list = Product.objects.all() 
        con = request.GET.get("condition")
        if con:
            product_list = Product.objects.filter(title__contains=con)
        nums = product_list.count()
        product = product_list[(20*(page-1)):(page*20)]
        return render(request, 'outerNet/exhibitionList.html', context={"nums":nums,"page":page,"con":con,"product":product})
    def post(self,request):
        pass



# 产品展厅详情
class Equip_Show_Detail(ListView):
    def get(self,request):
        e_id = request.GET.get("id")
        product = Product.objects.get(id=e_id)
        return render(request, 'outerNet/exhibitionDetail.html', context={"product":product})
    def post(self,request):
        pass


# 四季采摘-园区列表
class Garden_List(ListView):
    def get(self,request):
        pass
    def post(self,request):
        page = int(request.POST.get("page"))
        farm_list = FarmList.objects.all()
        farm = []
        for i in farm_list:
            farm.append({"name":i.name,"id":i.id})
        nums = len(farm)
        farms = farm[(10*(page-1)):(page*10)]
        data = {"farms":farms,"nums":nums}
        data = json.dumps(data)
        return HttpResponse(data)



# 四季采摘-主页
class Garden_View(ListView):
    def get(self,request):
        return render(request, 'outerNet/fourPick.html', context={})
    def post(self,request):
        pass
# 主页四级采摘进入的介绍页
class Garden_Intro(ListView):
    def get(self,request):
        return render(request, 'outerNet/pickIntro.html', context={})
    def post(self,request):
        pass


# 四季采摘-园区详情
class Garden_Detail(ListView):
    def get(self,request):
        pass
    def post(self,request):
        f_id = request.POST.get("id")
        page = int(request.POST.get("page"))
        farm = FarmList.objects.get(id=f_id)
        pick = Pick_Pub.objects.filter(farm=farm)
        pick_list = []
        for i in pick:
            pick_list.append({"farm":i.farm.name,"name":i.name,"time":i.upl_time,"company":i.company,"img":i.pick_img})
        nums = len(pick_list)
        pick_list = pick_list[(12*(page-1)):(page*12)]
        data = {"pick":pick_list,"nums":nums}
        data = json.dumps(data)
        return HttpResponse(data)

#旅游导览
class Tourist(ListView):
    def get(self,request):
        return render(request, 'outerNet/tourist.html', context={})
    def post(self,request):
        pass
#旅游导览
class Tourist_List(ListView):
    def get(self,request):
        return render(request, 'outerNet/touristList.html', context={})
    def post(self,request):
        pass

# 民宿列表
class Dorm_List(ListView):
    def get(self,request):
        page = int(request.GET.get("page"))
        con = request.GET.get("condition")
        hotel_list = Hotel_Info.objects.all()
        if con:
            hotel_list = Hotel_Info.objects.filter(name__contains=con)
        nums = hotel_list.count()
        hotel = hotel_list[(10*(page-1)):(page*10)]
        return render(request, 'outerNet/hotelList.html', context={"nums":nums,"hotel":hotel,"page":page,"con":con})
    def post(self,request):
        pass


# 民宿详情
class Dorm_Detail(ListView):
    def get(self,request):
        hotel_id = request.GET.get("id")
        hotel = Hotel_Info.objects.get(id=hotel_id)
        photos = Hotel_Photo.objects.filter(hotel=hotel)
        return render(request, 'outerNet/hotelDetail.html', context={"hotel":hotel,"photos":photos})
    def post(self,request):
        pass


# 农场导览  
class Farm_list(ListView):
    def get(self,request):
        page = int(request.GET.get("page"))
        con = request.GET.get("condition")
        hotel_list = Hotel_Info.objects.all()
        if con:
            hotel_list = Hotel_Info.objects.filter(name__contains=con)
        nums = hotel_list.count()
        hotel = hotel_list[(10*(page-1)):(page*10)]
        return render(request, 'outerNet/farmList.html', context={"nums":nums,"hotel":hotel,"page":page,"con":con})
    def post(self,request):
        pass

# 视频列表
class Video_List(ListView):
    def get(self,request):
        page = int(request.GET.get("page"))
        con = request.GET.get("condition")
        video_list = Video_data.objects.all()
        if con:
            video_list = Video_data.objects.filter(title__contains=con)
        nums = video_list.count()
        video = video_list[(12*(page-1)):(page*12)]
        return render(request, 'outerNet/videoList.html', context={"nums":nums,"video":video,"con":con,"page":page})
    def post(self,request):
        pass



# 视频详情
class Video_Detail(ListView):
    def get(self,request):
        v_id = request.GET.get("id")
        video = Video_data.objects.get(id=v_id)
        return render(request, 'outerNet/videoDetail.html', context={"video":video})
    def post(self,request):
        pass





# 后台管理页面
class Back_Manage(ListView):
    def get(self,request):
        if request.user.is_authenticated():
            current_user = request.user.username
            current_user = MyUser.objects.get(username=current_user)
            return render(request, 'backstageNet/home.html', context={"current_user":current_user})
        else:
            return render(request, 'outerNet/index2.html')
    def post(self,request):
        current_user = request.user.username
        print("current_user:", current_user)
        current_user = MyUser.objects.get(username=current_user)
        data = current_user.limit
        return HttpResponse(data)


# 信息发布页面
class Info_Pub(ListView):
    def get(self,request):
        return render(request, 'backstageNet/info/infoPub.html', context={})
    def post(self,request):
        # 文章标题
        title = request.POST.get('title')
        # 文章简介
        intro = request.POST.get('intro')
        # 文章内容
        info = request.POST.get('info')
        # 文章图片
        head_img = request.POST.get('upicture')
        admin = MyUser.objects.get(username="admin")
        if head_img:
            try:
                Article.objects.create(title=title,intro=intro,content=info,author=admin,head_img=head_img)
                data = "1"
            except:
                data = "0"
        else:
            data = "0"

        return HttpResponse(data)


# 信息维护页面
class Info_Manage(ListView): 
    def get(self,request):
        return render(request, 'backstageNet/info/infoManage.html', context={})
    def post(self,request):
        pass





# 气象站分页接口
class QXZ_Page(ListView):
    def get(self,request):
        # current_user = request.user.username
        # print("current_user:", current_user)
        # current_user = MyUser.objects.get(username="admin")
        page = request.GET.get('page')
        page = int(page)
        # f_id = request.GET.get('f_id')
        # print("f_id:", f_id)
        # if current_user.is_superuser != True and current_user.is_staff != True and current_user.is_agency != True:
        #     # 用户
        #     if f_id != "":
        #         equip_list = Equip.objects.filter(equip_type=5, equip_user=current_user, equip_id__contains=f_id)
        #     else:
        #         equip_list = Equip.objects.filter(equip_type=5, equip_user=current_user)

        # elif current_user.is_superuser != True and current_user.is_staff != True and current_user.is_agency == True:
        #     # 代理商
        #     if f_id != "":
        #         equip_list = Equip.objects.filter(equip_type=5, equip_agency=current_user.user_agency, equip_id__contains=f_id)
        #     else:
        #         equip_list = Equip.objects.filter(equip_type=5, equip_agency=current_user.user_agency)

        # else:
        #     # 管理员
        #     if f_id != "":
        #         equip_list = Equip.objects.filter(equip_type=5, equip_id__contains=f_id)
        #     else:
        equip_list = Equip.objects.filter(equip_type=5)
        e_ids = []
        for x in equip_list:
            n_d = {"equip_name":x.equip_name, "equip_id":x.equip_id}
            e_ids.append(n_d)
        nums = len(e_ids)
        # print(nums)
        ids = e_ids[(10*(page-1)):(page*10)]
        data = {'ids': ids, 'nums': nums}
        data = json.dumps(data)
        return HttpResponse(data)

    def post(self,request):
        pass



# 气象站状态
class QXZ_Status(ListView):
    def get(self,request):
        return render(request, 'backstageNet/qxzctrl/qxzData.html', context={})
    def post(self,request):
        e_id = request.POST.get("e_id")
        qxz_list = QXZstatus_New.objects.filter(equip_id=e_id)
        data = []
        for i in qxz_list:
            data.append({"interval":i.interval,"upl_time":i.upl_time.strftime('%Y-%m-%d %H:%M:%S'),"e1":i.e1,"e2":i.e2,"e3":i.e3,
                "e4":i.e4,"e5":i.e5,"e6":i.e6,"e7":i.e7,"e8":i.e8,"e9":i.e9,"e10":i.e10,"e11":i.e11,"e12":i.e12,"e13":i.e13,"e14":i.e14})
        data = json.dumps(data)
        return HttpResponse(data)



# 气象站状态测试
class QXZ_Status2(ListView):
    def get(self,request):
        return render(request, 'backstageNet/qxzctrl/qxzData.html', context={})
    def post(self,request):
        e_id = request.POST.get("e_id")
        qxz_list = QXZstatus_New.objects.filter(equip_id=e_id)
        # data = []
        for i in qxz_list:
            dat = {"e1":i.e1,"e2":i.e2,"e3":i.e3,"e4":i.e4,"e5":i.e5,"e6":i.e6,"e7":i.e7,"e8":i.e8,"e9":i.e9,"e10":i.e10,"e11":i.e11,"e12":i.e12,"e13":i.e13,"e14":i.e14}
            data = {"interval":i.interval,"upl_time":i.upl_time.strftime('%Y-%m-%d %H:%M:%S'),"dat":dat}
        data = json.dumps(data)
        return HttpResponse(data)


# 气象站控制
class QXZcontrol(ListView):
    def get(self,request):
        return render(request, 'backstageNet/qxzctrl/qxzctrl.html', context={})
    def post(self,request):
        e_id = request.POST.get('e_id')
        try:
            switch_obj = QXZswitchstatus.objects.get(equip_id=e_id)
            qxz_switch = switch_obj.qxz_switch
        except:
            qxz_switch = ""
        try:
            switch_name_obj = QXZswitchdata.objects.get(equip_id=e_id)
            switch_name = switch_name_obj.qxz_switch_data
        except:
            switch_name = ""


        data = {'qxz_switch':qxz_switch, 'switch_name':switch_name}
        data = json.dumps(data)
        return HttpResponse(data)


# 气象站数据
class QXZchart(ListView):
    def get(self,request):
        return render(request, 'backstageNet/qxzctrl/qxzchart.html', context={})
    def post(self,request):
        qxz_dict_2 = copy.deepcopy(qxz_dict)
        equip_id = request.POST.get('id')
        print("equip_id:", equip_id)
        f_tbegin = request.POST.get('begin')
        f_tend = request.POST.get('end')
        print("f_tbegin:", f_tbegin)
        print("f_tend:", f_tend)
        current_equip = Equip.objects.get(equip_id=equip_id)
        dat = []
        if f_tbegin:
            begindate = re.findall(r"\d+\.?\d*", f_tbegin)
            enddate = re.findall(r"\d+\.?\d*", f_tend)
            start_date = datetime.date(int(begindate[0]), int(begindate[1]), int(begindate[2]))
            end_date = datetime.date(int(enddate[0]), int(enddate[1]), int(enddate[2]))
            print("start_date:", start_date)
            print("end_date:", end_date)
            sta1 = QXZdata.objects.filter(
                equip_id=equip_id, upl_time__range=(start_date, end_date)).values()
            for x in sta1:
                sta = {"upl_time": x["upl_time"].strftime('%Y-%m-%d %H:%M:%S'),"e_len": len((eval(x["qxz_data"])["data"])),
                    "unit": [], "equip_id": x["equip_id_id"]}
                for i in eval(x["qxz_data"])["data"]:
                    qxz_dict_2[i["eNum"]][0] = i["eValue"]  # 将气象站字典列表里的索引值替换为 数据的eValue
                    d = copy.deepcopy(qxz_dict_2[i["eNum"]])   # 此处有坑 如果不深拷贝 后一次 qxz_dict[i["eNum"]][0] = i["eValue"] 赋值会把上次赋值替换掉
                    ek = i["eKey"]
                    d.append(ek)
                    d.append(i["eNum"])
                    sta["unit"].append(d)
                    # qxz_dict[eval(x.qxz_data)['data'][0]["eNum"]]
                # print(sta["unit"])
                dat.append(sta)
            # print(dat)
            data = {"e_name": current_equip.equip_name, "dat": dat}
            data = json.dumps(data)
            return HttpResponse(data)
        # 获取当前日期：
        now_time = datetime.datetime.now()
        print("当前日期为：",now_time)
        print("当前月为：",now_time.month)
        sta1 = QXZdata.objects.filter(equip_id=equip_id, upl_time__month=now_time.month).values()
        for x in sta1:
            sta = {"upl_time": x["upl_time"].strftime('%Y-%m-%d %H:%M:%S'),"e_len": len(eval(x["qxz_data"])["data"]),
                "unit": [], "equip_id": x["equip_id_id"]}
            for i in eval(x["qxz_data"])["data"]:
                qxz_dict_2[i["eNum"]][0] = i["eValue"]
                d = copy.deepcopy(qxz_dict_2[i["eNum"]])   # 此处有坑 如果不深拷贝 后一次 qxz_dict[i["eNum"]][0] = i["eValue"] 赋值会把上次赋值替换掉
                ek = i["eKey"]
                d.append(ek)
                d.append(i["eNum"])
                sta["unit"].append(d)
                # qxz_dict[eval(x.qxz_data)['data'][0]["eNum"]]
            dat.append(sta)
        # print(dat)
        data = {"e_name": current_equip.equip_name, "dat": dat}
        # print("------",data)
        data = json.dumps(data)
        return HttpResponse(data)




# 气象站列表详情
class QXZ_Report_Detail(ListView):
    def get(self, request):
        qxz_dict_3 = copy.deepcopy(qxz_dict)
        page = int(request.GET.get('page'))
        print("page:", page)
        equip_id = request.GET.get('id')
        print("equip_id:", equip_id)
        f_tbegin = request.GET.get('begin')
        f_tend = request.GET.get('end')
        print("f_tbegin:", f_tbegin)
        print("f_tend:", f_tend)
        current_equip = Equip.objects.get(equip_id=equip_id)
        dat = []
        if f_tbegin:
            begindate = re.findall(r"\d+\.?\d*", f_tbegin)
            enddate = re.findall(r"\d+\.?\d*", f_tend)
            start_date = datetime.date(int(begindate[0]), int(begindate[1]), int(begindate[2]))
            end_date = datetime.date(int(enddate[0]), int(enddate[1]), int(enddate[2]))
            print("start_date:", start_date)
            print("end_date:", end_date)
            sta1 = QXZdata.objects.filter(
                equip_id=equip_id, upl_time__range=(start_date, end_date)).values()
            for x in sta1:
                sta = {"upl_time": x["upl_time"].strftime('%Y-%m-%d %H:%M:%S'), "unit": [], "equip_id": x["equip_id_id"]}
                for i in eval(x["qxz_data"])["data"]:
                    qxz_dict_3[i["eNum"]][0] = i["eValue"]
                    d = copy.deepcopy(qxz_dict_3[i["eNum"]])   # 此处有坑 如果不深拷贝 后一次 qxz_dict[i["eNum"]][0] = i["eValue"] 赋值会把上次赋值替换掉
                    ek = i["eKey"]
                    d.append(ek)
                    sta["unit"].append(d)
                    # qxz_dict[eval(x.qxz_data)['data'][0]["eNum"]]
                dat.append(sta)
            nums = len(dat)
            dat = dat[(10*(page-1)):(page*10)]
            data = {"dat": dat, "nums":nums}
            data = json.dumps(data)
            return HttpResponse(data)
        sta1 = QXZdata.objects.filter(equip_id=equip_id).values()
        for x in sta1:
            sta = {"upl_time": x["upl_time"].strftime('%Y-%m-%d %H:%M:%S'), "unit": [], "equip_id": x["equip_id_id"]}
            for i in eval(x["qxz_data"])["data"]:
                qxz_dict_3[i["eNum"]][0] = i["eValue"]
                d = copy.deepcopy(qxz_dict_3[i["eNum"]])   # 此处有坑 如果不深拷贝 后一次 qxz_dict[i["eNum"]][0] = i["eValue"] 赋值会把上次赋值替换掉
                ek = i["eKey"]
                d.append(ek)
                sta["unit"].append(d)
            dat.append(sta)
        nums = len(dat)
        dat = dat[(10*(page-1)):(page*10)]
        data = {"dat": dat, "nums":nums}
        data = json.dumps(data)
        return HttpResponse(data)


class QXZ_Report_Detail2(ListView):
    def get(self, request):
        pass
    def post(self,request):
        e_id = request.POST.get("e_id")
        qxz_list = QXZdata_New.objects.filter(equip_id=e_id)
        data = []
        for i in qxz_list:
            dat = {"e1":i.e1,"e2":i.e2,"e3":i.e3,"e4":i.e4,"e5":i.e5,"e6":i.e6,"e7":i.e7,"e8":i.e8,"e9":i.e9,"e10":i.e10,"e11":i.e11,"e12":i.e12,"e13":i.e13,"e14":i.e14}
            data.append({"upl_time":i.upl_time.strftime('%Y-%m-%d %H:%M:%S'),"dat":dat})
        nums = len(data)
        datas = {"data":data,"nums":nums}
        datas = json.dumps(datas)
        return HttpResponse(datas)



# 气象站开关名字
class QXZ_Switch_Name(ListView):
    def get(self,request):
        pass
    def post(self,request):
        imei = request.POST.get('imei')
        way = request.POST.get('way')
        sw_name = request.POST.get('sw_name')
        try:
            switch_obj = QXZswitchdata.objects.get(equip_id=imei)
        except:
            return HttpResponse("1")
        sw_name_list = eval(switch_obj.qxz_switch_data)
        for i in sw_name_list:
            if i["JK"] == int(way):
                i["name"] = sw_name
        print(sw_name_list)
        try:
            switch_obj.qxz_switch_data = sw_name_list
            switch_obj.save()
        except:
            return HttpResponse("1")
        data = "0"
        return HttpResponse(data)




# 气象站通信接口
class QXZ_Mqtt(ListView):
    def get(self,request):
        pass
    
    def post(self,request):
        req = request.POST.get('req')
        imei = request.POST.get('imei')
        topic = "/yfkj/qxz/sub/"+imei
        if req == "read":
            payload = {"ext":{"type":"status"},"cmd":"read"}
        elif req == "set":
            way = int(request.POST.get('way'))
            switch = int(request.POST.get('switch'))
            payload = {"cmd":"control","ext":{"JK":way,"status":switch}}
        elif req == "conf":
            payload = {"ext":{"type":"jkStatus"},"cmd":"read"}
        elif req == "interval":
            time = int(request.POST.get('time'))
            payload = {"cmd": "config","ext": {"interval": time}}
        
        cmd = {"topic":topic,"payload":json.dumps(payload),'qos':0}
        res = requests.post("http://www.yfzhwlw.com:8080/api/v2/mqtt/publish",
                                data=json.dumps(cmd), auth=HTTPBasicAuth("admin", "yfkj_6019"))
        print("res.status_code:", type(res.status_code))
        if res.status_code == 200:
            data = "0"
            return HttpResponse(data)
        else:
            data = "1"
            return HttpResponse(data)







# 新闻审核
class News_Check(ListView):
    def get(self,request):
        return render(request, 'backstageNet/infoManage/newsManage.html', context={'role':'superuser'})
    def post(self,request):
        
        news_id = request.POST.get('id')
        news_see_id = request.POST.get("ids")
    
        # 通过后删除
        if news_id:
            try:
                news_sta = CKArticle.objects.get(id=news_id)
                news_sta.delete()
                return HttpResponse("1")
            except:
                return HttpResponse("0")
        # 通过查看详情
        art_list = CKArticle.objects.filter(id=news_see_id)
        dat = []
        for i in art_list:
            dat.append({
                "title":i.title,
                "intro":i.intro,
                "time": i.upl_time.strftime('%Y-%m-%d %H:%M:%S'),
                "img": "%s"%i.head_img,
                "writer":i.writer,
                "author":i.author.username,
                "content":i.content,
                "art_type":i.art_type,
            })
        data = json.dumps(dat)
        return HttpResponse(data)
        
            
        


# 新闻审核页面
class News_Check_List(ListView):
    def get(self,request):
        hidden = request.GET.get('hidden')
        page = int(request.GET.get('page'))
        art_list = CKArticle.objects.filter(art_type=5,hidden=hidden)
        nums = art_list.count()
        print(nums)
        art = art_list[(10*(page-1)):(page*10)]
        return render(request, 'backstageNet/infoManage/newsManageList.html', context={"art":art,"nums":nums})
    def post(self,request):
        art_id = request.POST.get('id')
        req = request.POST.get('req')
        art_obj = CKArticle.objects.filter(id=art_id)
        # 编辑
        if req == "edit":
            data = []
            for i in art_obj:
                data.append({
                    "id":i.id,
                    "title":i.title,
                    "intro":i.intro,
                    "head_img":i.head_img.name,
                    "content":i.content,
                    "art_type":i.art_type,
                    "writer":i.writer,
                    "upl_time":i.upl_time.strftime('%Y-%m-%d %H:%M:%S'),
                    "author":i.author.username
                    })
        # 未审核删除
        elif req == "del":
            art_obj.delete()
            data = "1"
        # 通过审核
        elif req == "check":
            art_obj = CKArticle.objects.get(id=art_id)
            art_obj.hidden = True
            art_obj.save()
            data = "1"
        data = json.dumps(data)
        return HttpResponse(data)



# 新闻审核上传图片接口
class News_Photo(ListView):
    def get(self,request):
        pass
    def post(self,request):
        # e_id = request.POST.get('id')
        # news_sta = Article.objects.get(id=e_id)
        news_photo = request.FILES.get('upicture')
        if news_photo:
            print("新闻图片：", news_photo)
            news_photo_dir = 'hnews_photo/'
            end_name = news_photo.name.split('.')[-1]
            # 判断如果路径不存在，即创建路径
            if os.path.exists(news_photo_dir) == False:
                os.makedirs(news_photo_dir)
            img = Image.open(news_photo)
            # img = img.convert('RGB')
            now_time = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))
            pic_name = now_time + '.' + end_name
            print("pic_name:", pic_name)
            img.save(news_photo_dir + pic_name)
            news_photo = news_photo_dir + pic_name
            print("new_photo:",news_photo)
            data = {"code": 0,"msg": "","data": {"src": news_photo}}
        else:
            new_photo = "0"
            data = {"code": 404,"msg": "","data": {"src": news_photo}}
        data = json.dumps(data)
        return HttpResponse(data)



# 新闻发布
class News_Pub(ListView):
    def get(self,request):
        return render(request, 'backstageNet/info/newsPub.html', context={'role':'superuser'})
    def post(self,request):
        current_user = MyUser.objects.get(username="admin")
        news_photo = request.POST.get('upload')
        art_type = request.POST.get('type')
        writer = request.POST.get('writer')
        intro = request.POST.get('intro')
        title = request.POST.get('title')
        content = request.POST.get('content')
        news_id = request.POST.get("id")
        if news_id:
            if CKArticle.objects.filter(id=news_id).exists():
                CKArticle.objects.filter(id=news_id).update(
                    art_type=art_type,
                    writer = writer,
                    intro = intro,
                    title = title,
                    content = content,
                    head_img = news_photo
                )
                data= "1"
            else:
                data = "0"
        else:
            try:
                CKArticle.objects.create(author=current_user,art_type=art_type,writer=writer,intro=intro,title=title,content=content,head_img=news_photo)
                data = "1"
            except Exception as e:
                print(e)
                data = "0"
        return HttpResponse(data)



# 视频发布
class Video_Pub(ListView):
    def get(self,request):
        return render(request, 'backstageNet/info/videoPub.html', context={})
    def post(self,request):
        # 视频标题
        title = request.POST.get('title')
        # 视频简介
        intro = request.POST.get('intro')
        # 视频链接
        video = request.POST.get('video_url')
        admin = MyUser.objects.get(username="admin")
        video_img = request.POST.get('video_img')
        video_id =request.POST.get('id')
        if video_id:
            if Video_data.objects.filter(id=video_id).exists():
                Video_data.objects.filter(id=video_id).update(
                    title=title,
                    intro=intro,
                    video_url=video,
                    author=admin,
                    video_img=video_img,
                    )
                data = '1'
            else:
                data = '0'
        else:
            try:
                Video_data.objects.create(title=title,intro=intro,video_url=video,author=admin,video_img=video_img)
                data = "1"
            except Exception as e:
                print("-------错误信息为----------")
                print(e)
                data = "0"
            else:
                data = "0"

        return HttpResponse(data)



# 视频封面上传图片接口
class Video_Photo(ListView):
    def get(self,request):
        pass
    def post(self,request):
        # e_id = request.POST.get('id')
        # news_sta = Article.objects.get(id=e_id)
        video_photo = request.FILES.get('video_img')
        if video_photo:
            print("视频图片：", video_photo)
            video_photo_dir = 'hvideo_photo/'
            end_name = video_photo.name.split('.')[-1]
            # 判断如果路径不存在，即创建路径
            if os.path.exists(video_photo_dir) == False:
                os.makedirs(video_photo_dir)
            img = Image.open(video_photo)
            now_time = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))
            pic_name = now_time + '.' + end_name
            print("pic_name:", pic_name)
            img.save(video_photo_dir + pic_name)
            video_photo = video_photo_dir + pic_name
            print("new_photo:",video_photo)
            data = {"code": 0,"msg": "","data": {"src": video_photo}}
        else:
            video_photo = "0"
            data = {"code": 404,"msg": "","data": {"src": video_photo}}
        data = json.dumps(data)
        return HttpResponse(data)



# 视频上传接口
class Video_Upload(ListView):
    def get(self,request):
        pass
    def post(self,request):
        obj = request.FILES.get('upload')
        f = os.path.join('hvideos',obj.name).replace('\\','/')
        
        print(f)
        if not obj:
            return HttpResponse("0")
        dest=open(f,"wb")
        try:
            for chunk in obj.chunks():
                dest.write(chunk)
        finally:
            dest.close()
        video_dir = "hvideos/" + obj.name
        data = {"code": 0,"msg": "","data": {"src":video_dir}}
        data = json.dumps(data)
        return HttpResponse(data)



# 产品发布
class Equip_Pub(ListView):
    def get(self,request):
        return render(request, 'backstageNet/info/productPub.html', context={})
    def post(self,request):
        # 产品标题
        title = request.POST.get('title')
        # 产品简介
        
        intro = request.POST.get('intro')
        # 产品内容
        content = request.POST.get('content')
        # 产品图片
        head_img = request.POST.get('img_url')
        mobile = request.POST.get('mobile')

        admin = MyUser.objects.get(username="admin")
        equip_id = request.POST.get("id")
        if equip_id:
            if Product.objects.filter(id=equip_id).exists():
                try:
                    Product.objects.filter(id=equip_id).update(
                        title=title,
                        intro=intro,
                        content=content,
                        author=admin,
                        head_img=head_img,
                        mobile=mobile
                        )
                    data = "1"
                except Exception as e:
                    print("-----------错误信息为-------------")
                    print(e)
                    data = "0"
            else:
                data = "0"   
        else:
            if head_img:
                try:
                    Product.objects.create(title=title,intro=intro,content=content,author=admin,head_img=head_img,mobile=mobile)
                    data = "1"
                except Exception as e:
                    print("-----------错误信息为-------------")
                    print(e)
                    data = "0"
            else:
                data = "0"

        return HttpResponse(data)



# 产品封面上传图片接口
class Equip_Photo(ListView):
    def get(self,request):
        pass
    def post(self,request):
        pro_photo = request.FILES.get('pro_img')
        if pro_photo:
            print("视频图片：", pro_photo)
            pro_photo_dir = 'product_photo/'
            # 判断如果路径不存在，即创建路径
            end_name = pro_photo.name.split('.')[-1]
            if os.path.exists(pro_photo_dir) == False:
                os.makedirs(pro_photo_dir)
            img = Image.open(pro_photo)
            now_time = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))
            pic_name = now_time + '.' + end_name
            print("pic_name:", pic_name)
            img.save(pro_photo_dir + pic_name)
            pro_photo = pro_photo_dir + pic_name
            print("pro_photo:",pro_photo)
            data = {"code": 0,"msg": "","data": {"src": pro_photo}}
        else:
            pro_photo = "0"
            data = {"code": 404,"msg": "","data": {"src": pro_photo}}
        data = json.dumps(data)
        return HttpResponse(data)



# 采摘农场选择
class Farm_Choice(ListView):
    def get(self,request):
        pass
    def post(self,request):
        current_user = MyUser.objects.get(username="admin")
        farmlist = FarmList.objects.filter(user=current_user)
        dat = []
        for i in farmlist:
            dat.append({"name":i.name})
        dat = json.dumps(dat)
        return HttpResponse(dat)



# 四季采摘图片上传
class Pick_Photo(ListView):
    def get(self,request):
        pass
    def post(self,request):
        gar_photo = request.FILES.get('gar_img')
        if gar_photo:
            print("视频图片：", gar_photo)
            garden_photo_dir = 'garden_photo/'
            end_name = gar_photo.name.split('.')[-1]
            # 判断如果路径不存在，即创建路径
            if os.path.exists(garden_photo_dir) == False:
                os.makedirs(garden_photo_dir)
            img = Image.open(gar_photo)
            now_time = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))
            pic_name = now_time + '.' + end_name
            print("pic_name:", pic_name)
            img.save(garden_photo_dir + pic_name)
            gar_photo = garden_photo_dir + pic_name
            print("gar_photo:",gar_photo)
            data = {"code": 0,"msg": "","data": {"src": gar_photo}}
        else:
            pro_photo = "0"
            data = {"code": 404,"msg": "","data": {"src": gar_photo}}
        data = json.dumps(data)
        return HttpResponse(data)



# 四季采摘发布
class Garden_Pub(ListView):
    def get(self,request):
        return render(request, 'backstageNet/info/gardenPub.html', context={})
    def post(self,request):
        farm = request.POST.get('farm')
        name = request.POST.get('name')
        time = request.POST.get('time')
        pick_s = request.POST.get('start')
        pick_e = request.POST.get('end')
        ripe_time = request.POST.get('ripe')
        # 规模
        scale = request.POST.get('scale')
        addr = request.POST.get('addr')
        company = request.POST.get('company')
        pick_img = request.POST.get('img_url')
        garden_id = request.POST.get('id')
        print("garden_id:",garden_id)
        begindate = re.findall(r"\d+\.?\d*", pick_s)
        enddate = re.findall(r"\d+\.?\d*", pick_e)
        start_date = datetime.date(int(begindate[0]), int(begindate[1]), int(begindate[2]))
        end_date = datetime.date(int(enddate[0]), int(enddate[1]), int(enddate[2]))
        # 编辑更新
        if garden_id:
            if Pick_Pub.objects.filter(id=garden_id).exists():
                farm_obj = FarmList.objects.get(name=farm)
                Pick_Pub.objects.filter(id=garden_id).update(pick_s=start_date,pick_e=end_date,ripe_time=ripe_time,
                                                             scale=scale,addr=addr,farm=farm_obj,name=name,company=company,pick_img=pick_img,upl_time=time)
                data = "1"
            else:
                data = "0"
            return HttpResponse(data)
        else:
            try:
                farm_obj = FarmList.objects.get(name=farm)
                Pick_Pub.objects.create(farm=farm_obj,name=name,company=company,pick_img=pick_img,upl_time=time)
                data = "1"
                print(data)
            except Exception as e:
                print("-----------报错信息为-------------")
                print(e)
                data = "0"
            return HttpResponse(data)



# 民宿封面
class Dorm_Img(ListView):
    def get(self,request):
        pass
    def post(self,request):
        hotel_photo = request.FILES.get('hotel_photo')
        if hotel_photo:
            print("视频图片：", hotel_photo)
            hotel_photo_dir = 'hotel_photo/'
            end_name = hotel_photo.name.split('.')[-1]
            # 判断如果路径不存在，即创建路径
            if os.path.exists(hotel_photo_dir) == False:
                os.makedirs(hotel_photo_dir)
            img = Image.open(hotel_photo)
            now_time = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))
            pic_name = now_time + '.' + end_name
            print("pic_name:", pic_name)
            img.save(hotel_photo_dir + pic_name)
            hotel_photo = hotel_photo_dir + pic_name
            print("hotel_photo:",hotel_photo)
            data = {"code": 0,"msg": "","data": {"src": hotel_photo}}
        else:
            hotel_photo = "0"
            data = {"code": 404,"msg": "","data": {"src": hotel_photo}}
        data = json.dumps(data)
        return HttpResponse(data)



# 民宿介绍图
class Dorm_Photo(ListView):
    def get(self,request):
        pass
    def post(self,request):
        hotel_photos = request.FILES.get('hotel_photos')
        if hotel_photos:
            print("视频图片：", hotel_photos)
            hotel_photo_dir = 'hotel_photos/'
            end_name = hotel_photos.name.split('.')[-1]
            # 判断如果路径不存在，即创建路径
            if os.path.exists(hotel_photo_dir) == False:
                os.makedirs(hotel_photo_dir)
            img = Image.open(hotel_photos)
            now_time = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))
            pic_name = now_time + '.' + end_name
            print("pic_name:", pic_name)
            img.save(hotel_photo_dir + pic_name)
            hotel_photos = hotel_photo_dir + pic_name
            print("hotel_photos:",hotel_photos)
            data = {"code": 0,"msg": "","data": {"src": hotel_photos}}
        else:
            hotel_photos = "0"
            data = {"code": 404,"msg": "","data": {"src": hotel_photos}}
        data = json.dumps(data)
        return HttpResponse(data)



# 民宿发布
class Dorm_Pub(ListView):
    def get(self,request):
        return render(request, 'backstageNet/info/dormPub.html', context={})
    def post(self,request):
        current_user = MyUser.objects.get(username="admin")
        name = request.POST.get('name')
        price = request.POST.get('price')
        person = request.POST.get('person')
        mobile = request.POST.get('mobile')
        img_url = request.POST.get('img_url')
        addr = request.POST.get('addr')
        location = request.POST.get('location')
        intro = request.POST.get('intro')
        content = request.POST.get('content')
        pic_list = request.POST.get('pic_list')
        Hotel_id= request.POST.get("id")
        if Hotel_id:
            if Hotel_Info.objects.filter(id=Hotel_id).exists():
                try:
                    Hotel_Info.objects.filter(id=Hotel_id).update(
                        name=name,
                        price=price,
                        intro=intro,
                        addr=addr,
                        location=location,
                        person=person,
                        hotel_img=img_url,
                        hotel_tel=mobile,
                        content=content,
                        author=current_user,
                        )
                    data="1"
                except Exception as e:
                    print("-----------报错信息为-------------")
                    print(e)
                    data = "0"
                if data == "1":
                    try:
                        hotel_obj = Hotel_Info.objects.get(name=name)
                        pic_list = pic_list.split(',')
                        for i in pic_list:
                            Hotel_Photo.objects.filter(hotel=hotel_obj).update(hotel=hotel_obj,addr=i)
                    except Exception as aa:
                        print("滚动图保存错误")
                        print(aa)
            else:
                data = "0"
            return HttpResponse(data)
        else:
            try:
                Hotel_Info.objects.create(
                    name=name,
                    price=price,
                    intro=intro,
                    addr=addr,
                    location=location,
                    person=person,
                    hotel_img=img_url,
                    hotel_tel=mobile,
                    content=content,
                    author=current_user)
                data = "1"
            except Exception as e:
                print("-----------报错信息为-------------")
                print(e)
                data = "0"
            if data == "1":
                try:
                    hotel_obj = Hotel_Info.objects.get(name=name)
                    pic_list = pic_list.split(',')
                    for i in pic_list:
                        Hotel_Photo.objects.create(hotel=hotel_obj,addr=i)
                except Exception as aa:
                    print("滚动图保存错误")
                    print(aa)
            return HttpResponse(data)



# 旅游发布介绍图
class Sightsee_Photo(ListView):
    def get(self,request):
        pass
    def post(self,request):
        sightsee_photos = request.FILES.get('sightsee_photos')
        if sightsee_photos:
            print("视频图片：", sightsee_photos)
            sightsee_photos_dir = 'sightsee_photos/'
            end_name = sightsee_photos.name.split('.')[-1]
            # 判断如果路径不存在，即创建路径
            if os.path.exists(sightsee_photos_dir) == False:
                os.makedirs(sightsee_photos_dir)
            img = Image.open(sightsee_photos)
            now_time = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))
            pic_name = now_time + '.' + end_name
            print("pic_name:", pic_name)
            img.save(sightsee_photos_dir + pic_name)
            sightsee_photos = sightsee_photos_dir + pic_name
            print("sightsee_photos:",sightsee_photos)
            data = {"code": 0,"msg": "","data": {"src": sightsee_photos}}
        else:
            sightsee_photos = "0"
            data = {"code": 404,"msg": "","data": {"src": sightsee_photos}}
        data = json.dumps(data)
        return HttpResponse(data)


# 旅游发布
class Sightsee_Pub(ListView):
    def get(self,request):
        return render(request, 'backstageNet/info/SightseePub.html', context={})
    def post(self,request):
        name = request.POST.get('name')
        price = request.POST.get('price')
        sightsee_tel = request.POST.get('mobile')
        sightsee_img = request.POST.get('img_url')
        sightsee_stime = request.POST.get('stime')
        sightsee_etime = request.POST.get('etime')
        # begindate = re.findall(r"\d+\.?\d*", sightsee_stime)
        # enddate = re.findall(r"\d+\.?\d*", sightsee_etime)
        # start_date = datetime.date(int(begindate[0]), int(begindate[1]), int(begindate[2]))
        # end_date = datetime.date(int(enddate[0]), int(enddate[1]), int(enddate[2]))
        # 位置
        location = request.POST.get('location')
        addr = request.POST.get('addr')
        # 内容
        content = request.POST.get('content')
        # 简介
        desc = request.POST.get('desc')
        Sightsee_Info.objects.create(
            name=name,
            price=price,
            location=location,
            sightsee_stime=sightsee_stime,
            sightsee_etime=sightsee_etime,
            sightsee_img=sightsee_img,
            sightsee_tel=sightsee_tel,
            addr=addr,
            content=content,
            desc=desc)
        data = "0"
        return HttpResponse(data)



#我的发布
class My_Pub(ListView):
    def get(self,request):
        return render(request, 'backstageNet/infoList/myPub.html', context={})
    def post(self,request):
        pass


#我的发布列表
class My_Pub_List(ListView):
    def get(self,request):
        page = int(request.GET.get("page",1))
        hidden = request.GET.get("hidden")
        _type = request.GET.get("type")
        _list = CKArticle.objects.all()
        if _type:
            _list = _list.filter(art_type=_type)
        if hidden:
            _list = _list.filter(hidden=hidden)
        nums = _list.count()
        art_list = _list[(10*(page-1)):(page*10)]
        return render(request, 'backstageNet/infoList/myPubList.html', context={"art_list":art_list,"nums":nums})
    def post(self,request):
        pass


# 视频审核
class Video_Check(ListView):
    def get(self,request):
        return render(request, 'backstageNet/infoManage/videoManage.html', context={'role':'superuser'})
    def post(self,request):
        
        video_id = request.POST.get('id')
        video_see_id = request.POST.get("ids")
        # 审核通过后删除
        if video_id:
            try:
                video_sta = Video_data.objects.get(id=video_id)
                video_sta.delete()
                return HttpResponse("1")
            except:
                return HttpResponse("0")
        # 审核通过查看详情
        art_list = Video_data.objects.filter(id=video_see_id)
        dat = []
        for i in art_list:
            dat.append({
                "title":i.title,
                "intro":i.intro,
                "video_url": i.video_url.name,
                "time": i.publish_date.strftime('%Y-%m-%d %H:%M:%S'),
                "video_img": "%s"%i.video_img.name,
                "author":i.author.username
            })
        data = json.dumps(dat,ensure_ascii=False)
        return HttpResponse(data)
        


# 视频审核页面
class Video_Check_List(ListView):
    def get(self,request):
        hidden = request.GET.get('hidden')
        page = int(request.GET.get('page'))
        art_list = Video_data.objects.filter(hidden=hidden)
        nums = art_list.count()
        art = art_list[(10*(page-1)):(page*10)]
        return render(request, 'backstageNet/infoManage/videoManageList.html', context={"art":art,"nums":nums})
    def post(self,request):
        art_id = request.POST.get('id')
        req = request.POST.get('req')
        art_obj = Video_data.objects.filter(id=art_id)
        # 编辑
        data = []
        if req == "edit":
            for i in art_obj:
                data.append({
                     "id":i.id,
                    "title":i.title,
                    "intro":i.intro,
                    "video_img":i.video_img.name,
                    "video_url":i.video_url.name,
                    "author":i.author.username,
                    "time":i.publish_date.strftime('%Y-%m-%d %H:%M:%S'),
                    })
        #删除
        elif req == "del":
            art_obj.delete()
            data = "1"
        #保存
        elif req == "check":
            art_obj = Video_data.objects.get(id=art_id)
            art_obj.hidden = True
            art_obj.save()
            data = "1"
        data = json.dumps(data)
        return HttpResponse(data)



# 产品审核
class Equip_Check(ListView):
    def get(self,request):
        return render(request, 'backstageNet/infoManage/productManage.html', context={'role':'superuser'})
    def post(self,request):
       
        delete = request.POST.get('id')
        product_see_id = request.POST.get("ids")
        # 审核通过后删除
        if delete:
            try:
                video_sta = Product.objects.get(id=delete)
                video_sta.delete()
                return HttpResponse("1")
            except:
                return HttpResponse("0")
        # 审核通过查看详情
        art_list = Product.objects.filter(id=product_see_id)
        dat = []
        for i in art_list:
            dat.append({
                "title":i.title,
                "intro":i.intro,
                "content": i.content,
                "time": i.publish_date.strftime('%Y-%m-%d %H:%M:%S'),
                "head_img": "%s"%i.head_img,
                "mobile":i.mobile,
                "author":i.author.username
               
            })
        data = json.dumps(dat)
        return HttpResponse(data)
        
            
       
# 产品审核页面
class Equip_Check_List(ListView):
    def get(self,request):
        hidden = request.GET.get('hidden')
        page = int(request.GET.get('page'))
        art_list = Product.objects.filter(hidden=hidden)
        nums = art_list.count()
        art = art_list[(10*(page-1)):(page*10)]
        return render(request, 'backstageNet/infoManage/productManageList.html', context={"art":art,"nums":nums})
    def post(self,request):
        art_id = request.POST.get('id')
        req = request.POST.get('req')
        art_obj = Product.objects.filter(id=art_id)
        # 编辑 
        if req == "edit":
            data = []
            for i in art_obj:
                data.append({
                    "id":i.id,
                    "title":i.title,
                    "intro":i.intro,
                    "head_img":i.head_img,
                    "content":i.content,
                    "mobile":i.mobile,
                    "author":i.author.username,
                    "time": i.publish_date.strftime('%Y-%m-%d %H:%M:%S'),
                    })
        #删除
        elif req == "del":
            art_obj.delete()
            data = "1"
        #审核通过
        elif req == "check":
            art_obj = Product.objects.get(id=art_id)
            art_obj.hidden = True
            art_obj.save()
            data = "1"
        data = json.dumps(data)
        return HttpResponse(data)
        


# 四季采摘审核
class Garden_Check(ListView):
    def get(self,request):
        return render(request, 'backstageNet/infoManage/pickManage.html', context={'role':'superuser'})
    def post(self,request):
        delete = request.POST.get('id')
        garden_see_id = request.POST.get("ids")
        if delete:
            try:
                garden_sta = Pick_Pub.objects.get(id=delete)
                garden_sta.delete()
                return HttpResponse("1")
            except:
                return HttpResponse("0")
        art_list = Pick_Pub.objects.filter(id=garden_see_id)
        dat = []
        # 查看详情
        for i in art_list:
            dat.append({
                "name":i.name,
                "company":i.company,
                "time": i.upl_time,
                "img": "%s"%i.pick_img,
                "farm":i.farm.name
            })
        data = json.dumps(dat)
        return HttpResponse(data)
        

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         
# 四季采摘审核页面
class Garden_Check_List(ListView):
    def get(self,request):
        hidden = request.GET.get('hidden')
        page = int(request.GET.get('page'))
        art_list = Pick_Pub.objects.filter(hidden=hidden)
        nums = art_list.count()
        art = art_list[(10*(page-1)):(page*10)]
        return render(request, 'backstageNet/infoManage/pickManageList.html', context={"art":art,"nums":nums})
    def post(self,request):
        art_id = request.POST.get('id')
        req = request.POST.get('req')
        art_obj = Pick_Pub.objects.filter(id=art_id)
        # 编辑
        if req == "edit":
            data = []
            for i in art_obj:
                data.append({
                    "id":i.id,
                    "name":i.name,
                    "company":i.company,
                    "pick_img":i.pick_img,
                    "time": i.upl_time,
                    "farm":i.farm.name
                    })
        #删除
        elif req == "del":
            art_obj.delete()
            data = "1"
        #审核通过
        elif req == "check":
            art_obj = Pick_Pub.objects.get(id=art_id)
            art_obj.hidden = True
            art_obj.save()
            data = "1"
        data = json.dumps(data,ensure_ascii=False)
        return HttpResponse(data)



# 民宿审核
class Dorm_Check(ListView):
    def get(self,request):
        return render(request, 'backstageNet/infoManage/dormManage.html', context={'role':'superuser'})
    def post(self,request):
        hote_see_id = request.POST.get('ids')
        delete = request.POST.get('id')
       
        #已通过的删除
        if delete:
            try:
                hote_sta = Hotel_Info.objects.get(id=delete)
                hote_sta.delete()
                return HttpResponse("1")
            except:
                return HttpResponse("0")
        art_list = Hotel_Info.objects.filter(id=hote_see_id)
        dat = []
        # 通过后查看详情
        for i in art_list:
            dat.append({
                "name":i.name,
                "price":i.price,
                "intro":i.intro,
                "addr":i.addr,
                "person":i.person,
                "hotel_tel":i.hotel_tel,
                "author":i.author.username,
                "content":i.content,
                "location":i.location,
                # "time": i.upl_time.strftime('%Y-%m-%d %H:%M:%S'),
                "img": "%s"%i.hotel_img,
            })
        data = json.dumps(dat,ensure_ascii=False)
        return HttpResponse(data)



# 民宿审核页面
class Dorm_Check_List(ListView):
    def get(self,request):
        hidden = request.GET.get('hidden')
        page = int(request.GET.get('page'))
        art_list = Hotel_Info.objects.filter(hidden=hidden)
        nums = art_list.count()
        art = art_list[(10*(page-1)):(page*10)]
        return render(request, 'backstageNet/infoManage/dormManageList.html', context={"art":art,"nums":nums})
    def post(self,request):
        art_id = request.POST.get('id')
        req = request.POST.get('req')
        art_obj = Hotel_Info.objects.filter(id=art_id)
        art = Hotel_Photo.objects.filter(hotel=art_id)
        data = []
        # 编辑
        if req == "edit":
            
            for i in art_obj:
                data.append({
                    "id":i.id,
                    "name":i.name,
                    "price":i.price,
                    "intro":i.intro,
                    "addr":i.addr,
                    "location":i.location,
                    "person":i.person,
                    "hotel_img":i.hotel_img,
                    "hotel_tel":i.hotel_tel,
                    "content":i.content,
                    # "upl_time":i.upl_time.strftime('%Y-%m-%d %H:%M:%S'),
                    })
            for x in art:
                data.append({"addr_photo":x.addr})
                # data.append(x.addr)       
        #删除
        elif req == "del":
            art_obj.delete()
            data = "1"
        #审核通过
        elif req == "check":
            art_obj = Hotel_Info.objects.get(id=art_id)
            art_obj.hidden = True
            art_obj.save()
            data = "1"
        data = json.dumps(data,ensure_ascii=False)
        return HttpResponse(data)

# 农场审核
class Farm_Check(ListView):
    def get(self,request):
        return render(request, 'backstageNet/infoManage/farmManage.html', context={'role':'superuser'})
    def post(self,request):
        delete = request.POST.get('id')
        garden_see_id = request.POST.get("ids")
        if delete:
            try:
                garden_sta = Pick_Pub.objects.get(id=delete)
                garden_sta.delete()
                return HttpResponse("1")
            except:
                return HttpResponse("0")
        art_list = Pick_Pub.objects.filter(id=garden_see_id)
        dat = []
        # 查看详情
        for i in art_list:
            dat.append({
                "name":i.name,
                "company":i.company,
                "time": i.upl_time,
                "img": "%s"%i.pick_img,
                "farm":i.farm.name
            })
        data = json.dumps(dat)
        return HttpResponse(data)
        

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         
# 农场审核页面
class Farm_Check_List(ListView):
    def get(self,request):
        hidden = request.GET.get('hidden')
        page = int(request.GET.get('page'))
        art_list = Pick_Pub.objects.filter(hidden=hidden)
        nums = art_list.count()
        art = art_list[(10*(page-1)):(page*10)]
        return render(request, 'backstageNet/infoManage/farmManageList.html', context={"art":art,"nums":nums})
    def post(self,request):
        art_id = request.POST.get('id')
        req = request.POST.get('req')
        art_obj = Pick_Pub.objects.filter(id=art_id)
        # 编辑
        if req == "edit":
            data = []
            for i in art_obj:
                data.append({
                    "id":i.id,
                    "name":i.name,
                    "company":i.company,
                    "pick_img":i.pick_img,
                    "time": i.upl_time,
                    "farm":i.farm.name
                    })
        #删除
        elif req == "del":
            art_obj.delete()
            data = "1"
        #审核通过
        elif req == "check":
            art_obj = Pick_Pub.objects.get(id=art_id)
            art_obj.hidden = True
            art_obj.save()
            data = "1"
        data = json.dumps(data,ensure_ascii=False)
        return HttpResponse(data)


# 景点审核
class Sightsee_Check(ListView):
    def get(self,request):
        return render(request, 'backstageNet/infoManage/sightseeManage.html', context={'role':'superuser'})
    def post(self,request):
        delete = request.POST.get('id')
        garden_see_id = request.POST.get("ids")
        if delete:
            try:
                garden_sta = Pick_Pub.objects.get(id=delete)
                garden_sta.delete()
                return HttpResponse("1")
            except:
                return HttpResponse("0")
        art_list = Pick_Pub.objects.filter(id=garden_see_id)
        dat = []
        # 查看详情
        for i in art_list:
            dat.append({
                "name":i.name,
                "company":i.company,
                "time": i.upl_time,
                "img": "%s"%i.pick_img,
                "farm":i.farm.name
            })
        data = json.dumps(dat)
        return HttpResponse(data)
        

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         
# 景点审核页面
class Sightsee_Check_List(ListView):
    def get(self,request):
        hidden = request.GET.get('hidden')
        page = int(request.GET.get('page'))
        art_list = Pick_Pub.objects.filter(hidden=hidden)
        nums = art_list.count()
        art = art_list[(10*(page-1)):(page*10)]
        return render(request, 'backstageNet/infoManage/sightseeManageList.html', context={"art":art,"nums":nums})
    def post(self,request):
        art_id = request.POST.get('id')
        req = request.POST.get('req')
        art_obj = Pick_Pub.objects.filter(id=art_id)
        # 编辑
        if req == "edit":
            data = []
            for i in art_obj:
                data.append({
                    "id":i.id,
                    "name":i.name,
                    "company":i.company,
                    "pick_img":i.pick_img,
                    "time": i.upl_time,
                    "farm":i.farm.name
                    })
        #删除
        elif req == "del":
            art_obj.delete()
            data = "1"
        #审核通过
        elif req == "check":
            art_obj = Pick_Pub.objects.get(id=art_id)
            art_obj.hidden = True
            art_obj.save()
            data = "1"
        data = json.dumps(data,ensure_ascii=False)
        return HttpResponse(data)




# 产品发布图片上传
class Product_Photo(ListView):
    def get(self,request):
        pass
    def post(self,request):
       pass



# 新闻审核上传图片接口
class Test_Photo(ListView):
    def get(self,request):
        pass
    def post(self,request):
        # e_id = request.POST.get('id')
        # news_sta = Article.objects.get(id=e_id)
        news_photo = request.FILES['upload']
        if news_photo:
            print("新闻图片：", news_photo)
            news_photo_dir = 'media/uploads/'
            end_name = news_photo.name.split('.')[-1]
            # 判断如果路径不存在，即创建路径
            if os.path.exists(news_photo_dir) == False:
                os.makedirs(news_photo_dir)
            img = Image.open(news_photo)
            now_time = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))
            pic_name = now_time + '.' + end_name
            print("pic_name:", pic_name)
            img.save(news_photo_dir + pic_name)
            news_photo = news_photo_dir + pic_name
            print("new_photo:",news_photo)
            data = {"uploaded": 1,"fileName": pic_name,"url": news_photo}
        else:
            new_photo = "0"
            data = {"code": 404,"msg": "","data": {"src": news_photo}}
        data = json.dumps(data)
        return HttpResponse(data)



class CKArticle_View(ListView):
    def get(self,request):
        pass
    def post(self,request):
        current_user = MyUser.objects.get(username="admin")
        news_photo = request.POST.get('upload')
        writer = request.POST.get('writer')
        intro = request.POST.get('intro')
        title = request.POST.get('title')
        art_type = request.POST.get('art_type')
        content = request.POST.get('content')
        try:
            # CKArticle.objects.create(auther=current_user.username,art_type=art_type,writer=writer,intro=intro,title=title,content=content,head_img=news_photo)
            CKArticle.objects.create(art_type=art_type,writer=writer,intro=intro,title=title,content=content,head_img=news_photo)
            data = "1"
        except Exception as e:
            print("错误信息为",e)
            data = "0"
        return HttpResponse(data)



#园区筛选
class Park_Land(ListView):
    def get(self,request):
        user_name = MyUser.objects.get(username="admin")
        art_list = GardenArea.objects.filter(user=user_name)
        data=[]
        for i in art_list:
            data.append({"name":i.name,"id":i.id})
        data = json.dumps(data)
        return HttpResponse(data)



# 农场管理 
class Garden_Manage_New(ListView):
    def get(self,request):
        gardenid = int(request.GET.get("ids"))
        user_name = MyUser.objects.filter(username="admin")
        for i in user_name:
            if i.username == "admin":
                art_list = FarmList.objects.all()
                nums = art_list.count()
            else:
                art_list = FarmList.objects.filter(garden=gardenid)
                print("aaa")
                print(art_list)
                for i in art_list:
                    print(i.name)
                nums = art_list.count()
        page = int(request.GET.get('page'))
        art = art_list[(9*(page-1)):(page*9)]
        return render(request, 'backstageNet/production/gardenNew.html', context={"art":art,"nums":nums})
    def post(self,request):
        req = request.POST.get("req")
        farm_id = request.POST.get('id')
        art_list=FarmList.objects.filter(id=farm_id)
        print(art_list)
        data = []
        #编辑回显数据
        if req =="edit":
            for i in art_list:
                if i.manage_user:
                    data.append({
                        "id":i.id,
                        "name":i.name,
                        "user":i.user.username,
                        "manage_user":i.manage_user.name,
                        "area":i.area,
                        "curr_var":i.curr_var,
                        "farm_img":i.farm_img,
                        "farm_desc":i.farm_desc
                        })
                else:
                    data.append({
                        "id":i.id,
                        "name":i.name,
                        "user":i.user.username,
                        "manage_user":"",
                        "area":i.area,
                        "curr_var":i.curr_var,
                        "farm_img":i.farm_img,
                        "farm_desc":i.farm_desc
                        })
        #删除数据  
        if req == 'del':
            pickid = Pick_Pub.objects.filter(farm=farm_id)
            storeid = Store_Manage.objects.filter(farm=farm_id)
            art = FarmList.objects.get(id=farm_id)
            if pickid.count() ==0 and storeid.count() ==0:
                art.delete()
                data="1"
            elif pickid.count() !=0 and storeid.count() ==0:
                pickid.delete()
                art.delete()
                data="1"
            elif pickid.count()  ==0 and storeid.count()  !=0:
                storeid.delete()
                art.delete()
                data="1"
            elif pickid.count()  !=0 and storeid.count()  !=0:
                pickid.delete()
                storeid.delete()
                art.delete()
                data="1"
        data = json.dumps(data,ensure_ascii=False)
        return HttpResponse(data)
            



# 修改农场管理 
class Garden_Manage_View(ListView):
    def get(self,request):
        return render(request, 'backstageNet/production/gardenManage.html', context={})
    def post(self,request):
        #农场id
        farm_id = request.POST.get('id')
        #农场名称
        name = request.POST.get('name')
        #农场介绍
        farm_desc = request.POST.get('content')
        #农场面积
        area = request.POST.get('area')
        #农场品种
        curr_var = request.POST.get('curr_var')
        #农场图片
        farm_img = request.POST.get('img_url')
        #园区id
        gardenid = request.POST.get("ids")
        #修改当前数据
        user_name = MyUser.objects.get(username="admin")
        if farm_id:
            try:
                hote_sta = FarmList.objects.filter(id=farm_id).update(
                    name=name,
                    farm_desc=farm_desc,
                    area=area,
                    curr_var=curr_var,
                    farm_img=farm_img,
                    user=user_name,
                )
                data="1"
            except Exception as e:
                print(e)
                data="0"
        else:
            try:      
                gardens=GardenArea.objects.get(id=gardenid)
                FarmList.objects.create(
                    name=name,
                    farm_desc=farm_desc,
                    area=area,
                    curr_var=curr_var,
                    farm_img=farm_img,
                    user=user_name,
                    garden=gardens
                )
                data="1"
            except Exception as e:
                print(e)
                data="0"
        return HttpResponse(data)




# 新建人员管理
class Garden_User_View(ListView):
    def get(self,request):
        return render(request, 'backstageNet/production/workerManage.html', context={})
    def post(self,request):
        #管理者id
        farm_id = request.POST.get('id')
        #管理者名称
        name = request.POST.get('name')
        #性别
        gender = request.POST.get('sex')
        #联系方式
        mobile = request.POST.get('mobile')
        #管理农场
        farm_name = request.POST.get("city")
        #修改
        if farm_id:
            try:

                hote_sta = FarmUser.objects.filter(id=farm_id).update(
                    name=name,
                    gender=gender,
                    mobile=mobile,
                )
                data="1"
                if data=="1":
                    farms =FarmUser.objects.get(name=name)
                    farm = FarmList.objects.filter(name=farm_name).update(
                        manage_user=farms
                    )
                    data="1"
            except Exception as e:
                print(e)
                data="0"
        else:
            #增加
            try:
                FarmUser.objects.create(
                    name=name,
                    gender=gender,
                    mobile=mobile,
                )
                data="1"
                if data=="1":
                    farms =FarmUser.objects.get(name=name)
                farm = FarmList.objects.filter(name=farm_name).update(
                    manage_user=farms
                )
                data="1"
            except Exception as e:
                print(e)
                data="0"
        return HttpResponse(data)




# 人员管理 
class Garden_User_New(ListView):
    def get(self,request):
        user_name = MyUser.objects.get(username="admin")
        art_list = FarmUser.objects.all()
        nums = art_list.count()        
        page = int(request.GET.get('page'))
        art = art_list[(9*(page-1)):(page*9)]
        return render(request, 'backstageNet/production/workerNew.html', context={"art":art,"nums":nums})
    def post(self,request):
        req = request.POST.get("req")
        farmuser_id = request.POST.get('id')
        art_list = FarmUser.objects.filter(id=farmuser_id)
        data = []
        #编辑数据回显
        if req == "edit":
            for i in art_list:
                data.append({
                    "id":i.id,
                    "name":i.name,
                    "gender":i.gender,
                    "mobile":i.mobile 
                    })
        #删除       
        elif req == 'del':
            art_list.delete()
            data = "1"
        data = json.dumps(data,ensure_ascii=False)
        return HttpResponse(data)




#  库存新建
class Repertory_View(ListView):
    def get(self,request):
        return render(request, 'backstageNet/production/repertoryManage.html', context={})
    def post(self,request):
         #库存id
        store_id = request.POST.get('id')
        #物料名称
        name = request.POST.get('name')
        #物料类别
        rtype = request.POST.get('rtype')
        #规格
        spec = request.POST.get('spec')
        #库存
        rese = request.POST.get('rese')
        #修改
        if store_id:
            try:
                hote_sta = Store_Manage.objects.filter(id=store_id).update(
                    name=name,
                    rtype=rtype,
                    spec=spec,
                    rese=rese,
                )
                data = "1"
            except Exception as e:
                print(e)
                data = "0"
        else:
            #新增
            try:
                Store_Manage.objects.create(
                    name=name,
                    rtype=rtype,
                    spec=spec,
                    rese=rese,
                )
                data = "1"
            except Exception as e:
                print(e)
                data = "0"
        return HttpResponse(data)




# 库存管理
class Repertory_New(ListView):
    def get(self,request):
        user_name = MyUser.objects.get(username="admin")
        ids = int(request.GET.get('ids'))
        try:
            art = FarmList.objects.filter(garden=ids,user=user_name)
            if art:
                art_list = Store_Manage.objects.all()
            print(art_list)
        except Exception as e:
            print(e)
            art_list = ""
        nums = art_list.count()
        page = int(request.GET.get('page'))
        art = art_list[(9*(page-1)):(page*9)]
        return render(request, 'backstageNet/production/repertoryNew.html', context={"art":art,"nums":nums})
    def post(self,request):
        req = request.POST.get("req")
        store_id = request.POST.get('id')
        art_list=Store_Manage.objects.filter(id=store_id)
        data = []
        #编辑数据回显
        if req == "edit":
            for i in art_list:
                data.append({
                    "id":i.id,
                    "name":i.name,
                    "rtype":i.rtype,
                    "spec":i.spec,
                    "rese":i.rese
                    })
        #删除
        elif req == 'del':
            art_list.delete()
            data = "1"
        data = json.dumps(data,ensure_ascii=False)
        return HttpResponse(data)




# 库存管理(出库，入库)
class Repertory_New_View(ListView):
    def get(self,request):
        pass
    def post(self,request):
        req = request.POST.get("req")
        store_id = request.POST.get('id')
        num = int(request.POST.get('num'))
        print("num",num)
        art_list = Store_Manage.objects.filter(id=store_id)
        #出库
        if req == "see":
            for i in art_list:
                res = int(i.rese)
                r = res-num
                if r >0 or  r == 0:
                    Store_Manage.objects.filter(id=store_id).update(rese=r)
                    data = "1"
                else:
                    data = "0"
            return HttpResponse(data)
        #入库
        elif req == "add":
            for i in art_list:
                res = int(i.rese)
                r = res+num
                if r:
                    Store_Manage.objects.filter(id=store_id).update(rese=r)
                    data = "1"
                else:
                    data = "0"
            return HttpResponse(data)




#  销售管理
class Sell_View(ListView):
    def get(self,request):
        current_user = MyUser.objects.get(username="admin")
        try:
            # user_gar = GardenArea.objects.get(user=current_user)
            farm_list = FarmList.objects.filter(garden__user=current_user)
        except Exception as e:
            print(e)
            farm_list = ""
        nums = farm_list.count()
        return render(request, 'backstageNet/production/sellManage.html', context={"farm_list":farm_list,"nums":nums})
    def post(self,request):
        current_user = MyUser.objects.get(username="admin")
        page = int(request.POST.get("page"))
        dat = []
        try:
            # user_gar = GardenArea.objects.get(user=current_user)
            # farm_list = FarmList.objects.filter(garden=user_gar)
            farm_list = FarmList.objects.filter(garden__user=current_user)
            for i in farm_list:
                for x in Sell_Manage.objects.filter(farm=i):
                    dat.append({
                        "id":x.id,
                        "farm":x.farm.name,"name":x.name,
                        "num":x.num,"money":x.money,
                        "time":x.upl_time.strftime('%Y-%m-%d %H:%M:%S')
                    })
        except Exception as e:
            print(e)
            dat = []
        nums = len(dat)
        dat = dat[(9*(page-1)):(page*9)]
        data = json.dumps({"dat":dat,"nums":nums})
        return HttpResponse(data)



# 销售新建
class Sell_New(ListView):
    def get(self,request):
        pass
    def post(self,request):
        farm = request.POST.get("farm")
        name = request.POST.get("name")
        num = request.POST.get("num")
        money = request.POST.get("money")
        time = request.POST.get("time")
        s_id = request.POST.get("id")
        if s_id:
            try:
                farm_obj = FarmList.objects.get(name=farm)
                sell_obj = Sell_Manage.objects.get(id=s_id)
                sell_obj.farm = farm_obj
                sell_obj.name = name
                sell_obj.num = num
                sell_obj.money = money
                sell_obj.upl_time = time
                sell_obj.save()
                data = "1"
            except Exception as e:
                print(e)
                data = "0"
        else:
            try:
                farm_obj = FarmList.objects.get(name=farm)
                Sell_Manage.objects.create(farm=farm_obj,name=name,num=num,money=money,upl_time=time)
                data = "1"
            except Exception as e:
                print(e)
                data = "0"
        return HttpResponse(data)


# 销售删除
class Sell_Del(ListView):
    def get(self,request):
        pass
    def post(self,request):
        s_id = request.POST.get("id")
        try:
            sell_obj = Sell_Manage.objects.get(id=s_id)
            sell_obj.delete()
            data = "1"
        except Exception as e:
            print(e)
            data = "0"
        return HttpResponse(data)



# 数据分析
class Cropdata(ListView):
    def get(self,request):
        return render(request, 'backstageNet/production/cropdata.html', context={})
    def post(self,request):
        pass


# 种植统计
class CropCount(ListView):
    def get(self,request):
        return render(request, 'backstageNet/production/cropcount.html', context={})
    def post(self,request):
        crop_count = request.POST.get('crop_count')
        area = request.POST.get('area')
        crop_id = request.POST.get('id')
        upl_time = request.POST.get("upl_time")
        cropname = request.POST.get('cropname')
        city = request.POST.get("city")
        count=crop_count + city
        print(count)
        #修改
        if crop_id:
            try:
                crops =GardenArea.objects.get(name=area)
                crop = Areacrop.objects.filter(id=crop_id).update(
                    cropname=cropname,
                    area=crops,
                    upl_time=upl_time,
                    crop_count=count,
                )
                data = "1"
            except Exception as e:
                print(e)
                data = "0"
        else:
            #新增
            try:
                crops =GardenArea.objects.get(name=area)
                Areacrop.objects.create(
                    cropname=cropname,
                    area=crops,
                    upl_time=upl_time,
                    crop_count=count,
                )
                data = "1"
            except Exception as e:
                print(e)
                data = "0"
        return HttpResponse(data)




# 种植管理
class CropCount_View(ListView):
    def get(self,request):
        user_name = MyUser.objects.get(username="admin")
        art = GardenArea.objects.filter(user=user_name)
        page = int(request.GET.get("page"))
        dat = []
        for i in art:
            art_list = Areacrop.objects.filter(area=i)
            for x in art_list:
                if x.end_time:
                    time = int(x.upl_time.strftime("%Y%m%d"))
                    time_now = int(x.end_time.strftime("%Y%m%d"))
                    data = time_now-time
                    curro = "当前阶段已结束" 
                    h2 = {"cropname":x.cropname,
                        "area":x.area.name,
                        "crop_count":x.crop_count,
                        "img":x.area.img,
                        "time":data,
                        "upl_time":x.upl_time.strftime('%Y-%m-%d'),
                        "id":x.id
                        } 
                    dat.append({"data":h2,"curro":curro})
                else:
                    time = int(x.upl_time.strftime("%Y%m%d"))
                    time_now = int(timezone.now().strftime("%Y%m%d"))
                    data = time_now-time
                    print(data)
                    curro = "" 
                    h2 = {"cropname":x.cropname,
                        "area":x.area.name,
                        "crop_count":x.crop_count,
                        "img":x.area.img,
                        "time":data,
                        "id":x.id,
                        "upl_time":x.upl_time.strftime('%Y-%m-%d')
                        } 
                    dat.append({"data":h2,"curro":curro})
        nums = len(dat)
        dat = dat[(9*(page-1)):(page*9)]
        data = json.dumps({"dat":dat,"nums":nums})
        return HttpResponse(data)
    def post(self,request):
        req = request.POST.get("req")
        areacropid = request.POST.get("id")
        art_list = Areacrop.objects.filter(id=areacropid)
        data = []
        #结束时间
        if req == "end":
            for x in art_list:
                Areacrop.objects.filter(id=areacropid).update(
                    end_time=datetime.datetime.now()
                )
            data = "1"
        #编辑数据返现
        elif req == "edit":
            for i in art_list: 
                data.append({
                    "id":i.id,
                    "area":i.area.name,
                    "crop_count":i.crop_count,
                    "cropname":i.cropname,
                    "upl_time":i.upl_time.strftime('%Y-%m-%d %H:%M:%S')
                })
        #删除
        elif req == "del":
            art_list.delete()
            data = "1"
        data = json.dumps(data)
        return HttpResponse(data)


# 个人采摘
class Pick(ListView):
    def get(self,request):
        current_user = MyUser.objects.get(username="admin")
        try:
            # user_gar = GardenArea.objects.get(user=current_user)
            farm_list = FarmList.objects.filter(garden__user=current_user)
        except Exception as e:
            print(e)
            farm_list = ""
        nums = farm_list.count()
        return render(request, 'backstageNet/production/pick.html', context={"farm_list":farm_list,"nums":nums})
    def post(self,request):
        current_user = MyUser.objects.get(username="admin")
        page = int(request.POST.get("page"))
        dat = []
        try:
            farm_list = FarmList.objects.filter(garden__user=current_user)
            for i in farm_list:
                for x in Person_Pick.objects.filter(farm=i):
                    dat.append({
                        "id":x.id,
                        "farm":x.farm.name,"name":x.name,
                        "num":x.num,"var":x.var,
                        "time":x.upl_time.strftime('%Y-%m-%d %H:%M:%S')
                    })
        except Exception as e:
            print(e)
            dat = []
        nums = len(dat)
        dat = dat[(9*(page-1)):(page*9)]
        data = json.dumps({"dat":dat,"nums":nums})
        return HttpResponse(data)




# 采摘新建
class Pick_New(ListView):
    def get(self,request):
        pass
    def post(self,request):
        farm = request.POST.get("farm")
        name = request.POST.get("name")
        num = request.POST.get("num")
        var = request.POST.get("var")
        time = request.POST.get("time")
        p_id = request.POST.get("id")
        if p_id:
            try:
                farm_obj = FarmList.objects.get(name=farm)
                pick_obj = Person_Pick.objects.get(id=p_id)
                pick_obj.farm = farm_obj
                pick_obj.name = name
                pick_obj.num = num
                pick_obj.var = var
                pick_obj.upl_time = time
                pick_obj.save()
                data = "1"
            except Exception as e:
                print(e)
                data = "0"
        else:
            try:
                farm_obj = FarmList.objects.get(name=farm)
                Person_Pick.objects.create(farm=farm_obj,name=name,num=num,var=var,upl_time=time)
                data = "1"
            except Exception as e:
                print(e)
                data = "0"
        return HttpResponse(data)



# 采摘删除
class Pick_Del(ListView):
    def get(self,request):
        pass
    def post(self,request):
        p_id = request.POST.get("id")
        try:
            pick_obj = Person_Pick.objects.get(id=p_id)
            pick_obj.delete()
            data = "1"
        except Exception as e:
            print(e)
            data = "0"
        return HttpResponse(data)




# 类型分析
class Type_View(ListView):
    def get(self,request):
        current_user = MyUser.objects.get(username="admin")
        area_list = GardenArea.objects.all()
        return render(request, 'backstageNet/datacenter/cropdata.html', context={"area_list":area_list})
    def post(self,request):
        area = request.POST.get("id")
        current_user = MyUser.objects.get(username="admin")
        year = datetime.datetime.now().year
        start_1 = datetime.date(year,1,1)
        end_1 = datetime.date(year,3,31)
        start_2 = datetime.date(year,4,1)
        end_2 = datetime.date(year,6,30)
        start_3 = datetime.date(year,7,1)
        end_3 = datetime.date(year,9,30)
        start_4 = datetime.date(year,10,1)
        end_4 = datetime.date(year,12,31)
        money = 0
        dat = []
        dat1 = []
        dat2 = []
        dat3 = []
        dat4 = []
        if area:
            # area_obj = GardenArea.objects.get(id=area)
            for i in FarmList.objects.filter(garden_id=area):
                for x in Sell_Manage.objects.filter(farm=i,upl_time__range=(start_1, end_1)):
                    money = money + int(x.money)
                dat1.append({"farm":i.name,"money":money})
                money = 0
            for i in FarmList.objects.filter(garden_id=area):
                for x in Sell_Manage.objects.filter(farm=i,upl_time__range=(start_2, end_2)):
                    money = money + int(x.money)
                dat2.append({"farm":i.name,"money":money})
                money = 0
            for i in FarmList.objects.filter(garden_id=area):
                for x in Sell_Manage.objects.filter(farm=i,upl_time__range=(start_3, end_3)):
                    money = money + int(x.money)
                dat3.append({"farm":i.name,"money":money})
                money = 0
            for i in FarmList.objects.filter(garden_id=area):
                for x in Sell_Manage.objects.filter(farm=i,upl_time__range=(start_4, end_4)):
                    money = money + int(x.money)
                dat4.append({"farm":i.name,"money":money})
                money = 0
            for i in FarmList.objects.filter(garden_id=area):
                dat.append({"area":i.area,"name":i.name})

        data = json.dumps({"1":dat1,"2":dat2,"3":dat3,"4":dat4,"dat":dat})
        return HttpResponse(data)
        


# 对比分析
class Contrast_View(ListView):
    def get(self,request):
        current_user = MyUser.objects.get(username="admin")
        area_list = GardenArea.objects.all()
        area_obj = GardenArea.objects.all().first()
        farm_list = FarmList.objects.filter(garden=area_obj)
        return render(request, 'backstageNet/datacenter/contrast.html', context={"area_list":area_list,"farm_list":farm_list})
    def post(self,request):
        area_id = request.POST.get("id")
        farm_list = FarmList.objects.filter(garden_id=area_id)
        dat= []
        for i in farm_list:
            dat.append({"name":i.name,"id":i.id})
        data = json.dumps(dat)
        return HttpResponse(data)


# 对比分析详情
class Contrast_Detail(ListView):
    def get(self,request):
        pass
    def post(self,request):
        farm_id = request.POST.get("id")
        year = datetime.datetime.now().year
        start_1 = datetime.date(year,1,1)
        end_1 = datetime.date(year,12,31)
        start_2 = datetime.date(year-1,1,1)
        end_2 = datetime.date(year-1,12,31)
        start_3 = datetime.date(year-2,1,1)
        end_3 = datetime.date(year-2,12,31)
        start_4 = datetime.date(year-3,1,1)
        end_4 = datetime.date(year-3,12,31)
        dat1 = []
        dat2 = []
        dat3 = []
        dat4 = []
        money = 0
        if farm_id != "":
            print("+++++++++++++++++")
            # area_obj = GardenArea.objects.get(id=area)
            for i in FarmList.objects.filter(id=farm_id):
                for x in Sell_Manage.objects.filter(farm=i,upl_time__range=(start_1, end_1)):
                    money = money + int(x.money)
                dat1.append({"farm":i.name,"money":money})
                money = 0
            for i in FarmList.objects.filter(id=farm_id):
                for x in Sell_Manage.objects.filter(farm=i,upl_time__range=(start_2, end_2)):
                    money = money + int(x.money)
                dat2.append({"farm":i.name,"money":money})
                money = 0
            for i in FarmList.objects.filter(id=farm_id):
                for x in Sell_Manage.objects.filter(farm=i,upl_time__range=(start_3, end_3)):
                    money = money + int(x.money)
                dat3.append({"farm":i.name,"money":money})
                money = 0
            for i in FarmList.objects.filter(id=farm_id):
                for x in Sell_Manage.objects.filter(farm=i,upl_time__range=(start_4, end_4)):
                    money = money + int(x.money)
                dat4.append({"farm":i.name,"money":money})
                money = 0
        elif farm_id == "":
            print("--------")
            dat1 = []
            dat2 = []
            dat3 = []
            dat4 = []
        data = json.dumps({"1":dat1,"2":dat2,"3":dat3,"4":dat4})
        return HttpResponse(data)



# 对比分析列表
class Contrast_List(ListView):
    def get(self,request):
        pass
    def post(self,request):
        area_id = request.POST.get("id")
        page = int(request.POST.get("page"))
        dat = []
        farm_list = FarmList.objects.filter(garden_id=area_id)
        for i in farm_list:
            for x in Sell_Manage.objects.filter(farm=i):
                dat.append({"name":x.farm.name,"num":x.num,"area":x.farm.area,"money":x.money,"upl_time":x.upl_time})
        nums = len(dat)
        dat = dat[(10*(page-1)):(page*10)]
        data = json.dumps({"dat":dat,"nums":nums})
        return HttpResponse(data)



# 产业数据
class Industry_Data(ListView):
    def get(self,request):
        current_user = MyUser.objects.get(username="admin")
        area_list = GardenArea.objects.all()
        return render(request, 'backstageNet/datacenter/industrydata.html', context={"area_list":area_list})
    def post(self,request):
        current_user = MyUser.objects.get(username="admin")
        area = request.POST.get("id")
        page = int(request.POST.get("page"))
        dat = []
        money = 0
        start_date = datetime.datetime.now().year
        start_date = datetime.date(start_date,1,1)
        end_date = datetime.datetime.now()
        if area:
            # area_obj = GardenArea.objects.get(id=area)
            for i in FarmList.objects.filter(garden_id=area):
                for x in Sell_Manage.objects.filter(farm=i,upl_time__range=(start_date, end_date)):
                    money = money + int(x.money)
                dat.append({"farm":i.name,"money":money,"manage":i.manage_user,"area":i.area})
                money = 0
        else:
            area_obj = GardenArea.objects.get(user=current_user)
            for i in FarmList.objects.filter(garden=area_obj):
                for x in Sell_Manage.objects.filter(farm=i,upl_time__range=(start_date, end_date)):
                    money = money + int(x.money)
                dat.append({"farm":i.name,"money":money,"manage":i.manage_user,"area":i.area})
                money = 0
        nums = len(dat)
        dat_split = dat[(10*(page-1)):(page*10)]
        data = json.dumps({"dat":dat,"nums":nums,"dat_split":dat_split})
        return HttpResponse(data)


# 气象站阈值设置
class QXZ_Warning_View(ListView):
    def get(self,request):
        user_name = request.user.username
        print('user_name=', user_name)
        current_user = MyUser.objects.get(username=user_name)
        equip_list = Equip.objects.filter(equip_user=current_user,equip_type=5)
        return render(request, 'backstageNet/warn/warnSet.html', context={"equip_list":equip_list})
    def post(self,request):
        pass



# 气象站阈值记录
class QXZ_Warning_List(ListView):
    def get(self,request):
        return render(request, 'backstageNet/warn/warnRecord.html', context={})
    def post(self,request):
        pass




# 生产方式设置
class Production_Set(ListView):
    def get(self,request):
        user_name = request.user.username
        print('user_name=', user_name)
        current_user = MyUser.objects.get(username=user_name)
        equip_list = Equip.objects.filter(equip_user=current_user,equip_type=5)
        return render(request, 'backstageNet/warn/productionset.html', context={"equip_list":equip_list})
    def post(self,request):
        pass


# 农场划分
class Farm_Mark(ListView):
    def get(self,request):
        return render(request, 'backstageNet/basicSet/farmmark.html', context={})
    def post(self,request):
        pass



# 农场列表
class Farm_List(ListView):
    def get(self,request):
        return render(request, 'backstageNet/basicSet/farmlist.html', context={})
    def post(self,request):
        pass


# 交通指引
class Traffic_Line(ListView):
    def get(self,request):
        return render(request, 'backstageNet/trafficLine/trafficLine.html', context={})
    def post(self,request):
        pass



# 管理员新闻发布
class Policy_Pub(ListView):
    def get(self,request):
        return render(request, 'backstageNet/annunciate/policyPub.html', context={})
    def post(self,request):
        current_user = MyUser.objects.get(username="admin")
        # news_photo = request.POST.get('upload')
        art_type = request.POST.get('type')
        # writer = request.POST.get('writer')
        # intro = request.POST.get('intro')
        title = request.POST.get('title')
        content = request.POST.get('content')
        policyid = request.POST.get("id")
        #修改
        if policyid:
            try:
                CKArticle.objects.filter(id=policyid).update(art_type=art_type,title=title,content=content,hidden=True)
                data = "1"
            except Exception as e:
                print(e)
                data = "0"
        #创建
        else:
            try:
                CKArticle.objects.create(author=current_user,art_type=art_type,title=title,content=content,hidden=True)
                data = "1"
            except Exception as e:
                print(e)
                data = "0"
        return HttpResponse(data)




# 管理员新闻列表
class Policy_List_View(ListView):
    def get(self,request):
        return render(request, 'backstageNet/annunciate/policyListView.html', context={})
    def post(self,request):
        policyid = request.POST.get("id")
        req = request.POST.get("req")
        art_list = CKArticle.objects.filter(id=policyid)
        data = []
        #查看
        if req == "see":
             for i in art_list:
                data.append({
                    "art_type":i.art_type,
                    "title":i.title,
                    "content":i.content,
                     "time":i.upl_time.strftime('%Y-%m-%d %H:%M:%S'),
                     "author":i.author.username
                })
        elif req == "del":
            art_list.delete()
            data="1"
        data = json.dumps(data,ensure_ascii=False)
        return HttpResponse(data)




# 管理员新闻列表
class Policy_List(ListView):
    def get(self,request):
        page = int(request.GET.get("page"))
        art_list = CKArticle.objects.all().exclude(art_type=5)
        nums = art_list.count()
        art = art_list[(10*(page-1)):(page*10)]
        return render(request, 'backstageNet/annunciate/policyList.html', context={"art":art,"nums":nums})
    def post(self,request):
        data = []
        req = request.POST.get("req")
        page = int(request.POST.get("page"))
        print(req)
        if req == "":
            art_list = CKArticle.objects.filter(art_type__lte=2)
            nums = art_list.count()

        else:
            art_list = CKArticle.objects.filter(art_type=req)
            #筛选
            nums = art_list.count()
        art = art_list[(10*(page-1)):(page*10)] 
        return render(request, 'backstageNet/annunciate/policyList.html', context={"art":art,"nums":nums})  

        
    


# 个人农场主页
class Person_Farm(ListView):
    def get(self,request):
        uname = request.GET.get('name')
        current_user = MyUser.objects.get(username=uname)
        news = CKArticle.objects.filter(author=current_user)
        garden = GardenArea.objects.get(user=current_user)
        video = Video_data.objects.filter(author=current_user)
        product = Product.objects.filter(author=current_user)
        return render(request, 'outerNet/person_farm.html', context={"news":news,"garden":garden,"video":video,"product":product})
    def post(self,request):
        pass


# 农场管理界面
class Person_Farm_Edit(ListView):
    def get(self,request):
        current_user = MyUser.objects.get(username='admin')
        return render(request, 'backstageNet/production/person_farm_edit.html', context={"current_user":current_user})
    def post(self,request):
        current_user = MyUser.objects.get(username='admin')
        try:
            gar_area = GardenArea.objects.get(user=current_user)
            data = {"name":gar_area.name,"manage":gar_area.manage,"mobile":gar_area.mobile,
                "area":gar_area.area,"location":gar_area.location,"addr":gar_area.addr,
                "desc":gar_area.desc,"img":gar_area.img
                }
            
        except Exception as e:
            print(e)
            data = {"name":"","manage":"","mobile":"",
                "area":"","location":"","addr":"",
                "desc":"","img":""
                }
        data = json.dumps(data)
        return HttpResponse(data)


# 地块发布
class Person_Area_Pub(ListView):
    def get(self,request):
        pass
    def post(self,request):
        current_user = MyUser.objects.get(username='admin')
        # 农场名称
        name = request.POST.get('name')
        # 负责人
        manage = request.POST.get('manage')
        # 联系电话
        mobile = request.POST.get('mobile')
        # 面积
        area = request.POST.get('area')
        # 农场介绍
        desc = request.POST.get('desc')
        # 图片
        img = request.POST.get('img')
        location = request.POST.get('location')
        addr = request.POST.get('addr')
        if GardenArea.objects.filter(user=current_user).exists():
            try:
                gar_obj = GardenArea.objects.get(user=current_user)
                gar_obj.name = name
                gar_obj.manage = manage
                gar_obj.mobile = mobile
                gar_obj.area = area
                gar_obj.desc = desc
                gar_obj.img = img
                gar_obj.location = location
                gar_obj.addr = addr
                gar_obj.save()
                data = "1"
            except Exception as e:
                print(e)
                data = "0"
        else:
            try:
                GardenArea.objects.create(user=current_user,name=name,manage=manage,mobile=mobile,
                    area=area,desc=desc,img=img,
                    location=location,addr=addr)
                data = "1"
            except Exception as e:
                print(e)
                data = "0"
        return HttpResponse(data)


class Person_View(ListView):
    def get(self,request):
        # 接收当前用户
        # current_user = request.session.get('username')
        current_user = MyUser.objects.get(username="admin")
        # print("current_user:", current_user)
        # current_user = MyUser.objects.get(username=current_user)
        page = request.GET.get("page")
        uname = request.GET.get("uname")
        user_list = MyUser.objects.all()
        nums = user_list.count()
        return render(request, 'backstageNet/systemSet/userManage.html', context={"nums": nums,"page":page,"uname":uname})

    def post(self, request):
        pass

# 地图设置
class SetMap_View(ListView):
    def get(self,request):
        # 接收当前用户
        # current_user = request.session.get('username')
        current_user = MyUser.objects.get(username="admin")
        # print("current_user:", current_user)
        # current_user = MyUser.objects.get(username=current_user)
        page = request.GET.get("page")
        uname = request.GET.get("uname")
        user_list = MyUser.objects.all()
        nums = user_list.count()
        pic_list = Pic_Info.objects.get(pic_user=current_user)
        return render(request, 'backstageNet/systemSet/mapManage.html', context={"nums": nums,"page":page,"uname":uname,"pic_list":pic_list})

    def post(self, request):
        map_photo = request.FILES.get('upicture')
        if map_photo:
            print("地图图片：", map_photo)
            map_photo_dir = 'map_photo/'
            end_name = map_photo.name.split('.')[-1]
            # 判断如果路径不存在，即创建路径
            if os.path.exists(map_photo_dir) == False:
                os.makedirs(map_photo_dir)
            img = Image.open(map_photo)
            # img = img.convert('RGB')
            now_time = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))
            pic_name = now_time + '.' + end_name
            print("pic_name:", pic_name)
            img.save(map_photo_dir + pic_name)
            news_photo = map_photo_dir + pic_name
            print("new_photo:",news_photo)
            data = {"code": 0,"msg": "","data": {"src": news_photo}}
        else:
            new_photo = "0"
            data = {"code": 404,"msg": "","data": {"src": news_photo}}
        data = json.dumps(data)
        return HttpResponse(data)


class Person_List(ListView):
    def get(self,request):
        page = int(request.GET.get('page'))
        print("page=", page)
        uname = request.GET.get("uname")
        # 接收当前用户
        # current_user = request.session.get('username')
        current_user = MyUser.objects.get(username="admin")
        # print("current_user:", current_user)
        # current_user = MyUser.objects.get(username=current_user)
        # if current_user.is_superuser == True:
        user_list = MyUser.objects.all().order_by(
            "-date_joined")[(10*(page-1)):(page*10)]
        if uname:
            user_list = MyUser.objects.filter(username__contains=uname).order_by(
            "-date_joined")[(10*(page-1)):(page*10)]
        return render(request, 'backstageNet/systemSet/user_list.html', context={'user_list': user_list})
    def post(self,request):
        # current_user = request.session.get('username')
        # print("current_user:", current_user)
        current_user = MyUser.objects.get(username="admin")
        print("筛选：")
        f_name = request.POST.get('uname')
        page = int(request.POST.get('page'))
        print("page:", page)
        user_list = MyUser.objects.filter(username__contains=f_name)
        nums = user_list.count()
        user_list = user_list[(10*(page-1)):(page*10)]
        return render(request, 'backstageNet/systemSet/user_list.html', context={'user_list': user_list, "nums": nums})



class Area_Create(ListView):
    def get(self,request):
        current_user = MyUser.objects.get(username="admin")
        currpage = request.GET.get('currpage')
        uname = request.GET.get("uname")
        f_name = request.GET.get("f_name")
        user_obj = MyUser.objects.get(username=uname)
        try:
            curr_area = GardenArea.objects.get(user=user_obj)
            # user_area = {"name":curr_area.name,"location":curr_area.location}
        except Exception as e:
            print(e)
            curr_area = ""
            # user_area = {"name":"","location":""}
        return render(request, 'backstageNet/systemSet/onlineSplit.html', context={"currpage":currpage,"uname":uname,"f_name":f_name,"curr_area":curr_area})
    def post(self,request):
        uname = request.POST.get("uname")
        name = request.POST.get("name")
        area = request.POST.get("area")
        location = request.POST.get("location")
        user_obj = MyUser.objects.get(username=uname)
        if GardenArea.objects.filter(user=user_obj).exists():
            try:
                area_obj = GardenArea.objects.get(user=user_obj)
                area_obj.name = name
                area_obj.area = area
                area_obj.location = location
                area_obj.upl_time = datetime.datetime.now()
                area_obj.save()
                data = "1"
            except Exception as e:
                print(e)
                data = "0"
        else:
            try:
                GardenArea.objects.create(user=user_obj,name=name,area=area,location=location,upl_time=datetime.datetime.now())
                data = "1"
            except Exception as e:
                print(e)
                data = "0"
            
        return HttpResponse(data)


class Area_Map(ListView):
    def get(self,request):
        return render(request, 'backstageNet/systemSet/onlineSplitMap.html', context={})
    def post(self,request):
        uname = request.POST.get("uname")
        user_obj = MyUser.objects.get(username=uname)
        all_area = []
        area_list = GardenArea.objects.all().exclude(user=user_obj)
        for i in area_list:
            all_area.append({"name":i.name,"location":i.location})
        try:
            curr_area = GardenArea.objects.get(user=user_obj)
            user_area = {"name":curr_area.name,"location":curr_area.location}
        except Exception as e:
            print(e)
            user_area = {"name":"","location":""}
        data = json.dumps({"all_area":all_area,"user_area":user_area})
        return HttpResponse(data)



# 菜单权限
class Limit(ListView):
    def get(self,request):
        currpage = request.GET.get('currpage')
        uname = request.GET.get("uname")
        f_name = request.GET.get("f_name")
        return render(request, 'backstageNet/limit/limit.html', context={"currpage":currpage,"uname":uname,"f_name":f_name})
    def post(self,request):
        uname = request.POST.get("uname")
        user_obj = MyUser.objects.get(username=uname)
        return HttpResponse(user_obj.limit)


class Limit_View(ListView):
    def get(self,request):
        # 接收当前用户
        # current_user = request.session.get('username')
        current_user = MyUser.objects.get(username="admin")
        # print("current_user:", current_user)
        # current_user = MyUser.objects.get(username=current_user)
        page = request.GET.get("page")
        uname = request.GET.get("uname")
        user_list = MyUser.objects.all()
        nums = user_list.count()
        return render(request, 'backstageNet/limit/limitUserManage.html', context={"nums": nums,"page":page,"uname":uname})

    def post(self, request):
        uname = request.POST.get("uname")
        limit = request.POST.get("limit")
        user_obj = MyUser.objects.get(username=uname)
        try:
            user_obj.limit = limit
            user_obj.save()
            data = "1"
        except Exception as e:
            print("错误信息为",e)
            data = "0"
        return HttpResponse(data)



class Person_Limit(ListView):
    def get(self,request):
        page = int(request.GET.get('page'))
        print("page=", page)
        uname = request.GET.get("uname")
        # 接收当前用户
        # current_user = request.session.get('username')
        current_user = MyUser.objects.get(username="admin")
        # print("current_user:", current_user)
        # current_user = MyUser.objects.get(username=current_user)
        # if current_user.is_superuser == True:
        user_list = MyUser.objects.all().order_by(
            "-date_joined")[(10*(page-1)):(page*10)]
        if uname:
            user_list = MyUser.objects.filter(username__contains=uname).order_by(
            "-date_joined")[(10*(page-1)):(page*10)]
        return render(request, 'backstageNet/limit/limit_user_list.html', context={'user_list': user_list})
    def post(self,request):
        # current_user = request.session.get('username')
        # print("current_user:", current_user)
        current_user = MyUser.objects.get(username="admin")
        print("筛选：")
        f_name = request.POST.get('uname')
        page = int(request.POST.get('page'))
        print("page:", page)
        user_list = MyUser.objects.filter(username__contains=f_name)
        nums = user_list.count()
        user_list = user_list[(10*(page-1)):(page*10)]
        return render(request, 'backstageNet/limit/limit_user_list.html', context={'user_list': user_list, "nums": nums})


# 专家诊断
class Expert(ListView):
    def get(self,request):
        return render(request, 'backstageNet/limit/expert.html', context={})
    def post(self,request):
        pass
class learnDepot(ListView):
    def get(self,request):
        return render(request, 'backstageNet/limit/learnDepot.html', context={})
    def post(self,request):
        pass

# 创建新用户
class Create_User(ListView):
    def get(self,request):
        currpage = request.GET.get("currpage")
        f_name = request.GET.get("f_name")
        return render(request, 'backstageNet/systemSet/creatUser.html', context={"currpage":currpage,"f_name":f_name})
    def post(self,request):
        name = request.POST.get("name")
        email = request.POST.get("email")
        phone = request.POST.get("phone")
        user_remark = request.POST.get("desc")
        if MyUser.objects.extra(where=['binary username=%s'], params=[name]).exists():
            # 用户已存在！！！
            data = "3"
            return HttpResponse(data)
        elif MyUser.objects.filter(email = email).exists():
            # 该邮箱已注册！！！
            data = "2"
            return HttpResponse(data)
        else:
            UserModel = get_user_model()
            # 创建用户：
            try:
                user = UserModel.objects.create_user(username=name, email=email,\
                        user_phone=phone, password="yf123456",\
                        is_active = 1,is_staff = 0,user_remark = user_remark,limit = 
                        [{
                            "id": 1,
                            "title": "首页",
                            "icon": "&#xe626;",
                            "url": "map",
                            "checked": "false",
                            "children": []
                        },
                        {
                            "id": 3,
                            "title": "信息发布",
                            "icon": "&#xe765;",
                            "url": "",
                            "children": [
                                {
                                    "id": 3.1,
                                    "title": "新闻资讯",
                                    "url": "news_pub",
                                },
                                {
                                    "id": 3.2,
                                    "title": "视频资讯",
                                    "url": "video_pub",
                                },
                                {
                                    "id": 3.2,
                                    "title": "产品展厅",
                                    "url": "equip_pub",
                                },
                                {
                                    "id": 3.3,
                                    "title": "四季采摘",
                                    "url": "garden_pub",
                                },
                                {
                                    "id": 3.4,
                                    "title": "民宿导览",
                                    "url": "dorm_pub",
                                },
                            ]
                        },
                        ])
                user.save()
                data = "1"
            except Exception as e:
                print(e)
                data = "0"
        return HttpResponse(data)


# 管理员修改密码
class Change_Pwd(ListView):
    def get(self,request):
        pass
    def post(self,request):
        uname = request.POST.get("uname")
        new_pwd = request.POST.get("userpassword")
        print("uname:",uname)
        print("new_pwd:",new_pwd)
        user = MyUser.objects.get(username=uname)
        user.set_password(new_pwd)
        try:
            user.save()
            data = "1"
        except:
            data = "0"
        return HttpResponse(data)


# 删除用户
class Delete_User(ListView):
    def get(self,request):
        pass

    def post(self,request):
        uname = request.POST.get("uname")
        try:
            user_obj = MyUser.objects.get(username=uname)
            user_obj.delete()
            data = "1"
        except Exception as e:
            print(e)
            data = "0"
        return HttpResponse(data)


# 用户修改自己密码
class User_Change_Pwd(ListView):
    def get(self,request):
        return render(request, 'backstageNet/systemSet/changePwd.html', context={})
    def post(self,request):
        username = request.user.username
        print('username:',username)
        user = MyUser.objects.get(username=username)
        print("当前用户为：", username)

        oldpassword = request.POST.get('oldpassword')
        password = request.POST.get('password')
        print("post的oldpassword:", oldpassword)
        print("post的password:", password)
        
        if(check_password(oldpassword, user.password)):
            user.set_password(password)
            user.save()
            data = "1"
        else:
            data = "0"
        return HttpResponse(data)





# 气象站阈值接口
class QXZ_Auto(ListView):
    def get(self,request):
        pass
    
    def post(self,request):
        imei = request.POST.get('imei')
        try:
            auto_list = QXZAutoswitch.objects.get(equip_id_id=imei)
            qxz_list = QXZstatus.objects.get(equip_id_id=imei)
            data = {"qxz_list":eval(qxz_list.qxz_status)['data'],"auto_list":auto_list.qxz_auto}
        except:
            data = {"qxz_list":[],"auto_list":[]}
        data = json.dumps(data)
        return HttpResponse(data)




# 气象站阈值设置接口
class QXZ_Value_Mqtt(ListView):
    def get(self,request):
        pass
    
    def post(self,request):
        req = request.POST.get('req')
        jk = request.POST.get('JK')
        ekey = request.POST.get('eKey')
        upper = request.POST.get('upper')
        lower = request.POST.get('lower')
        method = request.POST.get('method')
        imei = request.POST.get('imei')

        # topic = "/yfkj/qxz/sub/"+imei
        # if req == "read":
        #     payload = {"ext":{"type":"status"},"cmd":"read"}
        # elif req == "set":
        #     way = int(request.POST.get('way'))
        #     switch = int(request.POST.get('switch'))
        #     payload = {"cmd":"control","ext":{"JK":way,"status":switch}}
        # elif req == "conf":
        #     payload = {"ext":{"type":"jkStatus"},"cmd":"read"}
        
        # cmd = {"topic":topic,"payload":json.dumps(payload),'qos':0}
        # res = requests.post("http://www.yfzhwlw.com:8080/api/v2/mqtt/publish",
        #                         data=json.dumps(cmd), auth=HTTPBasicAuth("admin", "yfkj_6019"))
        # print("res.status_code:", type(res.status_code))
        # if res.status_code == 200:
        #     data = "0"
        #     return HttpResponse(data)
        # else:
        #     data = "1"
        #     return HttpResponse(data)
        return HttpResponse("0")
    
    
    
# 保存图片信息
class Pic_locat(ListView):
    def get(self,request):
        pass
    
    def post(self,request):
        username = request.user.username
        print('username:',username)
        user = MyUser.objects.get(username=username)
        print("当前用户为：", username)
        # 东北点
        locat1 = request.POST.get('locat1')
        # 西南点
        locat2 = request.POST.get('locat2')
        # 图片地址
        addr = request.POST.get('addr')
        locat_info = request.POST.get('locat_info')
        pic_center = request.POST.get('pic_center')
        if Pic_Info.objects.filter(pic_user=user).exists():
            pic_obj = Pic_Info.objects.get(pic_user=user)
            pic_obj.locat1=locat1
            pic_obj.locat2=locat2
            pic_obj.pic_center=pic_center
            pic_obj.addr=addr
            pic_obj.locat_info=locat_info
            pic_obj.save()
            return HttpResponse("1")
        try:
            Pic_Info.objects.create(pic_user=user,locat1=locat1,locat2=locat2,pic_center=pic_center,addr=addr,locat_info=locat_info)
            return HttpResponse("1")
        except Exception as e:
            print("--->>",e)
            return HttpResponse("0")