import subprocess
import schedule
import time
from datetime import datetime

#   jerome：增加akshare库
import akshare as ak

#   jerome:增加下列库用于爬虫获取主力连续代码
import pandas as pd
import requests
from bs4 import BeautifulSoup
import csv
import re
import os
#   jerome:增加文件名修改工作
import shutil

#   Jerome:需要设置的参数
new_directory = r"D:/Git_Nas/Quant_Code/999.账户相关/simnow_trader" #设置运行目录为程序所在目录new_directory
# 定义要启动的文件
files_to_run = ['dingdanliu_nb.py']
#   定义生成的保证金、手续费csv文件
fees_filepath = r'./futures_fees_info.csv'
contracts_filepath = r'./main_contacts.csv'
contracts_yd_filepath = r'./main_contacts_yd.csv'
exchange_filepath = r'./exchange_for_months.csv'



# jerome:修改运行目录
# 获取当前工作目录
current_directory = os.getcwd()
print("当前工作目录：", current_directory)
# 设置新的工作目录
os.chdir(new_directory) 
# 验证新的工作目录
updated_directory = os.getcwd()
print("已更改为新的工作目录：", updated_directory)

def run_scripts():
    print("启动程序...")
    for file in files_to_run:
        time.sleep(1)
        # 使用subprocess模块运行命令
        subprocess.Popen(['start', 'cmd', '/k', 'python', file], shell=True)
        print(file)
    print(datetime.now(),'程序重新启动完成，等待明天关闭重启')

def close_scripts():
    print("关闭程序...")
    # 通过创建一个包含关闭指定窗口命令的批处理文件来关闭CMD窗口
    def close_specific_cmd_window(cmd_window_title):
        with open("close_cmd_window.bat", "w") as batch_file:
            batch_file.write(f'@echo off\nfor /f "tokens=2 delims=," %%a in (\'tasklist /v /fo csv ^| findstr /i "{cmd_window_title}"\') do taskkill /pid %%~a')

        # 运行批处理文件
        subprocess.run("close_cmd_window.bat", shell=True)
        

    # 循环关闭所有脚本对应的CMD窗口
    for title in files_to_run:
        close_specific_cmd_window(title)
    print(datetime.now(),'已关闭程序，等待重新运行程序')

#   jerome:增加使用akshare获取期货的手续费等数据，并保存到对应目录下
def get_futures_fees_info():
    futures_fees_info_df = ak.futures_fees_info() 
    futures_fees_info_df[['品种代码', '交割月份']] = futures_fees_info_df['合约代码'].apply(lambda x: pd.Series(split_alpha_numeric(x)))
    futures_fees_info_df.to_csv(fees_filepath, index=False)
    print("期货保证金、手续费csv文件已经保存!")

def get_main_contacts():
    url = "https://www.9qihuo.com/hangqing"

    # 发送GET请求，禁用SSL验证
    response = requests.get(url, verify=False)
    response.encoding = 'utf-8'  # 确保编码正确

    # 解析网页内容
    soup = BeautifulSoup(response.text, 'lxml')

    # 找到目标表格
    table = soup.find('table', {'id': 'tblhangqinglist'})

    # 初始化CSV文件
    with open(r'./tmp_main_contacts.csv', mode='w', newline='', encoding='utf-8') as file:
        writer = csv.writer(file)
        
        # 遍历表格的所有行
        for row in table.find_all('tr'):
            # 获取每一行的所有单元格
            cols = row.find_all(['th', 'td'])
            # 提取文本内容并写入CSV文件
            writer.writerow([col.text.strip() for col in cols])

    df = pd.read_csv(r'./tmp_main_contacts.csv',encoding='utf-8')
    df['交易品种'] = df['合约'].str.split(r'[()]', n=1, expand=True)[0]
    df['主连代码'] = df['合约'].str.split(r'[()]', n=2, expand=True)[1]

    df[['品种代码', '交割月份']] = df['主连代码'].apply(lambda x: pd.Series(split_alpha_numeric(x)))
    if os.path.exists(contracts_filepath):
        os.remove(contracts_filepath)
        print("原有今日期货主连csv文件已经删除!")

    df.to_csv(r'./main_contacts.csv')
    os.remove(r'./tmp_main_contacts.csv')
    print("今日期货主连csv文件已经保存!")

#   拆分字母和数字的函数
def split_alpha_numeric(s):
    match = re.match(r"([a-zA-Z]+)([0-9]+)", s)
    if match:
        return match.groups()
    else:
        return (s, None)  # 如果没有匹配，返回原始字符串和None
    
def rename_file():
    # source_file = r'./main_contacts.csv'
    # target_file = r'./main_contacts_yd.csv'
    
    # 检查是否存在 main_contacts_yd.csv，如果存在则删除
    if os.path.exists(contracts_yd_filepath):
        os.remove(contracts_yd_filepath)
        print("原有昨日期货主连csv文件已经删除!")

    shutil.copy(contracts_filepath, contracts_yd_filepath)
    # print(f"{contracts_filepath} has been copied to {contracts_yd_filepath}")
    print("今日期货主连csv文件已经修改为昨日主连csv文件!")
    
    # # 重命名文件
    # if os.path.exists(source_file):
    #     os.rename(source_file, target_file)
    #     print(f'Renamed {source_file} to {target_file}')
    # else:
    #     print(f'{source_file} does not exist')

def exchange_for_months():
    td_df = pd.read_csv(contracts_filepath, header = 0, usecols= [16, 17],names=['主连代码', '品种代码'])
    if not os.path.exists(contracts_yd_filepath):       
        shutil.copy(contracts_filepath, contracts_yd_filepath)
        print("昨日主连csv文件不存在,已经使用今日主连csv替代!")
    yd_df = pd.read_csv(contracts_yd_filepath, header = 0, usecols= [16, 17],names=['主连代码', '品种代码']) 

    # 合并两个 DataFrame
    merged_df = pd.merge(td_df, yd_df, on='品种代码', suffixes=('_今日', '_昨日'))
    # 检查 '主连代码' 是否相等
    merged_df['主连代码_相等'] = merged_df['主连代码_今日'] == merged_df['主连代码_昨日']

    if os.path.exists(exchange_filepath):
        os.remove(exchange_filepath)
        print("原有换月对比csv文件已经删除!")
    merged_df.to_csv(exchange_filepath)
    print("换月对比csv文件已经生成!")

#   程序时间建议(以每晚9点交易为最开始时间）：1生成费率表和今日主连文件;2生成换月对比文件；3、启动晚间交易程序并登录账户；
#   4关闭晚间交易程序；5启动白天交易程序并登录账户；6生成昨日主连文件；7关闭白天交易程序。
# 设置定时任务，关闭程序
schedule.every().day.at("15:10").do(close_scripts)
schedule.every().day.at("03:00").do(close_scripts)

# 设置定时任务，启动程序
schedule.every().day.at("08:55").do(run_scripts)
# schedule.every().day.at("20:55").do(run_scripts)
schedule.every().day.at("21:52").do(run_scripts)

# 设置定时任务，生成费率表文件和今日主连文件
# schedule.every().day.at("20:53").do(get_futures_fees_info)
# schedule.every().day.at("20:53").do(get_main_contacts)
schedule.every().day.at("21:51").do(get_futures_fees_info)
schedule.every().day.at("21:51").do(get_main_contacts)

# 设置定时任务，生成换月对比文件
# schedule.every().day.at("20:55").do(exchange_for_months)
schedule.every().day.at("21:52").do(exchange_for_months)

# 设置定时任务，安排任务每天15:30执行, 生成昨日主连文件
schedule.every().day.at("15:05").do(rename_file)

# 保持脚本运行，等待定时任务触发
while True:
    schedule.run_pending()
    time.sleep(1)
