import datetime
import os
import re
import time
import win32gui

import paramiko  # 导入paramiko
import pyautogui
import pymysql
import pyperclip
import win32con

db = pymysql.connect(host='localhost', port=3306, user='root', password='123456', database='filetime',
                     charset='utf8mb4')
cursor = db.cursor()


def insert_data(path, time):
    # 如果数据库不存在文件,则创建一条记录包括文件绝对路径和修改时间
    ins = 'insert into file (path, modifytime) values (%s, %s)'
    cursor.execute(ins, (path, time))
    db.commit()
    # cursor.close()
    # db.close()


def text(word):
    # 写入修改事件
    ins = 'insert into text (content) values (%s)'
    cursor.execute(ins, "file_move事件" + word)
    db.commit()
    # cursor.close()
    # db.close()


def select_data():
    # 查询file表文件名修改时间
    sql = 'select  path, modifytime from file '
    # print(sql)
    sql = cursor.execute(sql)
    # print(sql)
    all_data = cursor.fetchmany(sql)  # 查询的个数
    print(all_data)
    # for i in all_data:
    #      print(i[0], i[1])
    return all_data


def sql_update(path, modifytime):
    # 修改数据库file表的修改过文件时间名字的时间
    try:
        ins = 'UPDATE  file SET modifytime = "{}" WHERE path = %s'.format(modifytime)

        cursor.execute(ins, path)

        db.commit()
        # print(ins)
        # cursor.close()
        # db.close()
    except Exception as result:
        print("sql_update错误", result)


def file_manage(cmdList):
    # 第一种ssh连接执行指令方式,把文件发送到centos上,并修改数据库文件时间
    transport = paramiko.Transport((hostname, 22))
    transport.connect(username=username, password=password)

    sftp = paramiko.SFTPClient.from_transport(transport)

    # 遍历cmd列表里面文件一个一个上传
    for cmd in cmdList:
        print(cmd, '/home' + cmd[0].replace("\\", "/"))
        sftp.put(win_path + cmd[0], '/home' + cmd[0].replace("\\", "/"))

        # sftp.get('/home/blog/media' + cmd, 'C:/Users/yys53/OneDrive/python/blog/media' + cmd)
        sql_update(cmd[0], cmd[1])  # 修改时间
        text('把win10文件:C:/Users/yys53/OneDrive/python' + cmd[0] + '/home' + cmd[0])
        if cmd:
            print("py文件更新需要reload")
            reload.append(cmd)

    transport.close()


def compare_tme():
    lis = []

    data = select_data()
    for i in half_file_list:
        for root, dirs, files in os.walk(win_path + '\\blog\\' + i):
            # (win_path + '\\blog\\' + iroots)代表需要遍历的根文件夹
            # root表示正在遍历的文件夹的名字(根 / 子)
            # dirs记录正在遍历的文件夹下的子文件夹集合
            # files记录正在遍历的文件夹中的文件集合
            for file in files:
                lis.append(root + file)
                # print(root[-1])
                if root[-1] == '\\':
                    pass
                else:
                    root = root + "\\"
                # print(r_list)
                f = root + file
                # print(root+file)
                mtime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(os.path.getmtime(f)))  # 修改时间
                # ctime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(os.path.getctime(f)))   # 创建时间
                pattern = re.compile('python(\\Wblog.*)', re.S)  # 获取的要带括号
                r_list = pattern.findall(root)

                for i in data:
                    # i[0]为数据库一半路径+文件名,i[1]为最后修改时间
                    # print(i[0], )
                    # 判断文件夹匹配
                    if r_list[0] + file == i[0]:
                        # print(r_list[0] + file, i[0])
                        # 如果文件夹相等,比一下时间
                        if i[1] == mtime:
                            pass
                            # print("满足")
                        else:
                            print("时间不满足%s,当前时间%s,最近修改时间%s" % (r_list[0] + file, i[1], mtime))
                            # 不满足做的事
                            # 1.移动文件
                            lis2.append((r_list[0] + file, mtime))

                            print(r_list[0])

                            time.sleep(0.5)
                        break
                else:
                    print("没有此文件:%s,需要插入file表中" % r_list[0] + file)

                    # # 插入file表
                    lis2.append((r_list[0] + file, mtime))
                    insert_data(r_list[0] + file, mtime)

                # print("文件路径:%s, 最新修改 : %s" % (file_dir, mtime))


def input(text, hwnd):
    # 字典字母的对应编号,根据遍历账号密码,得到对应整数型键,然后由WM_IME_CHAR得到字母和数字
    dic = {32: ' ', 33: '!', 34: '"', 35: '#', 36: '$', 37: '%', 38: '&', 39: "'", 40: '(', 41: ')', 42: '*', 43: '+',
           44: ',',
           45: '-', 46: '.', 47: '/', 48: '0', 49: '1', 50: '2', 51: '3', 52: '4', 53: '5', 54: '6', 55: '7',
           56: '8',
           57: '9', 58: ':', 59: ';', 60: '<', 61: '=', 62: '>', 63: '?', 64: '@', 65: 'A', 66: 'B', 67: 'C',
           68: 'D',
           69: 'E', 70: 'F', 71: 'G', 72: 'H', 73: 'I', 74: 'J', 75: 'K', 76: 'L', 77: 'M', 78: 'N', 79: 'O',
           80: 'P',
           81: 'Q', 82: 'R', 83: 'S', 84: 'T', 85: 'U', 86: 'V', 87: 'W', 88: 'X', 89: 'Y', 90: 'Z', 91: '[',
           92: '\\',
           93: ']', 94: '^', 95: '_', 96: '`', 97: 'a', 98: 'b', 99: 'c', 100: 'd', 101: 'e', 102: 'f', 103: 'g',
           104: 'h',
           105: 'i', 106: 'j', 107: 'k', 108: 'l', 109: 'm', 110: 'n', 111: 'o', 112: 'p', 113: 'q', 114: 'r',
           115: 's',
           116: 't', 117: 'u', 118: 'v', 119: 'w', 120: 'x', 121: 'y', 122: 'z', 123: '{', 124: '|', 125: '}',
           126: '~'}

    print("input程序 self.hwnd=%s" % hwnd)
    for i in text:
        value = int([k for k, v in dic.items() if v == i][0])
        win32gui.SendMessage(hwnd, win32con.WM_IME_CHAR, value)


def get_hwnd():
    """获取句柄进行后台cmd输入和回车,如果没有打开cmd就前台就行搜索框打开cmd,在进行输入,不能直接用路径打开cmd"""
    main_hwnd = win32gui.FindWindow(None, "管理员: 命令提示符")
    print(main_hwnd)
    if main_hwnd:
        # ssh 空格+ 用户名@ip
        input("ssh " + username + "@" + hostname, main_hwnd)
        win32gui.PostMessage(main_hwnd, win32con.WM_KEYDOWN, win32con.VK_RETURN, 0)
        time.sleep(1)
        input(password, main_hwnd)
        win32gui.PostMessage(main_hwnd, win32con.WM_KEYDOWN, win32con.VK_RETURN, 0)
        time.sleep(0.5)
        input("supervisorctl reload", main_hwnd)
        win32gui.PostMessage(main_hwnd, win32con.WM_KEYDOWN, win32con.VK_RETURN, 0)
        time.sleep(0.5)
        input("exit", main_hwnd)
        win32gui.PostMessage(main_hwnd, win32con.WM_KEYDOWN, win32con.VK_RETURN, 0)
        time.sleep(0.5)
        input("exit", main_hwnd)
        win32gui.PostMessage(main_hwnd, win32con.WM_KEYDOWN, win32con.VK_RETURN, 0)

    else:
        print("没打开cmd,需要打开cmd")
        pyautogui.hotkey('win', 'q')  # 搜索
        time.sleep(0.5)
        pyperclip.copy("cmd")
        time.sleep(0.5)
        pyautogui.hotkey('ctrl', 'v')  # 再粘贴
        time.sleep(0.5)
        pyautogui.hotkey('enter')  # 再确定
        time.sleep(1)
        get_hwnd()


if __name__ == '__main__':
    lis2 = []
    reload = []
    win_path = 'C:\\Users\\yys53\\OneDrive\\python'
    hostname = ip或域名
    username = ssh用户名
    password = ssh密码
    # 需要同步blog下的文件相对路径
    half_file_list = ["blog\\", 'home\\', 'templates\\', 'static\\', 'users\\']

    compare_tme()
    print(lis2)
    if len(lis2) > 0:
        # 获取所有需要上传列表相对路径,一次性上传完
        file_manage(lis2)

    if reload:
        print("有文件上传CentOs需要重启supervisor")
        # 重启supervisor
        get_hwnd()