from flask import Flask, request, jsonify
from temu_search import TemuSearch
from pictures_search import PicturesSearch
import time

temu_search = TemuSearch()
picture_search = PicturesSearch()

app = Flask(__name__)


@app.route('/search', methods=['POST'])
def search():
    print(request.form)  # 打印所有表单数据

    site_name = request.form.get('site_name', 'us')  # 默认值为 'us'
    search_key = request.form.get('search_key', 'asin')  # 默认值为 'asin'
    search_value = request.form.get('search_value', 'B0BBNQCXZL')  # 默认值为 'B0BBNQCXZL'
    top_k = int(request.form.get('top_k', 100))  # 默认值为 100
    print(site_name, search_key, search_value, top_k)
    # 获取文件并存储
    if search_key == 'file':
        file = request.files['file']  # 获取名为 "file" 的文件流参数
        # filename = file.filename
        timestamp = time.time()
        milli_timestamp = round(timestamp * 1000)  # 将秒级的时间戳转换为毫秒级
        filename = file.filename
        file_path = f'/mnt/data/img_data/tmp_img/{milli_timestamp}.jpg'
        file.save(file_path)
        print("file, file_path:", file, file_path)
    else:
        file_path = ''

    similarities_dict = temu_search.search_api(
        site_name=site_name, search_value=search_value
    )  # 进行搜索

    return jsonify(
        {
            "similarities_dict": similarities_dict,
        }
    )


@app.route('/search_amazon', methods=['POST'])
def search_amazon():
    site_name = request.form.get('site_name', 'us')  # 默认值为 'us'
    search_key = request.form.get('search_key', 'asin')  # 默认值为 'asin'
    search_value = request.form.get('search_value', 'B0BBNQCXZL')  # 默认值为 'B0BBNQCXZL'
    top_k = int(request.form.get('top_k', 100))  # 默认值为 100
    # 获取文件并存储
    if search_key == 'file':
        file = request.files['file']  # 获取名为 "file" 的文件流参数
        # filename = file.filename
        timestamp = time.time()
        milli_timestamp = round(timestamp * 1000)  # 将秒级的时间戳转换为毫秒级
        filename = file.filename
        file_path = f'/mnt/data/img_data/tmp_img/{milli_timestamp}.jpg'
        file.save(file_path)
        print("file, file_path:", file, file_path)
    else:
        file_path = ''

    similarities_dict = picture_search.search_api(
        site_name=site_name, search_key=search_key,
        search_value=search_value, top_k=top_k, file=file_path
    )  # 进行搜索

    return jsonify(
        {
            "similarities_dict": similarities_dict,
        }
    )


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8888)
