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

picture_search = PicturesSearch()

app = Flask(__name__)


# @app.route('/search', methods=['GET'])
# def search():
#     site_name = request.args.get('site_name', 'us')  # 默认值为 'us'
#     search_key = request.args.get('search_key', 'asin')  # 默认值为 'asin'
#     search_value = request.args.get('search_value', 'B0BBNQCXZL')  # 默认值为 'B0BBNQCXZL'
#     top_k = int(request.args.get('top_k', 100))  # 默认值为 100
#
#     similarities_dict = picture_search.search_api(
#         site_name=site_name, search_key=search_key,
#         search_value=search_value, top_k=top_k
#     )  # 进行搜索
#
#     return jsonify(
#         {
#             "similarities_dict": similarities_dict,
#         }
#     )

# @app.route('/search', methods=['POST'])
# def search():
#     data = request.get_json()
#
#     site_name = data.get('site_name', 'us')  # 默认值为 'us'
#     search_key = data.get('search_key', 'asin')  # 默认值为 'asin'
#     search_value = data.get('search_value', 'B0BBNQCXZL')  # 默认值为 'B0BBNQCXZL'
#     top_k = int(data.get('top_k', 100))  # 默认值为 100
#
#     similarities_dict = picture_search.search_api(
#         site_name=site_name, search_key=search_key,
#         search_value=search_value, top_k=top_k
#     )  # 进行搜索
#
#     return jsonify(
#         {
#             "similarities_dict": similarities_dict,
#         }
#     )


@app.route('/search', methods=['POST'])
def search():
    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,
        }
    )


@app.route('/upload', methods=['POST'])
def upload():
    if 'file' not in request.files:
        return 'No file part', 400
    file = request.files['file']
    if file.filename == '':
        return 'No selected file', 400
    # 你现在可以使用这个文件对象，比如保存它：
    file.save('/mnt/data/img_data/tmp_img/' + file.filename)
    return 'File uploaded successfully', 200


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