# -*-coding:utf-8 -*-
import json
import time
import traceback
# from django.shortcuts import render
# from django.http import HttpResponse
# from django.core.serializers.json import DjangoJSONEncoder
from django.contrib.auth.hashers import make_password, check_password
from django.views.decorators.csrf import csrf_exempt
from django.core.exceptions import ObjectDoesNotExist
from models import *

from common.common import (get_user_from_request, login_required,
                           params,JsonResponse)



# @login_required
@csrf_exempt
@params
def user_manage(request):
    """
    用户管理
    :param request:
    :return: userdata list

    """
    # user = request.session.get("user", None)
    data = request.PARAMS
    search_name = data.get("search_name", None)
    # search_name = "ton"
    print("search_name",search_name)
    if search_name:
        user_data = Users.objects.filter(username__icontains=search_name)
    else:
        user_data = Users.objects.all()

    print("user_manage111",user_data)
    data_show =[]
    if user_data:
        for list_data in user_data:
            dict_data = {}
            dict_data["uid"] = list_data.id
            dict_data["username"] = list_data.username
            dict_data["realname"] = list_data.real_name
            dict_data["status"] = list_data.status
            dict_data["permission"] = list_data.permission
            data_show.append(dict_data)
        res = {"code": 0, "msg": "get data success", "user_data": data_show}

    else:
        res = {"code": -1, "msg": "get no data!"}

    print(res)
    return JsonResponse(res)

# @login_required
@csrf_exempt
@params
def adduser(request):
    """
    添加用户
    :param request:
    :return: True/False
    """
    req_params = request.PARAMS
    if req_params:
        try:
            username = req_params.get("username")
            password = make_password(req_params.get("password"), None,
                                     "pbkdf2_sha256")
            status = req_params.get("status")
            permission = req_params.get("permission")
            real_name = req_params.get("real_name",None)
            print("adduser---real_name",real_name)
            print(username,password,status,permission)

            obj, created = Users.objects.get_or_create(username=username)
            if not created:
                return JsonResponse({"code": -1, "msg": u"该用户名已被注册"})
            else:
                # 保存其他信息
                obj.username = username
                obj.real_name = real_name
                obj.password = password
                obj.status = int(status)
                obj.permission = int(permission)

                obj.save()
                return JsonResponse({"code": 0, "msg": u"注册成功"})
        except:
            traceback.print_exc()
    else:
        return JsonResponse({"code": -1, "msg": u"缺少参数"})

@csrf_exempt
@params
def login(request):
    """
    用户登录
    :param request: username, password
    :return: True / False
    """
    data = request.PARAMS
    print("login****",data)
    if not data:
        return JsonResponse({"code": -1, "msg": u"参数不完整"})

    username = data.get("username", None)
    passwd = data.get("password", None)

    # 获取user的password
    try:
        user = Users.objects.get(username=username)
    except ObjectDoesNotExist:
        print("user not exit********")
        return JsonResponse({"code": -1, "msg": u"该用户不存在"})

    # 检查密码是否正确
    check_res = check_password(passwd, user.password)
    
    print("***********")
    print(username)
    print(user.username)
    print(check_res)
    if check_res:
        user_info = {"uid":user.id, "username": user.username,"realname": user.real_name,
                     "status": user.status, "permission": user.permission,}

        print("user_info",user_info)
        request.session["user"] = user_info
        res = {"code": 0, "msg": "success", "user": user_info}
    else:
        res = {"code": -1, "msg": "password wrong!"}

    print "set session: --> ", request.session.get("user", None)

    return JsonResponse(res)


# @login_required
@params
def logout(request):
    """
    退出
    :param request:
    :return:
    """
    try:
        del request.session["user"]
    except KeyError as ex:
        pass
    return JsonResponse({"code": 0, "msg": "success"})



@csrf_exempt
@login_required
@params
def modified_password(request):
    """
    修改密码
    :param request: old_password, new_password
    :return: True / False
    """
    user = get_user_from_request(request)
    print("uuuuuuu",user)
    req_params = request.PARAMS
    old_password = req_params.get("old_password")
    new_password = req_params.get("new_password")
    uid = user["uid"]
    print("*****uid",uid)
    user_obj = Users.objects.filter(id=uid).first()
    print("-----",user_obj)
    if user_obj:
        check_old = check_password(old_password, user_obj.password)

        print("mmmmmmm",check_old)
        if check_old:
            new_pass = make_password(new_password, None, "pbkdf2_sha256")
            user_obj.password = new_pass
            user_obj.save()
            res = {"code": 0, "msg": "success"}
        else:
            res = {"code": -1, "msg": "旧密码不正确"}
    else:
        res = {"code": 2, "msg": "没有登陆"}
    print(res)
    return JsonResponse(res)


@csrf_exempt
# @login_required
@params
def update_user(request):
    """
    编辑用户信息
    :param request: username
    :return: True / False
    """
    req_params = request.PARAMS
    if req_params:
        try:
            # username = req_params.get("username")
            uid = req_params.get("uid")
            status = req_params.get("status")
            permission = req_params.get("permission")
            print "status --> ", status
            print "permission --> ", permission

            user_obj = Users.objects.filter(id=uid).first()
            print("update-----",user_obj)

            if user_obj:
                user_obj.status = status
                user_obj.permission = permission
                user_obj.save()
                res = {"code":0, "msg":"updte success"}
            else:
                res = {"code":-1, "msg":"update fail"}
        except:
            traceback.print_exc()

    else:
        res = {"code":-1, "msg":"参数不完整"}

    print(res)
    return JsonResponse(res)

@csrf_exempt
# @login_required
@params
def delete_user(request):
    """
    删除指定用户
    :param request: username
    :return: True / False
    """
    req_params = request.PARAMS
    uid = req_params.get("uid", None)

    user_obj = Users.objects.filter(id=uid).first()
    print(user_obj)
    if user_obj:
        user_obj.delete()
        res = {"code":0, "msg":"删除成功"}
    else:
        res = {"code":-1, "msg":"删除失败"}

    print(res)
    return JsonResponse(res)




@csrf_exempt
# @login_required
@params
def reader_fb(request):
    """
    读者提问

    """
    data = request.PARAMS
    search_question = data.get("search_question", None)

    print("00000",search_question)
    if search_question:
        reader_data = Reader.objects.filter(question__icontains = search_question)
    else:
        reader_data = Reader.objects.all()
    data =[]
    if reader_data:
        for list_data in reader_data:
            dict_data = {}
            dict_data["rid"] = list_data.id
            dict_data["readername"] = list_data.readername
            dict_data["create_time"] = list_data.create_time
            dict_data["question"] = list_data.question


            # list_reply = Reply.objects.filter(fb_id = list_data.id).values('u_id','fb_content')

            # for dict_v in list_reply:
            #     name = Users.objects.filter(id=dict_v['u_id']).first().username
            #     dict_v['u_id'] = name

            # dict_data["fb_content"] = list_reply
            # print list_reply

            data.append(dict_data)
        res = {"code": 0, "msg": "get data success", "reader_data": data}

    else:
        res = {"code": -1, "msg": "get empty data!"}

    print(res)
    return JsonResponse(res)



@csrf_exempt
# @login_required
@params
def fb_question(request):
    """
    编辑回复信息
    :param request: rid ,content
    :return: True / False
    """
    
    user_id = 3
    # user = get_user_from_request(request)
    # if user:
    #     user_id = user["uid"]
    # else:
    #     return JsonResponse({"code":-1, "msg":"没登陆"})
    req_params = request.PARAMS
    if req_params:
        try:
            rid = req_params.get("rid")
            fb_content = req_params.get("fb_content")

            # reader_obj = Reader.objects.filter(id=rid).first()
            obj= Reply.objects.create(fb_id_id= rid,u_id_id = user_id,fb_content = fb_content)
            # print("update-----",reader_obj)
            if obj:
                print(obj)
                return JsonResponse({"code":0, "msg":"success", "fb_content":fb_content})
            else:
                return JsonResponse({"code":-1, "msg":"回复失败"})
        except:
            traceback.print_exc()

    else:
        return JsonResponse({"code":-1, "msg":"参数不完整"})
