# -*- coding: utf-8 -*-
# author：Li Mingjie time:2019/3/9
# Brief:

import domain_structure_analysis as DS
import time_series_analysis as TS
import user_portrait_analysis as UP
import chat_function_analysis as CF
import response_time_analysis as RT
import response_error_analysis as RE
import second_test as ST
import json
from flask import Flask, render_template
from flask import request
from flask_cors import CORS
from flask_caching import Cache
import time
import base64
import random

app = Flask(__name__)
CORS(app, supports_credentials=True)
# cache = Cache(app, config={'CACHE_TYPE': 'simple'})

print("*****datetime:")
now_time = time.strftime("%b %d %Y %H:%M:%S", time.localtime(time.time()))
print(now_time)
print("*****\n")

users = {
    "admin": "spdas!23"
}


def gen_token(uid):
    token = base64.b64encode((':'.join([str(uid), str(random.random()), str(now_time)])).encode('utf-8'))
    print("BASE64加密串:\n" + str(token, 'utf-8'))
    # users[uid].append(token)
    return token


@app.route('/SPDAS', methods=['GET'])
def index():
    return render_template('index.html')


@app.route('/SPDAS/login', methods=['POST'])
def login():
    data = request.get_data()
    json_re = json.loads(data)
    username = json_re['user']
    password = json_re['password']
    if username in users.keys() and password == users[username]:
        return gen_token(username)
        # gen_token(username)
        #return 'yes'
    else:
        return "error"


@app.route('/SPDAS/domain_structure_analysis1', methods=['POST'])
def domain():
    param = ({"data_type": [{"value": "control"}, {"value": "application"}, {"value": "all"}],
              "time": "2019-01-01 00:00:00/2019-01-02 00:00:00",
              "graph_type": [{"value": "bar"}, {"value": "pie"}],
              "image_path": "http://120.79.171.145:8000/plot_domain1.jpg"})
    return json.JSONEncoder().encode(param)


@app.route('/SPDAS/domain_structure_analysis2', methods=['POST'])
def domain_form():
    # 需要从request对象读取表单内容：
    data = request.get_data()
    json_re = json.loads(data)
    print(json_re)
    datatype = json_re['data_type']
    m_time = json_re['time']
    graphtype = json_re['graph_type']
    str_time = str(m_time)
    m_time = str_time.split('/')
    starttime = m_time[0]
    endtime = m_time[1]
    image_path = DS.data_statistics_plot(datatype=datatype, starttime=starttime, endtime=endtime, graphtype=graphtype)
    path = ({"domain_image": image_path})
    return json.JSONEncoder().encode(path)


@app.route('/SPDAS/time_series_analysis1', methods=['POST'])
def time():
    param = ({"time_type": [{"value": "hour", "id": 1}, {"value": "day", "id": 2},
                            {"value": "month", "id": 3}, {"value": "year", "id": 4}],
              "time": "2019-01-01 00:00:00/2019-01-02 00:00:00",
              "graph_type": [{"value": "bar"}, {"value": "pie"}],
              "image_path": "http://120.79.171.145:8000/plot_time1.jpg"})
    return json.JSONEncoder().encode(param)


@app.route('/SPDAS/time_series_analysis2', methods=['POST'])
def time_form():
    # 需要从request对象读取表单内容：
    data = request.get_data()
    json_re = json.loads(data)
    print(json_re)
    timetype = json_re['time_type']
    m_time = json_re['time']
    graphtype = json_re['graph_type']
    str_time = str(m_time)
    m_time = str_time.split('/')
    starttime = m_time[0]
    endtime = m_time[1]
    image_path = TS.datetime_data_plot(timetype=timetype, starttime=starttime, endtime=endtime, graphtype=graphtype)
    path = ({"time_image": image_path})
    return json.JSONEncoder().encode(path)


@app.route('/SPDAS/user_portrait_analysis1', methods=['POST'])
def user():
    param = ({"data_type": [{"value": "control"}, {"value": "application"}, {"value": "chat"}, {"value": "all"}],
              "time": "2019-01-01 00:00:00/2019-01-02 00:00:00",
              "image_path": "http://120.79.171.145:8000/plot_user1.jpg"})
    return json.JSONEncoder().encode(param)


@app.route('/SPDAS/user_portrait_analysis2', methods=['POST'])
def user_form():
    # 需要从request对象读取表单内容：
    data = request.get_data()
    json_re = json.loads(data)
    print(json_re)
    datatype = json_re['data_type']
    m_time = json_re['time']
    str_time = str(m_time)
    m_time = str_time.split('/')
    starttime = m_time[0]
    endtime = m_time[1]
    image_path = UP.portrait_plot(datatype=datatype, starttime=starttime, endtime=endtime)
    path = {"user_image": image_path}
    return json.JSONEncoder().encode(path)


@app.route('/SPDAS/chat_function_analysis/choice1', methods=['POST'])
def choice():
    param = (
        {"time": "2018-12-01 00:00:00/2018-12-28 20:00:00", "image_path": "http://120.79.171.145:8000/choice_num1.jpg"})
    return json.JSONEncoder().encode(param)


@app.route('/SPDAS/chat_function_analysis/choice2', methods=['POST'])
# @cache.cached(timeout=60 * 30, key_prefix='choice_form')
def choice_form():
    # 需要从request对象读取表单内容：
    data = request.get_data()
    json_re = json.loads(data)
    print(json_re)
    m_time = json_re['time']
    str_time = str(m_time)
    m_time = str_time.split('/')
    starttime = m_time[0]
    endtime = m_time[1]
    data_cluster = CF.Culter(start_time=starttime, end_time=endtime)
    data_cluster.feature_extraction_data()
    image_path = data_cluster.k_means(data_cluster.feature_matrix)
    path = ({"num_image": image_path})
    return json.JSONEncoder().encode(path)


@app.route('/SPDAS/chat_function_analysis/chat1', methods=['POST'])
def chat():
    param = ({"time": "2018-12-01 00:00:00/2018-12-28 20:00:00", "best_num": "1",
              "image1_path": "http://120.79.171.145:8000/hierachical_clusters1.jpg",
              "image2_path": "http://120.79.171.145:8000/cluster_point1.jpg"})
    return json.JSONEncoder().encode(param)


@app.route('/SPDAS/chat_function_analysis/chat2', methods=['POST'])
def chat_form():
    # 需要从request对象读取表单内容：
    data = request.get_data()
    json_re = json.loads(data)
    m_time = json_re['time']
    str_time = str(m_time)
    m_time = str_time.split('/')
    starttime = m_time[0]
    endtime = m_time[1]
    data_cluster = CF.Culter(start_time=starttime, end_time=endtime)
    data_cluster.feature_extraction_data()
    image_path = data_cluster.k_means(data_cluster.feature_matrix)
    charnum = json_re['best_num']
    bestnum = int(charnum)
    print(bestnum)
    image_path1 = data_cluster.k_means_cluster(best_num=bestnum)
    linkage_matrix = data_cluster.ward_hierarchical_clustering(data_cluster.feature_matrix)

    image_path2 = data_cluster.plot_hierarchical_clusters(linkage_matrix=linkage_matrix, m_data=data_cluster.chat_data,
                                                          figure_size=(35, 40))
    with open("/roobo/soft/phpmyadmin/chat_function_data.txt", 'w') as file:
        file.writelines(data_cluster.out_data)
    path = ({"cluster_point": image_path2, "ward_image": image_path1})
    return json.JSONEncoder().encode(path)


@app.route('/SPDAS/response_analysis1', methods=['POST'])
def response():
    param = ({"data_type": [{"value": "control"}, {"value": "application"}, {"value": "all"}],
              "effect_type": [{"value": "cost_time"}, {"value": "response_error"}],
              "time": "2019-01-01 00:00:00/2019-01-02 00:00:00",
              "image_path": "http://120.79.171.145:8000/response_time1.jpg"})
    return json.JSONEncoder().encode(param)


@app.route('/SPDAS/response_analysis2', methods=['POST'])
def response_form():
    # 需要从request对象读取表单内容：
    data = request.get_data()
    json_re = json.loads(data)
    print(json_re)
    datatype = json_re['data_type']
    effecttype = json_re['effect_type']
    m_time = json_re['time']
    str_time = str(m_time)
    m_time = str_time.split('/')
    starttime = m_time[0]
    endtime = m_time[1]
    if effecttype == 'cost_time':
        image_path = RT.cost_time_plot(datatype=datatype, starttime=starttime, endtime=endtime)
    else:
        image_path = RE.error_data_statistics_plot(datatype=datatype, starttime=starttime, endtime=endtime,
                                                   graphtype='bar')
    path = ({"response_image": image_path})
    print(image_path)
    return json.JSONEncoder().encode(path)


@app.route('/SPDAS/second_test1', methods=['POST'])
def second():
    param = ({"data_type": [{"value": "error_control"}, {"value": "error_application"}],
              "time": "2019-01-01 00:00:00/2019-01-02 00:00:00",
              "graph_type": [{"value": "bar"}, {"value": "pie"}],
              "image_path": "http://120.79.171.145:8000/response_error1.jpg"})
    return json.JSONEncoder().encode(param)


@app.route('/SPDAS/second_test2', methods=['POST'])
def second_form():
    # 需要从request对象读取表单内容：
    data = request.get_data()
    json_re = json.loads(data)
    print(json_re)
    datatype = json_re['data_type']
    m_time = json_re['time']
    str_time = str(m_time)
    m_time = str_time.split('/')
    starttime = m_time[0]
    endtime = m_time[1]
    graphtype = json_re['graph_type']

    image_path = ST.second_test_plot(datatype=datatype, starttime=starttime, endtime=endtime, graphtype=graphtype)
    path = ({"test_image": image_path})
    return json.JSONEncoder().encode(path)


if __name__ == '__main__':
    app.run(debug=True, host='10.7.19.129', port=5000)
