import os
import time
import json
import csv
import time

import flask
from flask import jsonify
from flask import Flask, render_template, request, session
from flask_bootstrap import Bootstrap
import test
import logincheck
import eel
from conn_mongodb import *
import add_testinfo

app = Flask(__name__)
bootstrap = Bootstrap(app)

UPLOAD_FOLDER = './static/doc'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER  # 设置文件上传的目标文件夹

app.secret_key = "lyc"
app.config['SESSION_COOKIE_NAME'] = "session_key"  # 这是配置网页中sessions显示的key


# app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(seconds=20)

@app.route('/')
def show_index():
    return render_template("index.html")
# def hello_world():
#     return 'Hello World!'


@app.route('/upload', methods=["GET", "POST"])
def upload_test():
    return render_template("upload.html")


@app.route('/show', methods=["GET", "POST"])
def show_test():
    return render_template("index.html")
    # return render_template("viewer.html")


@app.route("/api/upload", methods=["GET", "POST"])
def upload():
    file = request.files.get("file_data")
    msg = api_upload(app, file)
    upload_msg = json.loads(msg.data.decode("utf-8"))
    errmsg = upload_msg.get("errmsg")
    return jsonify({"msg": errmsg})


@app.route('/setvalue', methods=["POST", "GET"])
def setValue():
    value = request.values.get("str")
    # print(value)
    result = test.summary(value)
    # print(result)
    return result, 200


@app.route('/analyze', methods=["POST", "GET"])
def analyze():
    result = {}  # The return type must be a string, dict, tuple, Response instance, or WSGI callable
    # 摘要
    filename = request.values.get("filename")
    highlight = stories_col.find_one({"_id": int(filename)})
    print(filename, type(filename), highlight, type(highlight))
    result["highlight"] = highlight["highlight"]
    # 相似文本
    simId = similarity_col.find({"$or": [{"id": filename}, {"file_id": filename}]}).sort("sim_value", -1)  # 降序排列
    simIds = []
    for i in range(6):
        simIds.append([simId[i]["file_id"], simId[i]["sim_value"]])
    result["sim"] = simIds
    return result, 200


@app.route('/getbook', methods=["POST", "GET"])
def getbook():
    result = {}
    # 摘要
    filename = request.values.get("filename")
    highlight = stories_col.find_one({"_id": int(filename)})
    result["highlight"] = highlight["highlight"]
    # 文本info
    info = stories_col.find().sort("_id", 1)
    Ids = []
    for i in range(10):
        Ids.append({"_id": info[i]["_id"], "frequency": info[i]["frequency"], "highlight": info[i]["highlight"]})
    result["info"] = Ids
    return result, 200

@app.route('/getbook_qiangwei', methods=["POST", "GET"])
def getbook_qiangwei():
    result = {}
    # 文本info
    info = docs_col.find().sort("_id", 1)
    Ids = []
    for i in range(info.count()):
        Ids.append({"_id": info[i]["_id"], "filename": info[i]["filename"], "upper": info[i]["upper"], "upload_time": info[i]["upload_time"], "kind": info[i]["kind"], "status": info[i]["status"],"frequency": info[i]["frequency"]})
    result["info"] = Ids
    return result, 200

@app.route('/get_userhistory_qiangwei', methods=["POST", "GET"])
def get_userhistory_qiangwei():
    result = {}
    # 文本info
    info = history_col.find()
    Ids = []
    for i in range(info.count()):
        Ids.append({"_id": str(info[i]["_id"]), "email": info[i]["email"], "filename": info[i]["filename"], "mysecond": info[i]["mysecond"],  "time": info[i]["time"]})
    result["info"] = Ids
    # print(result)
    return result, 200

@app.route('/get_one_userhistory_qiangwei', methods=["POST", "GET"])
def get_one_userhistory_qiangwei():
    email = request.values.get("email")
    result = {}
    # 文本info
    info = history_col.find({"email":email})
    print(info)
    Ids = []
    for i in range(info.count()):
        Ids.append({"_id": str(info[i]["_id"]), "email": info[i]["email"], "filename": info[i]["filename"], "mysecond": info[i]["mysecond"],  "time": info[i]["time"]})
    result["info"] = Ids
    # print(result)
    return result, 200

@app.route('/get_userresult_qiangwei', methods=["POST", "GET"])
def get_userresult_qiangwei():
    # email = request.values.get("email")
    result = {}
    # 文本info
    info = result_col.find()
    print(info)
    Ids = []
    for i in range(info.count()):
        Ids.append({"_id": str(info[i]["_id"]), "email": info[i]["email"], "filename": info[i]["filename"], "result": info[i]["result"],  "time": info[i]["time"]})
    result["info"] = Ids
    # print(result)
    return result, 200

@app.route('/get_one_userresult_qiangwei', methods=["POST", "GET"])
def get_one_userresult_qiangwei():
    email = request.values.get("email")
    result = {}
    # 文本info
    info = result_col.find({"email":email})
    print(info)
    Ids = []
    for i in range(info.count()):
        Ids.append({"_id": str(info[i]["_id"]), "email": info[i]["email"], "filename": info[i]["filename"], "result": info[i]["result"],  "time": info[i]["time"]})
    result["info"] = Ids
    # print(result)
    return result, 200

@app.route('/freq_add', methods=["POST", "GET"])
def freq_add():
    filename = request.values.get("filename")
    freq = stories_col.find_one({"_id": int(filename)})["frequency"]
    stories_col.update_one({"_id": int(filename)}, {"$set": {"frequency": freq + 1}})  # 更新阅读次数
    return filename, 200

@app.route('/freq_add_qiangwei', methods=["POST", "GET"])
def freq_add_qiangwei():
    filename = request.values.get("filename")
    freq = docs_col.find_one({"filename": filename})["frequency"]
    docs_col.update_one({"filename": filename}, {"$set": {"frequency": freq + 1}})  # 更新阅读次数
    return filename, 200

@app.route('/get_username', methods=["POST", "GET"])
def get_username():
    email = request.values.get("email")
    username = userInfo_col.find_one({"email": str(email)})['username']
    return username, 200

@app.route('/get_userinfos', methods=["POST", "GET"])
def get_userinfos():
    ret, users, his = {}, {}, {}
    # 用户信息
    user_infos = userInfo_col.find()
    for info in user_infos:
        users[info["username"]] = [info["email"], info["status"]]
    ret["user"] = users
    # 用户行为数据
    his_infos = history_col.find()
    id = 0
    print(his_infos)
    for info in his_infos:
        his[id] = [info["email"], info["filename"], info["mysecond"], info["time"]]
        id += 1
    ret["his"] = his
    return ret, 200

# @app.route('/get_userinfos', methods=["POST", "GET"])
# def get_userinfos():
#     ret, users, his = {}, {}, {}
#     # 用户信息
#     user_infos = userInfo_col.find()
#     for info in user_infos:
#         print("user:", info)
#         users[info["username"]] = [info["email"], info["status"]]
#     ret["user"] = users
#     # 用户行为数据
#     his_infos = history_col.find()
#     id = 0
#     for info in his_infos:
#         print("his:", info)
#         # his[[info["_id"]]] = {"username": info["username"], "filename": info["filename"], "time": info["time"],
#         #                       "percent": info["percent"]}
#         his[id] = [info["username"], info["filename"], info["time"], info["percent"]]
#         id += 1
#     ret["his"] = his
#     return ret, 200


@app.route('/login', methods=["POST", "GET"])
def login():
    return render_template("login.html")


@app.route('/login_check', methods=["POST", "GET"])
def login_check():
    if request.method == 'GET':
        email = request.values.get('email')
        password = request.values.get('password')
        if not email:  # 账号不能为空
            return "null"
        result = logincheck.login(email, password)
        if (result == "wrong"):
            return 'wrong'
        elif (result == "signup"):
            return 'signup'
        else:
            session['email'] = email
            session.permanent = True
            if (result == "admin"):
                return 'admin'
            else:
                return 'ok'


@app.route('/signup_check', methods=["POST", "GET"])
def signup_check():
    if request.method == 'GET':
        email = request.values.get('email')
        password = request.values.get('password')
        username = request.values.get('username')
        if not email:  # 账号不能为空
            return "null"
        result = logincheck.signup(email, username, password)
        if (result == "NO"):
            return 'NO'
        else:
            session['email'] = email
            session.permanent = True
            return result

@app.route('/save_test', methods=["POST", "GET"])
def save_test():
    print("saving")
    if request.method == 'POST':
        data=request.get_json()
        print(data)
        email = data['email']
        myfilename = data['filename']
        mysecond = int(data['mysecond'])
        transfermsg = data['transfermsg']
        freq = data['freq']
        seqlist = data['seqlist']
        pagefreq = data['pagefreq']
        pagefreqoff = data['pagefreqoff']
        # transfermsg = eval(data['transfermsg'])
        # freq = eval(data['freq'])
        # seqlist = eval(data['seqlist'])
        # pagefreq = eval(data['pagefreq'])
        # pagefreqoff = eval(data['pagefreqoff'])
        # email = request.values.get('email')
        # myfilename = request.values.get('filename')
        # mysecond = request.values.get('mysecond')
        # transfermsg = request.values.get('transfermsg')
        # freq = request.values.get('freq')
        # seqlist = request.values.get('seqlist')
        # pagefreq = request.values.get('pagefreq')
        # pagefreqoff = request.values.get('pagefreqoff')
        # close_list= request.values.get('close_list')
        # print(pagefreqoff)
        if not email:  # 账号不能为空
            return "null"
        result = add_testinfo.save_data_simple(email, myfilename,mysecond,transfermsg,freq,seqlist,pagefreq,pagefreqoff)
        if (result == "OK"):
            return 'OK'
        else:
            return 'NO'
    print("NO")
    return "NO"
    

@app.route('/save_test_result', methods=["POST", "GET"])
def save_test_result():
    if request.method == 'POST':
        data=request.get_json()
        email = data['email']
        testresult = data['testresult']
        filename = data['filename']
        if not email:  # 账号不能为空
            return "null"
        print("mydata:",testresult)
        result = add_testinfo.save_result(email, testresult,filename)
        if (result == "OK"):
            print("OK")
            return "OK"
        else:
            return "NO"
@app.route('/save_test_accuracy', methods=["POST", "GET"])
def save_test_accuracy():
     if request.method == 'GET':
        email = request.values.get('email')
        onlinelist = request.values.get('onlinelist')
        offlinelist = request.values.get('offlinelist')
        testseqlist = request.values.get('testseqlist')
        evallist = request.values.get('evallist')
        if not email:  # 账号不能为空
            return "null"
        print("mydata:",onlinelist)
        result = add_testinfo.save_accuracy(email, onlinelist,offlinelist,testseqlist,evallist)
        if (result == "OK"):
            print("OK")
            return 'OK'
        else:
            return "NO"

@app.route('/calculate_freq_per_sentence', methods=["POST", "GET"])
def calculate_freq_per_sentence():
    data = json.loads(request.get_data(as_text=True))
    print(data)
    print(type(data))
    transfermsg = json.loads(data['transfermsg'])
    timestamp = data['timestamp']
    print(timestamp)
    splited_text_filepath = 'result2.txt'
    sents_base = []
    sents_pdfjs = [] # 记录transfermsg中的items
    freq_pdfjs = [] # 记录transfermsg中的freq
    str1 = str2 = ''
    with open(splited_text_filepath, 'r', encoding='utf-8') as f:
        for line in f.readlines():
            line = line.strip()
            if (line == ''):
                continue
            # 每一句后都补一个空格
            line += ' '
            sents_base.append(line)
            str1 += line
    for it in transfermsg:
        # 块最后不为空格 就补一个空格
        block_item = it['items'] 
        if block_item[-1] != ' ':
            block_item += ' '
        sents_pdfjs.append(block_item)
        freq_pdfjs.append(it['freq'])
        str2 += block_item
    # 此时需要保证str1与str2相等(起码长度相等) 否则会出问题
    print(len(str1), len(str2))
    belong = [0 for _ in range(len(str1))] # 记录每个字符属于第几句话
    freq = [0 for _ in range(len(sents_base))] # 记录每句话的注视频率
    j = 0 # 记录累计统计了多少个字符
    for i in range(len(sents_base)): # 分句到第i句
        for _ in range(len(sents_base[i])):
            belong[j] = i
            j += 1
    j = 0
    for i in range(len(sents_pdfjs)):
        for _ in range(len(sents_pdfjs[i])):
            # print(belong[j])
            freq[belong[j]] += freq_pdfjs[i] / len(sents_pdfjs[i]) # 相当于把每个块的freq平均到每个字符上
            j += 1
    print(freq)

    basedir = os.path.abspath(os.path.dirname(__file__))  # 获取当前项目的绝对路径
    print(basedir)
    tmp_filepath = os.path.join('static', 'statistic', 'data%s.txt' % (timestamp))
    csv_filepath = os.path.join(basedir, tmp_filepath)

    print(csv_filepath)
    with open(csv_filepath, 'w', encoding = 'utf-8', newline = '') as csvfile:
        writer = csv.DictWriter(csvfile, fieldnames=['freq','sentence'])
        writer.writeheader()
        for i in range(len(sents_base)):
            writer.writerow({'freq': freq[i], 'sentence': sents_base[i]})
        csvfile.close()
    # print(sents)
    return 'OK'

def api_upload(app_boj, file):
    basedir = os.path.abspath(os.path.dirname(__file__))  # 获取当前项目的绝对路径
    file_dir = os.path.join(basedir, app_boj.config['UPLOAD_FOLDER'])  # 拼接成合法文件夹地址
    if not os.path.exists(file_dir):
        os.makedirs(file_dir)  # 文件夹不存在就创建
    fname = file.filename
    ext = fname.rsplit('.', 1)[1]  # 获取文件后缀
    unix_time = int(time.time())
    new_filename = str(unix_time) + '.' + ext  # 修改文件名
    file.save(os.path.join(file_dir, new_filename))  # 保存文件到upload目录
    return jsonify({"result": 1, "new_name": new_filename, "errmsg": "上传成功"})


if __name__ == '__main__':
    app.run(debug=False)
