# -*- coding: utf-8 -*-
import datetime


from selenium.webdriver.support.wait import WebDriverWait

import time
import requests
from pyquery import PyQuery as pq
from selenium import webdriver

from requests.packages import urllib3
urllib3.disable_warnings()
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

import configparser
import redis


class CurrencyRate(object):
    def __init__(self):
        self.config = configparser.ConfigParser()
        # 读取配置文件
        self.config.read('config.ini')
        self.r = redis.Redis(host=self.config.get('redis', 'host'),
                             port=self.config.get('redis', 'port'),
                             password=self.config.get('redis', 'pass'), db=6)
        self.driver=self.get_webdriver()

    def get_webdriver(self):
        chrome_options = webdriver.ChromeOptions()
        chrome_options.add_argument('--disable-gpu')
        chrome_options.add_argument('--ignore-certificate-errors')
        chrome_options.add_experimental_option('excludeSwitches', ['enable-automation'])
        chrome_options.add_argument("--disable-blink-features=AutomationControlled")
        chrome_options.add_argument("--start-maximized")
        # chrome_options.add_argument('--headless')
        chrome_options.binary_location = self.config.get('selenium', 'binary_location')
        executable_path =self.config.get('selenium', 'chrome_driver')
        driver = webdriver.Chrome(options=chrome_options, executable_path=executable_path)
        return driver

    def getRate(self):
        rateList=[]
        for result1 in result_list1:
            currency_name = result1[0]
            currency = result1[1]
            to_USD = ''
            to_CNY = ''
            for i in range(len(result_list2)):
                result2 = result_list2[i]
                # https://qq.ip138.com/hl.asp?from=CNY&to=USD&q=1
                url = f'''https://qq.ip138.com/hl.asp?from={currency}&to={result2}&q=1'''
                # 等待页面加载完成
                try:
                    self.driver.get(url)
                    wait = WebDriverWait(self.driver, 300)
                    wait.until(EC.presence_of_element_located((By.TAG_NAME, "body")))
                    time.sleep(1)
                    doc_resp = pq(self.driver.page_source)
                    money = doc_resp('table tr:nth-child(3) td:nth-child(3)').text()
                    if money == '1':
                        money_result = money
                    else:
                        try:
                            money_result = round(float(money), 4)
                        except:
                            continue
                    if i == 0:
                        to_USD = money_result
                    else:
                        to_CNY = money_result
                except Exception as e:
                    try:
                        self.driver.close()
                        self.driver.quit()
                    except Exception as e:
                        print(e)
                    self.driver=self.get_webdriver()

            now = datetime.datetime.now()
            now_time = now.strftime('%Y-%m-%d')
            if to_USD == '' or to_CNY == '':
                continue
            result_dict = {
                '币种': currency_name,
                '币简称': currency,
                '对美元': to_USD,
                '对人民币': to_CNY,
                '更新时间': now_time }
            print(result_dict)
            rate={
                "currencyName": currency_name,
                "currencyCode": currency,
                "rateToUSD": to_USD,
                "rateToCNY": to_CNY,
                "createDate": now_time
            }
            rateList.append(rate)

        # market_url = f'http://192.168.1.39:8088/sync/currencyRate'
        market_url = f'http://114.115.236.206:8088/sync/currencyRate'
        try:
            resp = requests.post(market_url,json=rateList)
            # 检查响应状态码
            if resp.status_code == 200:
                print("请求成功")
                # 打印响应内容
                print(resp.content)
            else:
                print("请求失败")
        except Exception as e:
            print(e)

if __name__ == '__main__':
    result_list1 = [
        [
            '人民币',
            'CNY'],
        [
            '美元',
            'USD'],
        [
            '欧元',
            'EUR'],
        [
            '瑞士法郎',
            'CHF'],
        [
            '加元',
            'CAD'],
        [
            '波兰兹罗提',
            'PLN'],
        [
            '英镑',
            'GBP'],
        [
            '澳元',
            'AUD'],
        [
            '泰铢',
            'THB'],
        [
            '沙特里亚尔',
            'SAR'],
        [
            '巴西里亚伊',
            'BRL'],
        [
            '新土耳其新里拉',
            'TRY'],
        [
            '新台币',
            'TWD'],
        [
            '印度卢比',
            'INR'],
        [
            '墨西哥比索',
            'MXN'],
        [
            '日元',
            'JPY'],
        [
            '瑞典克朗',
            'SEK'],
        [
            '韩元',
            'KRW'],
        [
            '俄罗斯卢布',
            'RUB'],
        [
            '新加坡元',
            'SGD'],
        [
            '港币',
            'HKD']]
    result_list2 = [
        'USD',
        'CNY']
    currenRate=CurrencyRate()
    currenRate.getRate()
    currenRate.driver.quit()

