# -*- 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
import random
from django.core.cache import cache
import os
# from configure import verification_code
import re
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, GardenArea, Sightsee_Info,Hotel_Info, Relations
from qcloudsms_py import SmsSingleSender
from qcloudsms_py.httpclient import HTTPError
import requests
from django.utils.decorators import method_decorator
from .allocation import administrators,ordinary
# Create your views here.

"""
appkey 和 AppSecret
1、先调用我们开放的接口，获取 userid和code
2、然后使用userid 和code 带上appkey 和 AppSecret 请求客户提供的接口地址，获取用户信息
3、根据返回的数据进行判断是否登陆
"""


"""
{
	"timestamp": "2020-09-04 10:04:37",
	"status": 404,
	"error": "Not Found",
	"message": "No message available",
	"path": "/ducore//oauth/oauthLogin/oauthLogin/"
}


{
	"success": true,
	"message": "操作成功！",
	"code": 200,
	"result": {
		"address": "",
		"sex": 1,
		"telephone": "",
		"avatar": "files/20200902/3184478c3fe1ae8c6e2aa3828a6e62c_1599017263910.jpg",
		"isAdmin": "N",
		"delFlag": "0",
		"realname": "黄豪",
		"workNo": "11111",
		"kodaE": "",
		"post": "",
		"phone": "15959191107",
		"identity": "",
		"orgCode": "A01A03",
		"kodaPassword": "888888",
		"id": "5b75626a-1559-4596-aca5-3dcfaa736254",
		"kodaUsername": "0591002000007",
		"kodaId": "0591002000007",
		"email": "",
		"status": 1,
		"username": "15959191107"
	},
	"timestamp": 1599184606585
}
"""

app_key = "u8dF3opl0xCq1a"
app_secret = "Qz4jLdSisLDzyDxCdog7"
urls = "http://10.10.0.227:17022/ducore/oauth/oauthLogin/oauthLogin/" 
headers = {"app_key":app_key,"app_secret":app_secret}
#登陆校验
class Log_Verify(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.filter(hidden=True)[0:8]
        farm = FarmList.objects.all()[0:8]
        garden = GardenArea.objects.filter(hidden=True)[0:6]
        hotel = Hotel_Info.objects.filter(hidden=True)[0:6]
        article = CKArticle.objects.filter(hidden=True)[0:12]
        sightsee = Sightsee_Info.objects.filter(hidden=True)[0:6]
        hotel2 = Hotel_Info.objects.filter(hidden=True).order_by('-upl_time')[0:6]
        relation = Relations.objects.all()

        userId = request.GET.get("userId")
        print("userId",userId)
        code = request.GET.get("code")
        print("code",code)
        data = {"userId":userId,"code":code}
        data = json.dumps(data)
        url = urls + userId + "/" + code
        res = requests.post(url,headers=headers)
        rest = json.loads(res.text)
        #校验登陆是否成功
        try:
            code  = rest["code"]
        except:
            code = 400
        if code == 200:
            username = rest["result"]["username"]
            try:
                curr_user = MyUser.objects.get(username=username)
            except:
                curr_user = ""
            isadmin = rest["result"]["isAdmin"]
            # 普通用户
            if isadmin == "N":
                limit = ordinary
                num = 1

            # 管理员
            else:
                limit = administrators
                num = 2

            # 设置默认密码
            password = "qwerdf123456"

            # 修改
            if curr_user:
                curr_user.user_remark = rest["result"]["realname"]
                curr_user.user_picture = rest["result"]["avatar"]
                curr_user.user_phone = rest["result"]["phone"]
                curr_user.save()

            # 新增
            else:
                if num == 1:
                    # 普通用户
                    MyUser.objects.create_user(
                        user_remark = rest["result"]["realname"],
                        user_picture = rest["result"]["avatar"],
                        user_phone = rest["result"]["phone"],
                        username = rest["result"]["username"],
                        password=password,
                        limit=limit
                    )
                else:
                    # 管理员
                    MyUser.objects.create_user(
                        user_remark = rest["result"]["realname"],
                        user_picture = rest["result"]["avatar"],
                        user_phone = rest["result"]["phone"],
                        username = rest["result"]["username"],
                        password=password,
                        limit=limit,
                        is_superuser=1,
                        is_staff=1
                    )
            request.session['username'] = username
            return render(request, 'outerNet/index2.html', context={"user_news": user_news,"zero_news": zero_news, "one_news": one_news,"article":article,"relation":relation,
                                                               "two_news": two_news, "video_news": video_news,"hotel":hotel,"garden":garden,"hotel2":hotel2,
                                                               "product": product, "pick": pick, "farm": farm, "curr_user": curr_user,"sightsee":sightsee})
        else:
            return render(request,"outerNet/error.html",context={})


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):
        relation = Relations.objects.all()
        return render(request, 'outerNet/login2.html', context={"relation":relation})

    def post(self, request):
        pass




# 注册
class ForgetPaw_View(View):
    def get(self, request):
        relation = Relations.objects.all()
        return render(request, 'outerNet/forgetPaw.html', context={"relation":relation})

    def post(self, request):
        pass
# 注册
class register_View(View):
    def get(self, request):
        relation = Relations.objects.all()
        return render(request, 'outerNet/register.html', context={"relation":relation})

    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.filter(hidden=True)[0:8]
        farm = FarmList.objects.all()[0:8]
        garden = GardenArea.objects.filter(hidden=True)[0:6]
        hotel = Hotel_Info.objects.filter(hidden=True)[0:6]
        article = CKArticle.objects.filter(hidden=True)[0:12]
        sightsee = Sightsee_Info.objects.filter(hidden=True)[0:6]
        hotel2 = Hotel_Info.objects.filter(hidden=True).order_by('-upl_time')[0:6]
        relation = Relations.objects.all()
        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,"article":article,"relation":relation,
                                                               "two_news": two_news, "video_news": video_news,"hotel":hotel,"garden":garden,"hotel2":hotel2,
                                                               "product": product, "pick": pick, "farm": farm, "curr_user": curr_user,"sightsee":sightsee})

    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]
#         garden = GardenArea.objects.all()
#         farm = FarmList.objects.all()
#         hotel = Hotel_Info.objects.all()[0:5]
#         article = CKArticle.objects.all()[0:12]
#         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,"farm":farm,
#                                                                "two_news": two_news, "video_news": video_news,"hotel":hotel,"article":article,
#                                                                "product": product, "pick": pick, "garden": garden, "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)


# 用户退出 
@login_required
def logout(request):
    print("用户退出")
    del request.session['username']# 删除session
    auth.logout(request)
    return redirect('/login2')


#判断用户是否已登陆
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")
        


# 短信应用 SDK AppID
appid = 1400227496  # SDK AppID 以1400开头
# 短信应用 SDK AppKey
appkey = "c9aba961bd30072f1e1b9272077abaea"
#签名
sms_sign = "云飞科技"  # NOTE: 签名参数使用的是`签名内容`，而不是`签名ID`。这里的签名"腾讯云"只是示例，真实的签名需要在短信控制台中申请


#发送验证码
#1验证码不正确,2两次密码不一致4用户不存在请注册3手机号不正确 0重置密码成功
class Prove_Code(ListView):
    def post(self, request):
        # phone = json.loads(request.body.decode())
        # num = verification_code()
        # num = 123456
        
        num = ""
        for i in range(6):
            ch = chr(random.randrange(ord('0'), ord('9') + 1))
            num += ch
        
        mobile = request.POST.get("mobile")
        pass_word1 = request.POST.get("password")
        pass_word2 = request.POST.get("password2")
        code = request.POST.get("code")
        ret = request.POST.get("ret")
        # imei = request.POST.get("imei")
        # try:
        #     #提取imei
        #     imei = json.loads(imei)
        #     imeid = imei["uuid"]
        #     if imeid.find(",") != -1:
        #         imeid = imeid.split(",")[0]
        #     else:
        #         pass
        #     print("imeid",imeid)
        # except Exception as e:
        #     print(e)
        #     data = 0
        #     return HttpResponse(data)

        mobile_pat = re.compile('^(13\d|14[5|7]|15\d|166|17\d|18\d)\d{8}$')
        res = re.search(mobile_pat, mobile)
        if ret == "see":

            #校验手机号是否已经注册
            if MyUser.objects.filter(username=mobile).exists():
                data = 1
            else:
                #发送短信验证码
                template_id = 496156   # NOTE: 这里的模板 ID`7839`只是示例，真实的模板 ID 需要在短信控制台中申请
                # # 签名
                ssender = SmsSingleSender(appid, appkey)
                params = [num, "1"]
                #发送短信验证码
                result = ssender.send_with_param(86, mobile,
                                                    template_id, params, sign=sms_sign, extend="", ext="")
                if result["result"] == 0:
                    data = 0
                    request.session["code"] = num
                else:
                    data = 2

        elif ret == "land": #注册
            try:
                #登陆校验 获取存到session 中的验证码，与用户输入的验证码比较,
                #如果在60内没有输入正确的验证码会直接删除，而这个时候就获取不到code 了
                num = request.session.get('code')
            except Exception as e:
                print(e)
                data = 2
                return HttpResponse(data)

            if MyUser.objects.filter(username=mobile).exists():
                data = 1
            else:
                if code == num:
                    #在验证码输入正确的情况下，校验输入的两次密码是否一致
                    if pass_word1 == pass_word2:
                        code = mobile[:5]
                        user_remark = "勤劳的园丁"+ code
                        MyUser.objects.create_user(
                            username=mobile, password=pass_word1,user_remark=user_remark)
                        data = 5
                        # 验证码存在session中，在用户注册成功后要删除设置的验证码，
                        del request.session['code']
                    else:
                        data = 4
                else:
                    data = 2
        return HttpResponse(data)



#重置密码
class Reset_Password(ListView):
    def post(self, request):
        # phone = json.loads(request.body.decode())
        num = ""
        for i in range(6):
            ch = chr(random.randrange(ord('0'), ord('9') + 1))
            num += ch
        mobile = request.POST.get("mobile")
        pass_word1 = request.POST.get("password")
        pass_word2 = request.POST.get("password2")
        code = request.POST.get("code")
        ret = request.POST.get("ret")

        if ret == "see":
            mobile_pat = re.compile('^(13\d|14[5|7]|15\d|166|17\d|18\d)\d{8}$')
            res = re.search(mobile_pat, mobile)
            if res:
                #校验手机号
                if MyUser.objects.filter(username=mobile).exists():
                    template_id = 496444  # NOTE: 这里的模板 ID`7839`只是示例，真实的模板 ID 需要在短信控制台中申请
                    # # 签名
                    ssender = SmsSingleSender(appid, appkey)
                    params = [num, "1"]
                    #发送短信验证码
                    result = ssender.send_with_param(86, mobile,
                                                     template_id, params, sign=sms_sign, extend="", ext="")
                    if result["result"] == 0:
                        data = 0
                        #把验证码存到session中，以便后续校验
                        request.session["code"] = num
                    else:
                        data = 2
                else:
                    data = 4
            else:
                data = 3
        elif ret == "land":
            try:
                #如果在60内没有输入正确的验证码会直接删除，而这个时候就获取不到code 了
                num = request.session.get('code')
            except Exception as e:
                data = 1
                return HttpResponse(data)
            if MyUser.objects.filter(username=mobile).exists():
                if pass_word1 == pass_word2:
                    if num == code:
                        req = MyUser.objects.get(username=mobile)
                        #密码进行加密
                        req.set_password(pass_word1)
                        # pass_word3 = make_password(pass_word1)
                        # req.password = pass_word3
                        req.save()
                        # 验证码存在session中，在用户注册成功后要删除设置的验证码，
                        del request.session['code']
                        data = 0
                    else:
                        data = 1
                else:
                    data = 2
            else:
                data = 4
        return HttpResponse(data)