import trade_logic
import datetime
from tools import *
from pathlib import Path
root_path = Path(__file__).parent




class auto_trade:

    def __init__(self, users, op,order_id):
        self.op = op
        self.users = users
        self.order_id = order_id
        self.log = Logger(f'{root_path}/logs','trade_port')


    def trade_main(self,user):

        user_main = trade_logic.Trade(user, self.op,self.order_id)
        user_main.trade_by_op()

    def trades(self):
        for user in self.users:
            try:
                self.trade_main(user)
            except Exception as e:
                self.log.error(sys.exc_info())
                ip_address = get_host_ip()
                send_email('auto trade error',(ip_address+'   '+user))
                if "UnboundLocalError: local variable 'user' referenced before assignment" in str(sys.exc_info):
                    pass
                else:
                    self.log.error('交易錯誤')
                continue
            print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f'))

def get_userlist(order_id):
    today = str(datetime.date.today())
    Intranat_ip = get_host_ip()
    userlist = download_data_from_db(f'select Distinct Account_name from trade_instruction where ID_Order = "{order_id}" and Intranet_IP ="{Intranat_ip}"','user_center')['Account_name'].tolist()
    return userlist

def trade_instruction_monitor(last_order: int = 0):
    '''
    交易监控

    Returns
    -------
    None.

    '''

    if last_order == 0:
        last_order_id = str(
            int(download_data_from_db(f'select max(ID_Order) from trade_instruction', 'user_center').values.tolist()[0][0]))
    elif last_order == 1:
        last_order_id = '-1'

    while True:
        order_id = str(
            int(download_data_from_db(f'select max(ID_Order) from trade_instruction','user_center').values.tolist()[0][0]))
        if order_id == last_order_id:
            time.sleep(10)
            pass
        elif int(order_id) - int(last_order_id) > 1:
            order_id = str(int(last_order_id)+1)
            ip = get_host_ip()
            message = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + '    '+ str(ip) +'    ' + order_id + '    begin trade'
            # send_email('自动交易提醒', message)
            time.sleep(10)
            op = str(download_data_from_db(f'select Trade_Type from trade_instruction where ID_Order="{order_id}"', 'user_center').values.tolist()[0][0])
            userlist = get_userlist(order_id)
            trade_main = auto_trade(userlist,op,order_id)
            trade_main.trades()
            last_order_id = order_id
        elif int(order_id) - int(last_order_id) == 1:
            ip = get_host_ip()
            message = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + '    ' + str(
                ip) + '    ' + order_id + '    begin trade'
            # send_email('自动交易提醒', message)
            time.sleep(10)
            op = str(download_data_from_db(f'select Trade_Type from trade_instruction where ID_Order="{order_id}"',
                                 'user_center').values.tolist()[0][0])
            userlist = get_userlist(order_id)
            trade_main = auto_trade(userlist, op,order_id)
            trade_main.trades()
            last_order_id = order_id

        else:
            pass


def all_check():
    instruction = pd.read_sql(
        fr'select Account_Number Account_name,Ticker,Buy_Or_Sell Operate,Shares Number_transactions from trade_retail.trade_instruction_stock_retail where Trade_Date like "{today}%%"',
        engine_tencent)
    instruction['Number_transactions'] = instruction['Number_transactions'].apply(abs)
    # instruction = instruction[~instruction['Account_name'].isin(userlist)]
    # data1 = instruction.drop_duplicates()
    # instruction['trade_money'] = instruction['Price'] * instruction['Number_transactions']
    instruction_new = instruction.groupby(['Ticker', 'Operate', 'Account_name']).sum()
    # instruction_new['Average_price'] = instruction_new['trade_money'] / instruction_new['Number_transactions']
    instruction_new.reset_index(inplace=True)
    trade_user_list = get_save_list()

    instruction_new = instruction_new[instruction_new['Account_name'].isin(trade_user_list)]


    data = pd.read_sql(
        fr'select * from auto_update_web_strategy.daily_transaction_record_check where As_Of_Date = "{today}"',
        engine)
    # data['trade_money'] = data['Average_price'] * data['Number_transactions']
    new_data1 = data.groupby(['Ticker', 'Operate', 'Account_name']).sum()
    # new_data1['Average_price'] = new_data1['trade_money'] / new_data1['Number_transactions']
    new_data1.reset_index(inplace=True)
    new_data1['As_Of_Date'] = datetime.date.today()
    # del new_data1['trade_money']

    new_data1['Operate'] = new_data1['Operate'].apply(lambda x: 1 if x == '买' else -1)
    c = pd.merge(instruction_new, new_data1, how='left', on=['Account_name', 'Ticker', 'Operate'])
    # c['operate_different'] = c['Operate_x'] - c['Operate_y']
    c['number_different'] = c['Number_transactions_x'] - c['Number_transactions_y']
    # del c['Average_price']

    new = c.rename(columns={
        'Number_transactions_x': 'Number_transactions',
        'Number_transactions_y': 'Trade_Number_transactions'})

    all_dataframe = new[
        ['As_Of_Date', 'Account_name', 'Ticker', 'Operate', 'Number_transactions',
         'Trade_Number_transactions', 'number_different']]

    # all_dataframe = pd.concat(all_dataframe_chack)
    print('8888888', all_dataframe)
    error = all_dataframe.loc[(all_dataframe['number_different'] != 0)]
    print('error',error)
    ip = trade_logic.get_host_ip()
    if len(error) == 0:
        send_email(subject='智投交易check',message=ip + ' 没有错误')
    else:
        file = 'C:\\Users\\Administrator\\Desktop\\check.html'
        error.to_html(file)
        f = open(file, 'rb')
        mail_body = f.read()
        f.close()
        send_email(subject='智投交易check',message=ip, file_path=file)

def get_save_list():
    trading_users = pd.read_sql(
        fr'select * from user_center.trading_users where update_time = (select max(update_time) from user_center.trading_users) and Broker ="华泰证券"  or Broker = "长城证券" or Broker = "国泰君安"',
        engine)
    # print(trading_users)
    user_list = trading_users['Account_Name'].tolist()
    trade_list = pd.read_sql(fr'select * from user_center.trade_instruction where As_Of_Date like "{today}%%"', engine)
    trade_list_new = trade_list[~trade_list['Account_Name'].isin(user_list)]
    trade_user_list = list(set(trade_list_new['Account_Name']))
    return trade_user_list

if __name__ == '__main__':
    today = datetime.date.today()
    engine_tencent = create_engine(
        'mysql+pymysql://ainvest_luming:lm18242094506@bj-cdb-3gfxha84.sql.tencentcdb.com:59970/')
    engine = create_engine(
        'mysql+pymysql://cn_ainvest_db:cn_ainvest_sd3a1@rm-2zewagytttzk6f24xno.mysql.rds.aliyuncs.com:3306/')

    # userlist = get_save_list()
    #东吴证券用户
    # userlist = ['18207551053','13241235368']
    # userlist = [ '13333447911','17836359888']
    # userlist = [ '17836359888']
    # userlist = [ '15259202109','15355324922']1863619181

    # userlist = [ '18810394120','15299080760']



    # userlist = ['13880392643','13157750940']

    #
    # userlist = ['13708491492','138187729

    userlist = [ '13017155718', '13066780066', '13157750940', '13161021130', '13397720155', '13401005719', '13401019175', '13466839727', '13719786764', '13729600058', '13799978997', '13812913261', '13880392643', '13906885715', '13976670583', '15128806638', '15632751289', '15652609813', '17801018786', '18817026786', '18913869900']


    print(userlist)
    for user in userlist:
        SCRIPT_PATH = os.path.dirname(os.path.realpath(__file__))
        os.chdir(SCRIPT_PATH)
        # user_main = auto_trade(user, 'save_trades_check',0)
        user_main = auto_trade(user, 'save_all', 0)
        # user_main = auto_trade(user, 'save_balance_position', 0)
        # user_main = auto_trade(user, 'reset_mac_ip', 0)
        # user_main = auto_trade(user, 'save_deliver_order', 0)

        user_main.trade_main(user)

    # all_check()


