import time

from search import *
from search.abSearch import requestsend

def fileData():
    fcolums=['id','query','expect_cid3','commit']
    filename=os.path.join(data_file_path,'Top1000关键词测评.xlsx')
    df=readRenameColums(filename,fcolums)
    df['commit']=df['commit'].fillna(9999)
    return df

def compareResult():
    '''
    commit=1，表示品牌，brandid；commit=9999，表示cid3，commit=2，表示跳过，默认不统计
    :return:
    '''
    df=fileData()
    temp_score=[]
    for i in df.itertuples():
        print(i)
        id=i.__getattribute__('Index')
        query_context=i.__getattribute__('query')
        expect_cid3=str(i.__getattribute__('expect_cid3'))
        commit=i.__getattribute__('commit')
        temp_expect_cid3=expect_cid3.split(',') if expect_cid3 else []
        uuid,deviceid=genUuidDeviceid()
        # uuid,deviceid,searchContent,selectedActivitie,page=1,searchtype='txt',env='pro'
        *info,cid3s,brandnames=\
            requestsend(uuid,deviceid,query_context,selectedActivitie=1,page=1,env='pro')
        if commit=='1' or commit==1:
            tempbrandnames=brandnames[:5]
            score=[1 for i in  tempbrandnames  if i in temp_expect_cid3 ]
            temp_score.append(score)
            df.loc[id,'score']=sum(score)
            df.loc[id,'final_score']=round(sum(score)/len(tempbrandnames),2)
            try:
                df.loc[id,'actual_cid3']=','.join(brandnames[:5])
            except:
                #print(brandnames,type(brandnames))
                brandnames=[str(i) for i in brandnames]
                df.loc[id,'actual_cid3']=','.join(brandnames)
        elif commit=='9999' or commit==9999:
            tempcid3s=cid3s[:5]
            score=[1 for i in tempcid3s  if i in temp_expect_cid3 ]
            print('比对得分',score)
            #print(score,id,type(id),df.loc(id))
            #temp_score.append(score)
            df.loc[id,'score']=sum(score)
            df.loc[id,'final_score']=round(sum(score)/len(tempcid3s),2)
            df.loc[id,'actual_cid3']=','.join(cid3s[:5])
            #df.iloc[0,'score']=sum(score)
            #i.__setattr__('score',sum(score))
        else:
            df.loc[id,'score']=0
            df.loc[id,'final_score']=0
            df.loc[id,'actual_cid3']=0

        #df['score']=temp_score

    return df


def saveResult():
    df=compareResult()
    reportname=filePath(file_path,'compareResult')
    #df['skunos']=df['skunos'].astype('string')
    df.to_excel(reportname,index=0,encoding = 'utf-8')

def anasfile(filename=None):
    result=[]
    filename=filename if filename \
        else os.popen("cd {};ls -t |grep -v 'init' |head -1".format(file_path)).read(100)
    filename_path=os.path.join(file_path,filename.strip())
    print('解析文件名：',filename_path)
    df=readFile(filename_path)
    temp_df=df[(df['commit']!=2) &(~ df['expect_cid3'].isna()) &(~ df['expect_cid3'].isna())]
    #temp_df['expect_cid3_len']=(temp_df['expect_cid3'].astype(str)+',').str.split(',')
    print('有效数据总数,',temp_df.shape[0])
    #temp_df['final_score']=temp_df['score']/(temp_df['expect_cid3_len'].apply(len)-1)
    print("准确率",temp_df['final_score'].mean())
    print('通过率',temp_df[temp_df['final_score']>0.6]['final_score'].mean())
    print('无效数据总数',df[(df['commit']==2) | (df['commit']=='2')].shape[0])
    print('实际结果和预期结果都为空的总数',df[(df['commit']!=2) & ((df['expect_cid3'].isna()) | ( df['expect_cid3'].isna()))].shape[0])
    #round(df['score']/df['expect_cid3'].str.split(','),2)

    #print(temp_df['final_score'].head(2))

    # reportname=filePath(file_path,'final_result')
    # #df['skunos']=df['skunos'].astype('string')
    # temp_df.to_excel(reportname,index=0,encoding = 'utf-8')




if __name__ == '__main__':
    print(saveResult())
    time.sleep(1)
    print('1112',anasfile())