# Create your views here.
import json
import base64

import re
from django import http
from django.shortcuts import render,redirect

# Create your views here.
from django.views import View
from django.conf import settings
from django.db import connection, transaction
import datetime
from django.contrib.auth import authenticate, login,logout

from utils.sqlinjection import sqlinjections
from utils.cust_data import customer_data
from utils.et_CACC_NO import et_CACC_NO
from utils.examine_ood import examine_ood
from utils.if_account import if_account

from utils.usr_data import usr_data
from utils.monthly_odd import monthly_odd
from utils.executeQuery import executeQuery

# 用户注册
from users.models import Customer

# 用户注册
class RegisterView(View):
    def get(self,request):
        return render(request,'register.html')

    def post(self,request):
        #1,获取参数
        user_name = request.POST.get("user_name")
        pwd = request.POST.get("pwd")
        #2,校验参数
        #2,1 为空校验
        if not all([user_name,pwd]):
            return http.HttpResponseForbidden("参数不全")

        #3,创建用户对象,保存到数据库中
        user = Customer.objects.create(username=user_name,password=pwd)

        #4,返回响应
        response = redirect("http://www.taobao.com")
        return response
# 用户登录处理
class Login(View):
    def get(self, request):
        return render(request, 'login.html')
    def post(self, request):
        # req_data = json.loads(request.body.decode())["params"]
        # user_1 = req_data.get("user_1").split('->')[0]
        # pswd = req_data.get("pswd")
        sqlinjection = sqlinjections().ifsql(request.POST)
        if sqlinjection:
            return http.HttpResponseForbidden("参数非法")
        user_1 = request.POST.get("user_name").split('->')[0]
        # print(request.POST)
        pswd = request.POST.get("pwd").lower()
        # 校验参数
        if not all([user_1,pswd]):
            return http.HttpResponseForbidden("请输入账号密码")
        # 判断用户密码正确性
        try:
            user = Customer.objects.get(user_no=user_1)
        except Exception:
            return http.HttpResponseForbidden("存在重复的账号，请联系管理员")
        # 对数据库密码进行解码
        try:
            sql_password = bytes(base64.b64decode(user.password.encode(encoding='utf-8'))).decode()
        except Exception:
            return http.HttpResponseForbidden("密码被后台操作过请联系管理员")
        print(sql_password)
        # 校验密码是否正确
        if user.user_no !=user_1 or sql_password!=pswd:
            return http.HttpResponseForbidden("账号或者密码错误")
        # 3,状态保持
        # login(request, user)
        # 3,1设置状态保持的时间
        # if request.session.get('username'):
        request.session['username'] = user_1
        request.session.set_expiry(3600 * 24 * 2)  # 两天有效
        response = redirect('/index')
        response.set_cookie("username", user.username, 3600 * 24 * 2)
        return response
        # 4,返回响应
        # context = {
        #     "errmsg": "登录成功",
        #     "code": 200
        # }
        # return http.JsonResponse(context)
    def put(self,request):
        req_data = json.loads(request.body.decode())["params"]
        user_2 = req_data.get("user_2").split('->')[0]
        print(user_2)
        pswd_old = req_data.get("pswd_old").lower()
        pswd_new = req_data.get("pswd_new").lower()
        print(req_data)
        try:
            user = Customer.objects.get(user_no=user_2)
        except Exception:
            return http.HttpResponseForbidden("存在重复的账号，请联系管理员")
        # 对数据库密码进行解码
        try:
            sql_password = bytes(base64.b64decode(user.password.encode(encoding='utf-8'))).decode()
        except Exception:
            return http.HttpResponseForbidden("密码被后台操作过请联系管理员")
        # 判断输入的密码是否正确
        if user.user_no !=user_2 or sql_password!=pswd_old:
            return http.HttpResponseForbidden("旧密码与账号不匹配")
        pswd_new = bytes(base64.b64encode(pswd_new.encode())).decode()
        user.password = pswd_new
        user.save()
        context = {
            "message":"修改成功",
            "code":200
        }
        return http.JsonResponse(context)
    def delete(self, request):
        del request.session['username']
        response = redirect('/login/')
        response.delete_cookie("username")
        return response
        # context = {
        #     "errmsg": "登录成功",
        #     "code": 200
        # }
        # return http.JsonResponse(context)
class Logout(View):
    def get(self, request):
        del request.session['username']
        response = redirect('/login/')
        response.delete_cookie("username")
        return response
#获取用户登录信息
class LoginInformation(View):
    def get(self, request):
        search_no = request.GET["search_no"]
        if search_no != '':
            search_no = ' USR LIKE ' + "'" + '%%' + search_no + '%%' + "'" + ' OR ' + '[NAME] LIKE ' + "'" + '%%' + search_no + '%%' + "'"
            # search_no = ' PRD_NO LIKE '+"'"+'%%'+search_no+'%%'+"'"
            sql = """SELECT USR,NAME FROM PSWD WHERE {0}""".format(search_no)
        else:
            sql = """SELECT USR,NAME FROM PSWD """
        data = []
        print(sql)
        with connection.cursor() as cursor:
            try:
                dep_data = cursor.execute(sql, []).fetchall()
            except Exception:
                context = {
                    "data": data,
                    "errmsg": "没有获取到数据",
                    "code": 510
                }
                return http.JsonResponse(context)
        if len(dep_data) != 0:
            for i in dep_data:
                data.append({"id": i[0], "text": str(i[0]) + '->' + str(i[1])})
        # print(data)
        context = {
            "data": data,
            "errmsg": "获取用户信息成功",
            "code": 200
        }
        return http.JsonResponse(context)
