# -*- coding: utf-8 -*-

from django.shortcuts import render, redirect
# from apps.SystemManage.forms import AddUserForm
from django.http import HttpResponse
from django.template import RequestContext
from django.contrib import auth
from django.contrib.auth import authenticate, login as auth_login, logout
from django.contrib.auth import get_user_model
from django.contrib.auth.models import User, Group, Permission
from django.contrib.auth.hashers import make_password, check_password

from django.contrib.auth.decorators import login_required
from django.views.decorators.csrf import csrf_exempt

from django.views.generic import ListView
from django.views.generic.base import View
import datetime
from PIL import Image
import time
import json
import base64
import redis
from django.core.cache import cache
import os

from apps.AppInfo.models import Equip, Equip_type, MyUser, QXZdata, QXZstatus, QXZdata_New, JKdata, Article, QXZstatus_New, QXZswitchdata, QXZswitchstatus, CKArticle, GardenManage, Video_data,\
    Product, Pick_Pub, FarmList, Hotel_Info


from django.utils.decorators import method_decorator

# Create your views here.


class Home_Test(View):
    def get(self, request):
        pass

    def post(self, request):
        pass


# 用户登录
@method_decorator(csrf_exempt, name='dispatch')
class Login_View(View):
    def get(self, request):
        HTTP_HOST = request.META['HTTP_HOST']
        print('HTTP_HOST:', HTTP_HOST)
        # form = AddUserForm()
        # return render(request, 'home/login.html', context={'form': form})
        if request.user.is_authenticated():
            user_name = request.user.username
            print('user_name=', user_name)
            current_user = MyUser.objects.get(username=user_name)
            if current_user.is_superuser:
                role = "superuser"
            elif current_user.is_staff:
                role = "staff"
            else:
                role = "user"
            print("当前用户类型：是否为超级管理员", current_user.is_superuser)
            return render(request, 'home/home.html', context={'user_name': user_name, 'role': role})
        else:
            if HTTP_HOST == "127.0.0.1" or HTTP_HOST == "120.27.222.26":
                return render(request, 'home/login.html', context={})

    def post(self, request):
        user_name = request.POST.get('username')
        pass_word = request.POST.get('password')
        print('输入的用户名：', user_name)
        user = MyUser.objects.extra(
            where=['binary username=%s'], params=[user_name])
        print("user.exists():", user.exists())
        if user.exists() == False:
            data = "0"
            return HttpResponse(data)
        else:
            user = MyUser.objects.get(username=user_name)
            if user.is_active != True:
                data = "2"
                return HttpResponse(data)
            else:
                if check_password(pass_word, user.password) != True:
                    data = "3"
                    return HttpResponse(data)
                else:
                    print('登陆成功')
                    current_user = MyUser.objects.get(username=user_name)
                    auth_user = authenticate(
                        username=user_name, password=pass_word)
                    auth_login(request, auth_user)
                    # 将当前登录的用户名写入session
                    request.session['username'] = user_name
                    if user.is_superuser:
                        role = "superuser"
                    elif user.is_staff:
                        role = "staff"
                    else:
                        role = "user"
                    data = "1"
                    returnUrl = request.POST.get('returnUrl')
                    print("returnUrl:", returnUrl)
                    if returnUrl == None:
                        print("returnUrl is none!!!!!!!!")
                        return HttpResponse(data)
                    else:
                        if returnUrl == "":
                            print("returnUrl is empty")
                            return render(request, 'outerNet/index2.html')
                        elif returnUrl != "":
                            print("returnUrl is not empty")
                            return render(request, 'outerNet/index.html')
# 用户登录2
class Login2_View(View):
    def get(self, request):
        return render(request, 'outerNet/login2.html', context={})

    def post(self, request):
        pass

# 外网首页
class Home(View):
    def get(self, request):
        user_news = CKArticle.objects.filter(art_type=5)[0:10]
        zero_news = CKArticle.objects.filter(art_type=0)[0:10]
        one_news = CKArticle.objects.filter(art_type=1)[0:10]
        two_news = CKArticle.objects.filter(art_type=2)[0:10]
        video_news = Video_data.objects.all()[0:4]
        product = Product.objects.all()[0:8]
        pick = Pick_Pub.objects.all()[0:6]
        farm = FarmList.objects.all()[0:6]
        hotel = Hotel_Info.objects.all()[0:5]
        if request.user.is_authenticated():
            user_name = request.user.username
            curr_user = MyUser.objects.get(username=user_name)
            print('user_name=', user_name)
            print('user=', curr_user.username)
        else:
            curr_user = ""
        return render(request, 'outerNet/index2.html', context={"user_news": user_news,"zero_news": zero_news, "one_news": one_news,
                                                               "two_news": two_news, "video_news": video_news,"hotel":hotel,
                                                               "product": product, "pick": pick, "farm": farm, "curr_user": curr_user})

    def post(self, request):
        pass

# 外网首页2
class Home2(View):
    def get(self, request):
        user_news = CKArticle.objects.filter(art_type=5)[0:10]
        zero_news = CKArticle.objects.filter(art_type=0)[0:10]
        one_news = CKArticle.objects.filter(art_type=1)[0:10]
        two_news = CKArticle.objects.filter(art_type=2)[0:10]
        video_news = Video_data.objects.all()[0:4]
        product = Product.objects.all()[0:8]
        pick = Pick_Pub.objects.all()[0:6]
        farm = FarmList.objects.all()[0:6]
        hotel = Hotel_Info.objects.all()[0:5]
        if request.user.is_authenticated():
            user_name = request.user.username
            curr_user = MyUser.objects.get(username=user_name)
            print('user_name=', user_name)
            print('user=', curr_user.username)
        else:
            curr_user = ""
        return render(request, 'outerNet/index2.html', context={"user_news": user_news,"zero_news": zero_news, "one_news": one_news,
                                                               "two_news": two_news, "video_news": video_news,"hotel":hotel,
                                                               "product": product, "pick": pick, "farm": farm, "curr_user": curr_user})

    def post(self, request):
        pass


# 首页设备显示
class Home_Equip(View):
    def get(self, request):
        pass

    def post(self, request):
        pass


#修改个人信息,
class Modify_Head(ListView):
    def get(self, request):
        art_list = MyUser.objects.get(username="admin")
        print(art_list.username)
        return render(request, "backstageNet/systemSet/systemSet.html", context={"art_list": art_list})

    def post(self, request):
        head = request.POST.get("user_picture")
        remark = request.POST.get("user_remark")
        phone = request.POST.get("user_phone")
        name = request.POST.get("username")
        try:
            art_list = MyUser.objects.filter(username=name).update(
                user_picture=head,
                user_remark=remark,
                user_phone=phone
            )
            data = "1"
        except Exception as e:
            print(e)
            data = "0"
        return HttpResponse(data)


# 头像上传
class User_Img(ListView):
    def get(self, request):
        pass

    def post(self, request):
        user_photo = request.FILES.get('user_photo')
        if user_photo:
            print("头像图片：", user_photo)
            user_photo_dir = 'user_photo/'
            end_name = user_photo.name.split('.')[-1]
            # 判断如果路径不存在，即创建路径
            if os.path.exists(user_photo_dir) == False:
                os.makedirs(user_photo_dir)
            img = Image.open(user_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(user_photo_dir + pic_name)
            user_photo = user_photo_dir + pic_name
            print("user_photo:", user_photo)
            data = {"code": 0, "msg": "", "data": {"src": user_photo}}
        else:
            user_photo = "0"
            data = {"code": 404, "msg": "", "data": {"src": user_photo}}
        data = json.dumps(data)
        return HttpResponse(data)



#新建用户
class User_News(ListView):
    def get(self,request):
        pass

    def post(self,request):
        username = request.POST.get("username")
        user_remark = request.POST.get("user_remark")
        user_phone = request.POST.get("user_phone")
        email = request.POST.get("email")
                



#用户登陆
class User_Land(ListView):
    def get(self,request):
        pass
    def post(self, request):
        user_name = request.POST.get("username")
        pass_word = request.POST.get("password")
        print('输入的用户名', user_name)
        print('输入的密码：', pass_word)
        user = MyUser.objects.extra(
            where=['binary username=%s'], params=[user_name])
        print("user.exists():", user.exists())
        if user.exists() == False:
            data = 0
            print("用户不存在")
            data = json.dumps(data)
            return HttpResponse(data)
        else:
            user = MyUser.objects.get(username=user_name)
            if user.is_active != True:
                data = 2
                print("用户名错误")
                data = json.dumps(data)
                return HttpResponse(data)
            else:
                if check_password(pass_word, user.password) != True:
                    data = 3
                    print('密码错误')
                    data = json.dumps(data)
                    return HttpResponse(data)
                else:
                    print('登陆成功')
                    auth_user = authenticate(
                        username=user_name, password=pass_word)
                    auth_login(request, auth_user)
                    # 将当前登录的用户名写入session
                    request.session['username'] = user_name

                    art_list = MyUser.objects.filter(username=user_name)
                    for i in art_list:
                        he = {"username":i.username,"user_img":i.user_picture.name,"code":1 }
                    data = json.dumps(he)
                    print("data:", data)
                    return HttpResponse(data)



#判断用户是否已登陆
class User_Check(ListView):
    # def get(self,request):
    #     pass
    def get(self, request):
        ret_url = request.path_info
        print(ret_url)
        if ret_url == "/home":
            return HttpResponse(ret_url)
        else:
            print(000)
            return HttpResponse("00000")
