from flask import url_for,redirect,Flask,make_response,render_template,request,jsonify,session
import uuid
import mysql.connector
from ast import literal_eval
from qcloud_cos import CosConfig
from qcloud_cos import CosS3Client
from qcloud_cos import CosServiceError
from qcloud_cos import CosClientError
import sys
import logging
import time
from operator import itemgetter
import timeago,datetime
import json

app = Flask(__name__)

app.jinja_env.variable_start_string = '[['
app.jinja_env.variable_end_string = ']]'


def get_time():
    computer_time = str(time.strftime('%Y/%m/%d %H:%M:%S', time.localtime(time.time())))
    return computer_time

def get_ip():
    ip = request.environ.get('HTTP_X_REAL_IP', request.remote_addr)
    return ip

def database_operation(operation_type,form_name,obj_key=None,obj_value=None,update_key=None,update_value=None,):
    conn = mysql.connector.connect(user='root', password='20001103', database='icbc', charset="utf8mb4",
                                   use_unicode=True)
    cursor = conn.cursor(dictionary=True)
    try:
        if operation_type == "search":
            if obj_key and obj_value:
                sql = 'select * from %s where %s = "%s"' % (form_name,obj_key,obj_value)
            else:
                sql = "SELECT * FROM "+str(form_name)
            cursor.execute(sql)
            u = cursor.fetchall()
            #u.sort(key=itemgetter('time'), reverse=True)
            conn.commit()
            return u

        # print(database_operation("insert","creative_data",'(id)','("storyfaee7d17-221f-408a-b6f6-3de78c109")'))
        if operation_type == "insert":
            if obj_key and obj_value :
                cursor.execute(
                'insert into ' + form_name + " " + obj_key + ' values' + obj_value)
                conn.commit()
            if change_cache(form_name):
                return "insert successful"
        if operation_type == "update":
            if obj_key and obj_value and update_key and update_value :
                cursor.execute('update %s set %s = "%s" where %s = "%s"'
                               %(form_name,update_key,update_value,obj_key,obj_value))
                conn.commit()
            if change_cache(form_name):
                return "update_successful"
        if operation_type == "delete":
            if obj_key and obj_value :
                cursor.execute('delete from %s where %s = "%s"'
                               % (form_name, obj_key, obj_value))
                conn.commit()
            if change_cache(form_name):
                return "delete_successful"
    except:
        pass
    conn.close()
    return "error"

def change_cache(form_name):
    global creative_database
    if form_name == "creative_data":
        creative_database = database_operation("search", "creative_data")
        return True

# database cache 数据库读本地缓存

creative_database = database_operation("search","creative_data")

@app.route('/api/video_up_video', methods=['GET', 'POST'])
def up_file1():
    if request.method == "POST":
        address = str(uuid.uuid4())[0:8]
        t = request.cookies.get("id")
        file = request.files['mf']
        file_address_test = t + str(file.filename)
        new_fname = r'static/user_files/' + str(file_address_test)
        file.save(new_fname)  # 保存文件到指定路径
        #print("本地保存成功")
        # up_tencent(new_fname,
        #            "web_file/picture/" + address + "/" + str(file.filename))
        #print(t,str(file.filename))
        # database_operation("insert", "creative_data", "(id,type,time,name,author,author_id,summary,content)",
        #                    str((t,"file", get_time(), str(file.filename),address,get_ip(),str(file.filename),"none"))
        #                    )
        database_operation("insert", "creative_data", "(id,type,time,name,author,author_id,summary,content)",
                           str((t,"file", get_time(), str(file.filename),t,get_ip(),str(file.filename),"none"))
                           )
        return jsonify('上传成功')
    return "fuck"



def get_type_data(type,number):
    #global creative_database
    u = []
    for i in creative_database:
        if i["type"] == type :
            u.append(i)
    u.sort(key=itemgetter('time'), reverse=True)
    try:
        t = u[0:int(number)]
    except:
        t = u
    return t


def change_time_type(data):
    now = datetime.datetime.now()
    t = []
    for i in data:
        f = {}
        if i["comment_number"] == "true":
            f["name"], f["summary"], f['author'], f["author_id"], f["content"], f["id"], f["type"], f["time"], f[
                "view_number"] \
                = i["name"], i["summary"], i['author'], i["author_id"], i["content"], i["id"], i["type"], i["time"], i[
                "view_number"]
            f["time"] = timeago.format(f["time"], now, "zh_CN")
            t.append(f)
    return t



def change_password_type(data):
    t = []
    for i in data:
        f = {}
        if i["view_number"] == "true":
            f["name"], f["summary"], f['author'], f["author_id"], f["content"], f["id"], f["type"], f["time"], f[
                "view_number"] \
                = i["name"], i["summary"], "", i["author_id"], i["content"], i["id"], i["type"], i["time"], i[
                "view_number"]
            t.append(f)
        else:
            f["name"], f["summary"], f['author'], f["author_id"], f["content"], f["id"], f["type"], f["time"], f[
                "view_number"] \
                = i["name"], i["summary"], i['author'], i["author_id"], i["content"], i["id"], i["type"], i["time"], i[
                "view_number"]
            t.append(f)
    return t








def get_cache_data(cache_name,obj_key=None,obj_value=None,number= 0 ,display = None ):
    try:
        f = []
        for i in cache_name:
            t = i[obj_key]
            if t == obj_value:
            #     if display:
            #         if i["others"] != "{'display': None}":
            #             f.append(i)
            #     else:
            #         f.append(i)
                f.append(i)
        # if cache_name == creative_database:
        #     f.sort(key=itemgetter('time'), reverse=True)
        # if cache_name == comment_database:
        #     f.sort(key=itemgetter('comment_time'), reverse=True)
        if f != []:
            if number == "h":
                return f[0]
            if number == "all":
                return f
            if number == "random":
                return random.sample(f , 4)
            if number == 0:
                return [f[0]]
            if len(f) >= number:
                return f[0:number]
            else:
                return f
        else:
            return []
    except:
        None




@app.route("/",methods = ["get","POST"])
def aa():
    return render_template("main.html")




@app.route("/files",methods = ["get","POST"])
def aaa():
    return render_template("index.html")



@app.route("/up_file",methods = ["get","POST"])
def bb():
    id = str(uuid.uuid4())[0:8]
    response = make_response(render_template("up_file.html"))
    response.set_cookie("id",id, 3600)
    return response


def search(search_value):
    u = get_type_data("file",500)
    t = []
    for i in u:
        try:
            if search_value in i["name"] or search_value in i["summary"] or  search_value in i["content"]:
                t.append(i)
        except:
            pass
    return t


@app.route("/search",methods = ['get'])
def response_search():

    search_value = str(request.values.get("s"))
    response = make_response(render_template("search_result.html"))
    response.set_cookie("search_value", search_value, 3600)
    return response



#此处的代码有转义,实际nane应该加尖括号
@app.route("/file/name",methods = ["get","POST"])
def cc(name):
    file_name = name
    response = make_response(render_template("file_content.html"))
    response.set_cookie("file_name", file_name, 3600)
    return response


@app.route("/api/get_data",methods = ["get","POST"])
def dd():
    request_data = json.loads(request.get_data())
    id = request.cookies.get("id")
    password,password_value,public,other_name,other_name_value,note = request_data["password"],\
        request_data["password_value"],request_data["public"],request_data["other_name"],\
        request_data["other_name_value"],request_data["note"]
    database_operation("update", "creative_data", "id", id, "view_number", password)
    database_operation("update", "creative_data", "id", id, "like_number", password_value)
    database_operation("update", "creative_data", "id", id, "comment_number", public)
    database_operation("update", "creative_data", "id", id, "all_comment", other_name)
    database_operation("update", "creative_data", "id", id, "summary", other_name_value)
    database_operation("update", "creative_data", "id", id, "content", note)
    print(request_data)
    return jsonify("success")


@app.route("/api/get_data1",methods = ["get","POST"])
def ff():
    return jsonify(change_password_type(change_time_type(get_type_data("file",50))))


@app.route("/api/get_data2",methods = ["get","POST"])
def gg():
    request_data = json.loads(request.get_data())
    return jsonify(change_password_type(get_cache_data(creative_database,"id",request_data["type"])))



@app.route("/api/verify",methods = ["get","POST"])
def hh():
    request_data = json.loads(request.get_data())
    password = request_data["password"]
    t = get_cache_data(creative_database, "id", request_data["type"])
    real_password = t[0]["like_number"]
    if password == real_password:
        return jsonify(t[0]["author"])
    return jsonify("password_error_huang")


@app.route("/api/search",methods = ["get","POST"])
def ii():
    search_value = request.cookies.get("search_value")
    #print(search(search_value))
    return {'search_result' : search(search_value),
            "search_value" : search_value }


if __name__ == '__main__':

    app.run(host='127.0.0.1', port=5002, debug='True')