if 1:
    from   oneclass.onedb import Onedb
    from   oneclass.kclass import Kdata
    from   oneclass.oneqs import Oneqs
    import os,math,sys,time,re,json,datetime,requests,warnings,logging,xlrd,traceback
    import numpy as np
    import pandas as pd
    import tushare as ts
    from   sqlalchemy import create_engine
    import sqlalchemy  #初始化数据库连接，使用pymysql模块
    import pymysql
    import multiprocessing as mp
if 1:
    ts.set_token('8f6e67ec8a48922bbb531b95687625d99ee263940a07561ae95f4648')  # Tushare Pro
    pd.set_option('mode.chained_assignment', None)
    warnings.filterwarnings("ignore")
    durtime,durting1,FocusPeriod,uihandle,plock,showtype,havelistseq=0.001,0.5,0,0,0,1,1
    stockcode,mysqlhost="300027.SS","119.45.95.223"
    xgresult,qsresult,allstocklist=pd.DataFrame(),pd.DataFrame(),pd.DataFrame()
def combine_choose():
    onedb=Onedb()
    df = pd.read_csv(r"./csv/2022.csv")
    df['stockcode'] = df['stockcode'].map(lambda x: format_code(x[1:-1]))
    df=df.drop_duplicates(['stockcode'])
    df.rename(columns={'name':'stockname'},inplace=True)
    df['time']="2022"
    df['reason']="月线"
    onedb.into_table(df,"tmpch","stockcode",9)
    print(df)
def help_info():
    print("--main: main()")
    print("--xg2022:xg_2022()")
    print("--xghavelist:xg_havelist()")
    print("--xgselct: xg_select()")
    print("--hqall:get_hq_all()")
    print("--autotrade:get_autotrade()")
def revise_choosed():
    onedb=Onedb()
    #get former choosed db
    formerdb=onedb.execute_sqlnew("select * from choosed")

    print("formerdb",formerdb)
    #query to find new stocks
    #df=onedb.call_mysql_procedure("choosealls")
    #df.columns=['stockcode','stockname','reason']
    df=onedb.execute_sqlnew("call choosealls")
    df.rename(columns={'cm':'reason'},inplace=True)
    tmptoday=datetime.datetime.now().strftime('%Y-%m-%d')
    df['time']=tmptoday
    print("querydb",df)
    #combine and del duplication
    formerdb=formerdb.append(df,ignore_index=True)
    revisedb=formerdb.drop_duplicates(subset=['stockcode','reason'],keep='first',ignore_index=True)
    '''
    同一个原因在同一天出现 => 被删除重复
    同一个原因在不同天出殃 => 保留??? 
    是否需要按信号的周期和间隔长度来判断去留, 保留正确的信号
    是否需要保留选股时的趋势或信号, 用信号来判断是否是同一次信号
    '''
    print("reviewd db",revisedb)
    #update choosed db
    onedb.execute_sqlnew("delete from choosed")  #delete or drop table
    onedb.into_table(revisedb,"choosed","stockcode",9)
def format_code(scode):
    if len(scode)==9: return scode
    if scode[0:1]=="6":
        return scode+".SH"
    elif scode[0:1]=="8" or scode[0:1]=="4": 
        return scode+".BJ"
    else:
        return scode+".SZ"
def main():
    global stockcode,showtype,havelistseq,allstocklist
    while True:
        k=Kdata(stockcode,showtype,havelistseq)
        #k.get_div_fromdb()
        k.show(showtype)
        old_stockcode=stockcode
        stockcode=input("New stockcode<s;1;3.79;5000>:")
        #"Q" = Quit
        if stockcode=="q":
            print("\033[0;31;40m\t ~see u!~ \033[0m")
            break
        #"A" = all List
        if stockcode=='a':
            showtype = 1
        #"NN" = show selected stock
        try:
            if int(stockcode)>=1 and int(stockcode)<=300:
                showtype=2
                havelistseq=int(stockcode)
        except:
            pass
        #"XXXXXX.SZ" = show keyin stock
        if len(stockcode)==6:
            showtype=3
        if len(stockcode)==9:
            old_stockcode=stockcode
            showtype=3
        if showtype==3 and len(stockcode)==0:
            stockcode=old_stockcode
        #"s;1;3.79;5000" = sell stock by SeqNo.
        #"b;1;3.55;5000" = sell stock by SeqNo.
        #"s;300027;3.79;5000"=sell stock by stockcode
        if stockcode[0:1]=="s" or stockcode[0:1]=="S":
            pdbszc=pd.DataFrame() 
            sinfo=stockcode.split(";")
            tmpstockcode=sinfo[1]
            if len(tmpstockcode)<=3:
                scode=k.havelist['code'][int(sinfo[1])]
                sname=k.havelist['name'][int(sinfo[1])]
            else:
                scode=tmpstockcode
                #sname="get sname from stocklist"
                for key,tmpstock in allstocklist.iterrows():
                    if tmpstock.symbol==tmpstockcode:
                        #print("tmpstock",tmpstock)
                        sname=tmpstock['name']
                        #print(allstocklist)
                        #_=input(f"scode:{scode}, sname:{sname}")
                        break
            sprice=float(sinfo[2])
            sqty=float(sinfo[3])
            samt=sprice*sqty/10000
            samt=round(samt,2)
            sreason=sinfo[4]
            sconfirm=input(f"[---SSS---{samt}W---]:{scode}:{sname}:{sprice}:{sqty} (Y/N)")
            if sconfirm.upper()=="Y":
                print("[---SSS---]")
                timestr=time.strftime("%Y-%m-%d %H:%M:%S")
                tmpbszc={"stockcode":scode,"BSZ":"S","price":sprice,"qty":sqty,"time":timestr,\
                         "optime":"asap","loopornot":"no","applyed":"no","done":"no","stockname":sname,\
                         "reason":sreason}
                pdbszc=pdbszc.append(tmpbszc,ignore_index=True)
                k=Kdata(stockcode,showtype,havelistseq)
                self.onedb.into_table(pdbszc,"autotradelist","stockcode",6)
                print(pdbszc)
            stockcode=old_stockcode

        if stockcode[0:1]=="b" or stockcode[0:1]=="B":
            pdbszc=pd.DataFrame() 
            #sinfo=stockcode.split(";")
            #bcode=k.havelist['code'][int(sinfo[1])]
            #bname=k.havelist['name'][int(sinfo[1])]
            sinfo=stockcode.split(";")
            tmpstockcode=sinfo[1]
            if len(tmpstockcode)<=3:
                bcode=k.havelist['code'][int(sinfo[1])]
                bname=k.havelist['name'][int(sinfo[1])]
            else:
                bcode=tmpstockcode
                #sname="get sname from stocklist"
                for key,tmpstock in allstocklist.iterrows():
                    if tmpstock.symbol==tmpstockcode:
                        #print("tmpstock",tmpstock)
                        bname=tmpstock['name']
                        #print(allstocklist)
                        #_=input(f"bcode:{bcode}, bname:{bname}")
                        break
            #print("sinfo",sinfo)
            bprice=float(sinfo[2])
            bqty=float(sinfo[3])
            bamt=bprice*bqty/10000
            bamt=round(bamt,2)
            breason=sinfo[4]
            bconfirm=input(f"[---SSS---{bamt}W---]:{bcode}:{bname}:{bprice}:{bqty} (Y/N)")
            if bconfirm.upper()=="Y":
                print("[---SSS---]")
                timestr=time.strftime("%Y-%m-%d %H:%M:%S")
                tmpbszc={"stockcode":bcode,"BSZ":"B","price":bprice,"qty":bqty,"time":timestr,\
                         "optime":"asap","loopornot":"no","applyed":"no","done":"no","stockname":bname,\
                         "reason":breason}
                pdbszc=pdbszc.append(tmpbszc,ignore_index=True)
                k=Kdata(stockcode,showtype,havelistseq)
                onedb=Onedb()
                onedb.into_table(pdbszc,"autotradelist","stockcode",6)
                print(pdbszc)
            stockcode=old_stockcode
def xg_select():
    newlist=pd.DataFrame()
    stocklist = pd.read_csv(r"./tmpout/2022.csv",index_col=0)
    stocklist=stocklist[['stockcode','month','week','day','spacem','profitm','spacew','profitw','spaced','profitd','name']]
    stocklist=stocklist.fillna("")    #从message计算的源程序解决了self.QS[period]出现NaN的问题
    for key,stock in stocklist.iterrows():
        if "-1abc" in stock.month and "-1abc" in stock.week:
            newlist=newlist.append(stock)
    print(newlist)
def get_autotrade():
    autotrade=pd.DataFrame()
    autotrade = pd.read_csv(r"./csv/autotrade.csv",index_col=0)
    autotrade=autotrade.fillna("")
    autotrade.reset_index(drop=False, inplace=True)  
    for i in range(autotrade.shape[0]):
        autotrade['stockcode'][i]=autotrade['stockcode'][i][1:7]
    k=Kdata(stockcode,showtype,havelistseq)
    #k.del_table("autotradelist")
    #k.into_table(autotrade,"autotradelist","stockcode",6)
    onedb=Onedb()
    sql="DELETE FROM autotradelist WHERE loopornot<>'no'"
    onedb.execute_sql(sql)
    onedb.into_table(autotrade,"autotradelist","stockcode",6)
    print(autotrade)
if __name__=="__main__":
    if sys.argv[1] == "main":  
        k=Kdata(stockcode,showtype,havelistseq)
        #k.get_div_fromdb()
        onedb=Onedb()
        allstocklist=onedb.From_table("select symbol,name,area from tusharestocklist") 
        main()
    if sys.argv[1] == "xg2022":                     #读取csv/2022.csv计算后输出到tmpout/2022result.csv
        k=Kdata(stockcode,showtype,havelistseq)
        try:
            if sys.argv[2]=="1":
                k.get_div_fromdb()
        except:
            pass
        k.xg_2022_mp()
    if sys.argv[1] == "xgall":                     #读取csv/2022.csv计算后输出到tmpout/2022result.csv
        k=Kdata(stockcode,showtype,havelistseq)
        k.get_div_fromdb()
        k.xg_all_mp()
    if sys.argv[1] == "xghavelist":
        k=Kdata(stockcode,showtype,havelistseq)
        k.get_div_fromdb()
        k.get_havelist()
        k.xg_havelist()                             #从db读取havelist,依次显示分析结果
    if sys.argv[1] == "xgselect": 
        xg_select()       #从/tmpout/2022result.csv中查询满足条件的股票
    if sys.argv[1] == "hqall":                      #读取所有股票行情
        k=Kdata(stockcode,showtype,havelistseq)
        k.get_hq_all()
    if sys.argv[1] == "autotrade":                  #执行每日的定时常规工作 
        get_autotrade()                             #读csv/autotrade.csv并放到autotradelist
    if sys.argv[1] == "?":
        help_info()
    if sys.argv[1] == "choose":
        '''记录所有选股'''
        revise_choosed()
    if sys.argv[1] == "combine":
        '''临时合并2022和2023股票'''
        combine_choose()

    print(datetime.datetime.now().strftime('%Y-%m-%d-%H:%M:%S'))
