import json

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(uuid,gid,content):
    #uuid,gid=genUuidDeviceid()
    #uuid=""
    #gid="58A9A9D2-6445-4550-9715-72151CC1A726"
    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 limit 5"
    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)[:8],result_skus

    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','rank']]. \
            groupby(by=['query'])['sku_no'].count().reset_index(name='count') \
        if not  sku_match_df.empty else []
    ##通过query分组拿到skuno，如果3个元素的值都小于1，则空列表
    try:
        if len(result_skus)==1:
            sku_match_temp=sku_match_change_df['query'].to_list()
        else:
            sku_match_temp=sku_match_change_df[sku_match_change_df['count']>1].sort_values(by=['count'],ascending=0)['query'].to_list()
    except:
        sku_match_temp=[]

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

def supplementSearch(uuid,gid,searchword):
    temp=[]
    url=search_url_aliyun+'/searchReplenishment'
    headers={
        "XQG-USER-UUID":uuid if uuid else "",
        "Content-Type":"application/json"
    }
    body={
        "deviceId":gid if gid else "" ,
        "userUuid": uuid if uuid else "",
        "extraParams": {
            "terminalType": 1
        },
        "searchContent": "",
        "sortType": 1
    }
    for i in searchword[:3]:
        body['searchContent']=i
        t=requests.post(url,headers=headers,data=json.dumps(body))
        #print(body)
        #print(t.json())
        skus=jsonpath.jsonpath(t.json(),'$..skuNo')
        temp+=skus
    return temp




def main(uuid,gid,searchword):
    words,search_skus=searchTopic(uuid,gid,searchword)
    recommend_supplement_result=supplementSearch(uuid,gid,words)
    print("补量的推荐商品数据如下:",len(recommend_supplement_result),recommend_supplement_result)
    print("补量的搜索商品数据:",search_skus)
    if search_skus:
        temp=[i for i in search_skus if i  in recommend_supplement_result]
        print("以上数据是否有重复:",temp if len(temp)>=1 else 0)
    print("补量的推荐词如下:",words)

    return words,recommend_supplement_result




if __name__ == '__main__':
    uuid=""
    gid="65E052A9-7C04-433A-80B9-927964707456"
    searchword='beats耳机'
    print("最终推荐结果:",main(uuid,gid,searchword))

