import math
import random
import psutil
import pymysql
import pytz

from flask import Flask, render_template, jsonify, request, session, redirect, url_for
from datetime import datetime
from sqlalchemy.sql.ddl import CreateTable

app = Flask(__name__)
# 创建数据库连接
app.secret_key = 'SecretKey'    # 设置Secret Key

@app.route("/404")  #host:post/404:404页面展示，主要用于划分权限查看
def index_404():
    return render_template('page/404.html',)

##注销页面
@app.route("/logout")  #host:post/logout:
def logout():
    session.clear()  # 清除会话数据
    # session['logged_out'] = True
    return redirect(url_for('login'))
##注册页面
@app.route("/register")
def register():
    return render_template('page/register.html',)
##登录页面
@app.route("/login")
def login():
    return render_template('page/login.html',)
##登录接口，通过Ajax实现异步交互
@app.route("/api_login", methods=['GET'])
def api_login():
    username =request.args.get('username')
    password = request.args.get('password')
    # 连接到数据库
    connection = pymysql.connect(host='192.168.153.165', user='yunwei', password='123456', database='yunwei', charset='utf8mb4',cursorclass=pymysql.cursors.DictCursor)
    try:
        with connection.cursor() as cursor:
            # 检查用户名和密码是否正确
            sql = f"SELECT * FROM user WHERE username = '{username}' AND password = '{password}'"
            cursor.execute(sql)
            result = cursor.fetchone()

            if result:
                session['quanxian'] = result['quanxian']
                session['username'] = username
                data={'code':0,'msg':'登录成功'}
            else:
                data = {'code': 1, 'msg': '登录失败'}
    finally:
        connection.close()  # 确保数据库连接被关闭
    return jsonify(data)

@app.route("/api_register", methods=['GET'])
def api_register():
    username =request.args.get('username')
    password = request.args.get('password')
    # 连接到数据库
    connection = pymysql.connect(host='192.168.153.165', user='yunwei', password='123456', database='yunwei', charset='utf8mb4',cursorclass=pymysql.cursors.DictCursor)
    try:
        with connection.cursor() as cursor:
            # 插入一条数据的 SQL 语句
            sql = """
                INSERT INTO user(username, password,quanxian)
                VALUES (%s, %s, %s)
                """
            # 替换 %s 为你想要插入的数据
            data = (username,password,0)
            # 执行 SQL 语句
            cursor.execute(sql, data)
            # 提交事务
            connection.commit()

            res_data = {
                'code': 0,
                'msg': '注册成功'
            }
    except:
        res_data = {
            'code': 1,
            'msg': '注册失败'
        }
    finally:
        connection.close()  # 确保数据库连接被关闭

    return jsonify(res_data)

@app.route("/")
def logins():
    return render_template('page/login.html',)

@app.route("/index_echarts")
def index_echarts():
    return render_template('index.html',)
##告警
@app.route("/warings")
def warings():
    if session['quanxian'] == 1:
        return render_template('page/warings.html')
    else:
        return render_template('page/404.html')
##管理员权限
@app.route("/admin")
def admin():
    username = session['username']
    data={
        'username':username
    }
    return render_template('page/index.html', **data)

@app.route("/log")
def log():
    return render_template('page/table.html',)
##用户权限
@app.route("/user")
def user():
    if session['quanxian'] ==1:
        return render_template('page/user.html')
    else:
        return render_template('page/404.html')

@app.route("/install")
def install():
    try:
        db = pymysql.connect(host='192.168.153.165', user='yunwei',      password='123456',database='yunwei',  charset='utf8mb4',cursorclass=pymysql.cursors.DictCursor)
        with db.cursor() as cursor:
            # 创建一个表的 SQL 语句
            sql = """
            CREATE TABLE IF NOT EXISTS my_table (
                ID INT AUTO_INCREMENT PRIMARY KEY,
                CPU FLOAT NOT NULL,
                neicun FLOAT NOT NULL,
                disk FLOAT NOT NULL,
                shang FLOAT NOT NULL,
                xia FLOAT NOT NULL,
                jiqihao VARCHAR(80),
                at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
            """
            user_sql = """
                  CREATE TABLE IF NOT EXISTS user (
                      ID INT AUTO_INCREMENT PRIMARY KEY,
                      username VARCHAR(80) UNIQUE NOT NULL,
                      password VARCHAR(80),
                      quanxian INT,
    
                      at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
                  ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
                  """
            warings = """
            CREATE TABLE IF NOT EXISTS warings (
                ID INT AUTO_INCREMENT PRIMARY KEY,
                CPU FLOAT NOT NULL,
                neicun FLOAT NOT NULL,
                disk FLOAT NOT NULL,
                shang FLOAT NOT NULL,
                xia FLOAT NOT NULL,
                jiqihao VARCHAR(80),
                message VARCHAR(80),
                ip VARCHAR(80),
                at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
            """
            # 执行 SQL 语句
            cursor.execute(warings)
            # 执行 SQL 语句
            cursor.execute(user_sql)
            # 执行 SQL 语句
            cursor.execute(sql)
            # 提交事务
            db.commit()

    finally:
        # 关闭数据库连接
        db.close()
    return jsonify({'code':0,'msg':'数据库创建成功'})

@app.route("/api_log", methods=['GET'])
def api_log():
    # 假设每页显示10条记录
    LIMIT_PER_PAGE =int(request.args.get('limit'))
    # 假设我们要查询第3页的数据
    PAGE = int(request.args.get('page'))
    # 计算 OFFSET
    OFFSET = (PAGE - 1) * LIMIT_PER_PAGE
    # 创建数据库连接
    connection = pymysql.connect(host='192.168.153.165', user='yunwei', password='123456', database='yunwei', charset='utf8mb4',cursorclass=pymysql.cursors.DictCursor)
    try:
        with connection.cursor() as cursor:
            # 创建一个 SQL 查询，使用 LIMIT 和 OFFSET 进行翻页
            sql = "SELECT * FROM my_table LIMIT %s OFFSET %s"
            cursor.execute(sql, (LIMIT_PER_PAGE, OFFSET))
            # 获取所有记录
            results = cursor.fetchall()
            # 创建一个 SQL 查询，用于获取表中的行数
            sql_count = "SELECT COUNT(*) FROM my_table"
            cursor.execute(sql_count)
            result_count = cursor.fetchone()
            count = result_count['COUNT(*)']
            res=[]
            for row in results:
                print(row)
                res.append({
                    'id':row['ID'],
                    'cpu':row['CPU'],
                    'disk':row['disk'],
                    'shang':row['shang'],
                    'xia':row['xia'],
                    'neicun':row['neicun'],
                    'jiqihao': row['jiqihao'],
                    'at':row['at']
                })
    finally:
        # 关闭数据库连接
        connection.close()
    data={'code':0,'msg':'','count':count,'data':res}
    return jsonify(data)

@app.route("/api_warings", methods=['GET'])
def api_warings():
    # 设置页面数据量
    LIMIT_PER_PAGE =int(request.args.get('limit'))
    # 查询页面数据
    PAGE = int(request.args.get('page'))
    # 计算 OFFSET
    OFFSET = (PAGE - 1) * LIMIT_PER_PAGE
    # 创建数据库连接
    connection = pymysql.connect(host='192.168.153.165', user='yunwei', password='123456', database='yunwei', charset='utf8mb4',cursorclass=pymysql.cursors.DictCursor)
    try:
        with connection.cursor() as cursor:
            # 创建一个 SQL 查询，使用 LIMIT 和 OFFSET 进行翻页
            sql = "SELECT * FROM warings LIMIT %s OFFSET %s"
            cursor.execute(sql, (LIMIT_PER_PAGE, OFFSET))
            # 获取所有记录
            results = cursor.fetchall()
            # 创建一个 SQL 查询，用于获取表中的行数
            sql_count = "SELECT COUNT(*) FROM warings"
            cursor.execute(sql_count)
            result_count = cursor.fetchone()
            count = result_count['COUNT(*)']
            res=[]
            for row in results:

                res.append({
                    'id':row['ID'],
                    'cpu':row['CPU'],
                    'disk':row['disk'],
                    'shang':row['shang'],
                    'xia':row['xia'],
                    'neicun':row['neicun'],
                    'jiqihao': row['jiqihao'],
                    'message': row['message'],
                    'at':row['at']
                })
    finally:
        # 关闭数据库连接
        connection.close()
    data={'code':0,'msg':'','count':count,'data':res}
    return jsonify(data)

@app.route("/api_user", methods=['GET'])
def api_user():
    # 假设每页显示10条记录
    LIMIT_PER_PAGE =int(request.args.get('limit'))
    # 假设我们要查询第3页的数据
    PAGE = int(request.args.get('page'))
    # 计算 OFFSET
    OFFSET = (PAGE - 1) * LIMIT_PER_PAGE
    # 创建数据库连接
    connection = pymysql.connect(host='192.168.153.165', user='yunwei', password='123456', database='yunwei', charset='utf8mb4',cursorclass=pymysql.cursors.DictCursor)
    try:
        with connection.cursor() as cursor:
            # 创建一个 SQL 查询，使用 LIMIT 和 OFFSET 进行翻页
            sql = "SELECT * FROM user LIMIT %s OFFSET %s"
            cursor.execute(sql, (LIMIT_PER_PAGE, OFFSET))
            # 获取所有记录
            results = cursor.fetchall()
            # 创建一个 SQL 查询，用于获取表中的行数
            sql_count = "SELECT COUNT(*) FROM user"
            cursor.execute(sql_count)
            result_count = cursor.fetchone()
            count = result_count['COUNT(*)']
            res=[]
            for row in results:
                if row['quanxian']==0:
                    quanxian='普通用户'
                else:

                    quanxian = '超级管理员'
                res.append({
                    'id':row['ID'],
                    'username':row['username'],
                    'quanxian':quanxian,

                    'at':row['at']
                })
    finally:
        # 关闭数据库连接
        connection.close()
    data={'code':0,'msg':'','count':count,'data':res}
    return jsonify(data)

@app.route("/api_msg")
def api_msg():
    total_mem,used_mem,available_memory_gb,memory_percent=neicun()
    cpu=get_cpu_percent()
    used, free,usage_percent= get_disk_usage()
    disk_data=[
        {
            'name': '已用硬盘',
            'value': used
        },
        {
            'name': '未用硬盘',
            'value': free
        }
    ]
    cpu_data=[
        {
            'name': '已用CPU',
            'value': cpu
        }, {
            'name': '未用CPU',
            'value': 100-int(cpu)
        }
    ]
    shang= random.randint(0,100)
    xia= random.randint(0,100)
    kuandai_data=[
        {
            'name': '上行',
            'value':shang
        }, {
            'name': '下行',
            'value': xia
        }
    ]
    neicun_data=[{
        'name':'已用内存',
        'value':used_mem
    },{
        'name':'未用内存',
        'value':available_memory_gb
    }]

    try:
        db = pymysql.connect(host='192.168.153.165', user='yunwei',      password='123456',database='yunwei',  charset='utf8mb4',cursorclass=pymysql.cursors.DictCursor)
        with db.cursor() as cursor:
            # 插入一条数据的 SQL 语句
            sql = """
            INSERT INTO my_table(CPU, neicun, disk, shang, xia, jiqihao)
            VALUES (%s, %s, %s, %s, %s, %s)
            """
            data = (int(cpu), memory_percent, usage_percent,shang, xia, '业务2号机')
            cursor.execute(sql, data)
            # 执行 SQL 语句
            if 100-int(cpu)>=90:
                sql = """
                          INSERT INTO warings(CPU, neicun, disk, shang, xia, jiqihao,message)
                          VALUES (%s, %s, %s, %s, %s, %s, %s)
                          """
                # 替换 %s 为你想要插入的数据
                data = (int(cpu), memory_percent, usage_percent, shang, xia, '业务2号机','CPU负载过高')
                cursor.execute(sql, data)
            db.commit()

        print("数据插入成功！")

    except pymysql.MySQLError as e:
        print(f"发生错误: {e}")

    finally:
        # 关闭连接
        db.close()
    data={
        'neicun':neicun_data,
        'cpu':cpu_data,
        'disk':disk_data,
        'kuandai':kuandai_data
    }
    return jsonify(data)

@app.route("/delete_username", methods=['GET'])
def delete_username():
    # 假设每页显示10条记录，通过设置最大单词读取数，优化数据库性能
    id =request.args.get('id')

    try:
        db = pymysql.connect(host='192.168.153.165', user='yunwei', password='123456', database='yunwei', charset='utf8mb4',cursorclass=pymysql.cursors.DictCursor)
        with db.cursor() as cursor:
            # 插入一条数据的 SQL 语句
            sql = f"DELETE FROM user WHERE id = '{id}'"

            cursor.execute(sql)
            db.commit()
        data={
            'code':0,
            'msg':'用户删除成功'
        }

    except pymysql.MySQLError as e:
        print(f"发生错误: {e}")
        data = {
            'code': 1,
            'msg': f'发生错误: {e}'
        }

    finally:
        # 关闭连接
        db.close()
    return jsonify(data)

@app.route("/api_Superadmin", methods=['GET'])
def api_Superadmin():
    # 假设每页显示10条记录
    id =request.args.get('id')
    try:
        db = pymysql.connect(host='192.168.153.165', user='yunwei', password='123456', database='yunwei', charset='utf8mb4',cursorclass=pymysql.cursors.DictCursor)
        with db.cursor() as cursor:
            # 插入一条数据的 SQL 语句
            sql = f"UPDATE user SET quanxian = 1 WHERE id = '{id}'"
            cursor.execute(sql)
            db.commit()
        data={
            'code':0,
            'msg':'用户设置成功'
        }

    except pymysql.MySQLError as e:
        data = {
            'code': 1,
            'msg': f'发生错误: {e}'
        }
    finally:
        # 关闭连接
        db.close()
    return jsonify(data)

def neicun():
    # 获取内存信息
    mem = psutil.virtual_memory()
    # 将字节转换为GB
    total_memory_gb = mem.total / (1024 ** 3)
    used_memory_gb = mem.used / (1024 ** 3)
    available_memory_gb = mem.available / (1024 ** 3)  # 空闲内存
    # 计算空间占比（已用内存占总内存的百分比）
    memory_percent = (mem.used / mem.total) * 100
    return total_memory_gb,used_memory_gb,available_memory_gb,memory_percent
def get_cpu_percent(interval=1):
    return psutil.cpu_percent(interval=interval)
def get_disk_usage(disk_path='/'):
    disk_usage = psutil.disk_usage(disk_path)
    used = disk_usage.used  # 已用空间
    free = disk_usage.free  # 未用空间
    total = disk_usage.total

    # 计算已用空间与总空间的比例（以百分比表示）
    usage_percent = (used / total) * 100
    return used, free,usage_percent

##设置URL
if __name__ == '__main__':
    app.run(debug=True, host='127.0.0.1', port='7000')
