"""
根据提供的品牌名称 去 商标网查对应的专利,部署再h7物理机
"""
from flask import Flask, request, jsonify
import requests
import traceback
import json

app = Flask(__name__)
# 在应用程序中设置JSON_AS_ASCII选项为False
app.config['JSON_AS_ASCII'] = False


class brand_tmview():
    def __init__(self):
        self.data_dict = {}
        self.items = {}
        self.data_dict_list = []

    def get_tmview_data(self):
        # 获取商标编码。根据国家开头 如 US500000074325647，UK500000074325647
        url = "https://www.tmdn.org/tmview/api/search/results"
        headers = {
            "Accept": "application/json",
            "Accept-Language": "zh-CN,zh-TW;q=0.9,zh;q=0.8",
            "Cache-Control": "no-cache",
            "Connection": "keep-alive",
            "Content-Type": "application/json; charset=utf-8",
            "Origin": "https://www.tmdn.org",
            "Pragma": "no-cache",
            "Referer": "https://www.tmdn.org/tmview/",
            "Sec-Fetch-Dest": "empty",
            "Sec-Fetch-Mode": "cors",
            "Sec-Fetch-Site": "same-origin",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
            "sec-ch-ua": "\"Not_A Brand\";v=\"8\", \"Chromium\";v=\"120\", \"Google Chrome\";v=\"120\"",
            "sec-ch-ua-mobile": "?0",
            "sec-ch-ua-platform": "\"Windows\""
        }

        data = {"page": "1", "pageSize": "50", "criteria": "I", "basicSearch": self.keyword,
                "fOffices": ["ES", "FR", "GB", "IT", "US", "WO", "DE", "CA"], "fTMStatus": ["Registered", "Filed"],
                "fields": ["ST13", "markImageURI", "tmName", "tmOffice", "applicationNumber", "applicationDate",
                           "tradeMarkStatus", "niceClass"]}
        ST13_list = []
        try:
            response = requests.post(url, headers=headers, json=data, timeout=30).json()
            trademarks_list = response['tradeMarks']
            print('trademarks_list::', trademarks_list)
            if trademarks_list:
                for trademarks in trademarks_list:
                    ST13_list.append({"ST13": trademarks['ST13'], 'niceClass': trademarks['niceClass'],
                                      'tmOffice': trademarks['tmOffice'],
                                      'asin': self.asin, 'site': self.site, 'brand': self.keyword})
                if ST13_list:
                    self.get_trademark_detail(ST13_list)
            else:
                self.data_dict_list.append(response)
        except Exception as e:
            print("error_info：", e, f"\n{traceback.format_exc()}")

    def get_trademark_detail(self, ST13_list):
        # 根据商标编码获取注册人名称
        for ST13_data in ST13_list:
            url = f'https://www.tmdn.org/tmview/api/trademark/detail/{ST13_data["ST13"]}?translate=true'
            print('获取权利人名称url：', url)
            headers = {
                "Accept": "application/json",
                "Accept-Language": "zh-CN,zh;q=0.9",
                "Cache-Control": "no-cache",
                "Connection": "keep-alive",
                "Content-Type": "application/json; charset=utf-8",
                "Pragma": "no-cache",
                "Referer": "https://www.tmdn.org/tmview/",
                "Sec-Fetch-Dest": "empty",
                "Sec-Fetch-Mode": "cors",
                "Sec-Fetch-Site": "same-origin",
                "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
                "sec-ch-ua": "\"Not_A Brand\";v=\"8\", \"Chromium\";v=\"120\", \"Google Chrome\";v=\"120\"",
                "sec-ch-ua-mobile": "?0",
                "sec-ch-ua-platform": "\"Windows\""
            }
            for i in range(3):
                try:
                    response = requests.get(url, headers=headers,timeout=30).json()
                    applicants_list = response['applicants']
                    print('查看申请人详情::', applicants_list)
                    break
                except:
                    headers['Host'] = 'www.tmdn.org'
                    continue
            for applicants in applicants_list:
                ST13 = ST13_data["ST13"]
                niceClass = ST13_data['niceClass']
                tmOffice = ST13_data['tmOffice']
                asin = ST13_data['asin']
                brand = ST13_data['brand']
                site = ST13_data['site']
                full_name = applicants.get('fullName')
                if full_name is None:
                    full_name = applicants.get('organizationName')
                data_dict = {"ST13":ST13,'fullName': full_name, 'niceClass': niceClass,
                             'tmOffice': tmOffice,
                             'asin': asin, 'site': site, 'brand': brand}
                print('data_dictdata_dict::', data_dict)
                self.data_dict_list.append(data_dict)
        self.unique_data()

    def unique_data(self):
        # 创建一个集合来存储已经存在的元组（fullName、niceClass、tmOffice）
        seen = set()
        # 创建一个列表来存储去重后的数据
        unique_data_list = []
        # 遍历数据列表
        for item in self.data_dict_list:
            # 构建元组
            key = (item['fullName'], tuple(sorted(item['niceClass'])), item['tmOffice'])
            # 如果元组不在集合中，说明是新的条目，将其添加到集合和新的列表中
            if key not in seen:
                seen.add(key)
                unique_data_list.append(item)
        self.data_dict_list = unique_data_list

    def run(self, keyword, asin, site):
        print('搜索品牌名称：', keyword, asin, site)
        self.keyword = keyword
        self.asin = asin
        self.site = site
        self.get_tmview_data()
        return self.data_dict_list


# if __name__ == '__main__':
#     data_dict_list = brand_tmview().run('coospider-repta','B0C5D7TZ33','us')
#     print(data_dict_list)

#
@app.route('/tmview', methods=['GET'])
def get_args():
    asin = request.args.get('asin')
    site = request.args.get('site')
    keyword = request.args.get('brand')
    if site and asin and keyword:
        data_dict_list = brand_tmview().run(keyword, asin, site)
        if data_dict_list:
            items = {"code": 200, "message": "success", "data_dict": data_dict_list}
        else:
            items = {"code": 500, "message": "Retry", "data_dict": []}
        return jsonify(items)
    else:
        response = {'message': 'Request parameter error', 'code': 401, 'data_dict': []}
        return jsonify(response)


if __name__ == '__main__':
    app.run('0.0.0.0', 10247)

