import requests

from recommend import *

def preconditions(content,uuid,gid):
    from search.abSearch import requestsend
    try:
        _, spu_nos,*_=requestsend(uuid,gid,content,selectedActivitie=1,page=1,searchtype='txt',env='test')
        temp_spu_nos=spu_nos.split(',')
        if len(temp_spu_nos)>5:
            return 0
        return temp_spu_nos
    except:
        return 0

def diwenci(uuid=None,gid=None):
    url=nearline_url_aliyun+"/recommend/searchShadingWords"
    body={
        "position":1,
        "userUuid":uuid or "",
        "deviceId":gid or ""
    }
    temp=requests.get(url,params=body)
    word=jsonpath.jsonpath(temp.json(),'$..word')
    return word

def searchTopic(content):
    #uuid,gid=genUuidDeviceid()
    uuid=""
    gid="4205df9318c69521"
    print("uuid:",uuid,"====>","gid",gid)
    #diwenci_result=diwenci(uuid,gid)
    result_skus=preconditions(content,uuid,gid)
    diwenci_result=diwenci(uuid,gid)
    print("搜索结果的skus,",result_skus)
    #query+similar_query
    similar_temp=[]
    similar_change_sql=recommend_hot_query_similar_info_sql+" where hot_query="+"'"+str(content)+"'" +" order by rank asc"
    similar_df=execmysl('89',similar_change_sql)
    similar_query_word=similar_df['hot_query_similar'].to_list() if   not similar_df.empty else []
    similar_temp+=similar_query_word
    print("相似热词结果:",similar_temp)
    ##sku+query
    if not result_skus:
        print("底纹词,",diwenci_result)
        ##如果搜索没有商品数，则结果=相似搜索词+底纹词,并去重
        return removeRepeat(similar_temp+diwenci_result[:3])


    sku_match_change_sql=concatSql(recommend_sku_query_match_info_sql,**{"sku_no":result_skus}) +'order by rank asc'
    sku_match_df=execmysl('89',sku_match_change_sql)
    sku_match_change_df=sku_match_df.astype(str)[['sku_no','query']]. \
            groupby(by='query')['sku_no'].count().reset_index(name='count') \
        if not  sku_match_df.empty else []
    ##通过query分组拿到skuno，如果3个元素的值都小于1，则空列表
    try:
        sku_match_temp=sku_match_change_df[sku_match_change_df['count']>1].sort_values(by='count',ascending=False)['query'].to_list()
    except:
        sku_match_temp=[]

    finally:
        if not (similar_temp and sku_match_temp):
            return removeRepeat(diwenci_result)
        print("商品相关词:",sku_match_temp)
        ##从sku的query结果中，去掉相似query，然后2边交叉排序
        sku_match_temp_remove_from_similar=bingji(sku_match_temp,similar_temp)
        ##因为随机取不好弄，所以拿到所有数据交叉的
        return listCross(similar_temp,sku_match_temp_remove_from_similar)







if __name__ == '__main__':
    print(searchTopic('苹果耳机'))

