# -*- 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 resHtml(self,url):
        header={
            'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
            'Accept-Encoding':'gzip, deflate, br',
            'Accept-Language':'zh-CN,zh;q=0.9',
            'Cache-Control':'no-cache',
            'Connection':'keep-alive',
            'Cookie':'PHPSESSID=vii39tk7djrlebgqbdson80oj0; Hm_lvt_431865d92b681d30c9b5170d5d64ea44=1693794941; Hm_lpvt_431865d92b681d30c9b5170d5d64ea44=1693795260',
            'Host':'www.waihui999.com',
            'Pragma':'no-cache',
            'Referer':'https://www.waihui999.com/HUFcny/',
            'Sec-Fetch-Dest':'document',
            'Sec-Fetch-Mode':'navigate',
            'Sec-Fetch-Site':'same-origin',
            'Sec-Fetch-User':'?1',
            'Upgrade-Insecure-Requests':'1',
            'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36',
            'sec-ch-ua':'"Chromium";v="116", "Not)A;Brand";v="24", "Google Chrome";v="116"',
            'sec-ch-ua-mobile':'?0',
            'sec-ch-ua-platform':'"Windows"'
        }
        res = requests.get(url,headers=header)
        res.encoding = 'utf-8'
        html=res.text
        # print(html)
        return html
    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'''
                url = f'''https://www.waihui999.com/{currency}{result2}/#100'''
                url=url.lower()
                # 等待页面加载完成
                try:
                    # self.driver.get(url)
                    # wait = WebDriverWait(self.driver, 300)
                    # wait.until(EC.presence_of_element_located((By.TAG_NAME, "body")))
                    time.sleep(2)
                    html=self.resHtml(url)
                    doc_resp = pq(html)
                    money = doc_resp('div[class="ft"]>table>tbody>tr>td:nth-child(2)').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:
                    print('请求异常！！')
                    # 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)
            # 检查响应状态码
            print("请求成功")
            if resp.status_code == 200:
                print("请求成功")
                # 打印响应内容
                print(resp.content)
            else:
                print("请求失败")
        except Exception as e:
            print(e)

if __name__ == '__main__':
    result_list1 = [
        ['人民币','CNY'],
        ['港元','HKD'],
        ['台币','TWD'],
        ['欧元','EUR'],
        ['美元','USD'],
        ['英镑','GBP'],
        ['澳元','AUD'],
        ['韩元','KRW'],
        ['日元','JPY'],
        ['澳元','AUD'],
        ['阿尔巴尼亚列克','ALL'],
        ['阿尔及利亚第纳尔','DZD'],
        ['阿根廷比索','ARS'],
        ['阿鲁巴岛弗罗林','AWG'],
        ['澳元','AUD'],
        ['埃及镑','EGP'],
        ['埃塞俄比亚比尔','ETB'],
        ['澳门元','MOP'],
        ['阿曼里亚尔','OMR'],
        ['阿联酋迪拉姆','AED'],
        ['巴哈马元','BSD'],
        ['巴林第纳尔','BHD'],
        ['巴巴多斯元','BBD'],
        ['白俄罗斯卢布','BYR'],
        ['伯利兹元','BZD'],
        ['百慕大元','BMD'],
        ['不丹卢比','BTN'],
        ['玻利维亚诺','BOB'],
        ['博茨瓦纳普拉','BWP'],
        ['巴西里亚伊','BRL'],
        ['保加利亚列瓦','BGN'],
        ['布隆迪法郎','BIF'],
        ['冰岛克朗','ISK'],
        ['巴基斯坦卢比','PKR'],
        ['巴拿马巴尔博亚','PAB'],
        ['巴布亚新几内亚基那','PGK'],
        ['巴拉圭瓜拉尼','PYG'],
        ['波兰兹罗提','PLN'],
        ['朝鲜圆','KPW'],
        ['多哥非洲共同体法郎','XOF'],
        ['丹麦克朗','DKK'],
        ['多米尼加比索','DOP'],
        ['俄罗斯卢布','RUB'],
        ['佛得角埃斯库多','CVE'],
        ['福克兰群岛镑','FKP'],
        ['斐济元','FJD'],
        ['菲律宾比索','PHP'],
        ['港元','HKD'],
        ['刚果中非共同体法郎','XAF'],
        ['哥伦比亚比索','COP'],
        ['哥斯达黎加科朗','CRC'],
        ['古巴比索','CUP'],
        ['格林纳达东加勒比元','XCD'],
        ['冈比亚达拉西','GMD'],
        ['圭亚那元','GYD'],
        #['韩元','KRW'],
        ['海地古德','HTG'],
        ['洪都拉斯伦皮拉','HNL'],
        ['哈萨克斯坦腾格','KZT'],
        ['柬埔寨利尔斯','KHR'],
        ['加拿大元','CAD'],
        ['捷克克朗','CZK'],
        ['吉布提法郎','DJF'],
        ['几内亚法郎','GNF'],
        ['科摩罗法郎','KMF'],
        ['克罗地亚库纳','HRK'],
        ['肯尼亚先令','KES'],
        ['科威特第纳尔','KWD'],
        ['卡塔尔利尔','QAR'],
        ['老挝基普','LAK'],
        ['拉脱维亚拉图','LVL'],
        ['黎巴嫩镑','LBP'],
        ['莱索托洛提','LSL'],
        ['利比里亚元','LRD'],
        ['利比亚第纳尔','LYD'],
        ['立陶宛里塔斯','LTL'],
        ['列斯荷兰盾','ANG'],
        ['罗马尼亚新列伊','RON'],
        ['卢旺达法郎','RWF'],
        #['美元','USD'],
        ['孟加拉塔卡','BDT'],
        ['马其顿第纳尔','MKD'],
        ['马拉维克瓦查','MWK'],
        ['马来西亚林吉特','MYR'],
        ['马尔代夫卢非亚','MVR'],
        ['毛里塔尼亚乌吉亚','MRO'],
        ['毛里求斯卢比','MUR'],
        ['墨西哥比索','MXN'],
        ['摩尔多瓦列伊','MDL'],
        ['蒙古图格里克','MNT'],
        ['摩洛哥道拉姆','MAD'],
        ['缅甸元','MMK'],
        ['秘鲁索尔','PEN'],
        ['纳米比亚元','NAD'],
        ['尼泊尔卢比','NPR'],
        ['尼加拉瓜科多巴','NIO'],
        ['尼日利亚奈拉','NGN'],
        ['挪威克朗','NOK'],
        ['南非兰特','ZAR'],
        ['欧元','EUR'],
        ['日元','JPY'],
        ['瑞典克朗','SEK'],
        ['瑞士法郎','CHF'],
        ['萨尔瓦多科朗','SVC'],
        ['萨摩亚塔拉','WST'],
        ['圣多美多布拉','STD'],
        ['沙特阿拉伯里亚尔','SAR'],
        ['塞舌尔法郎','SCR'],
        ['塞拉利昂利昂','SLL'],
        ['所罗门群岛元','SBD'],
        ['索马里先令','SOS'],
        ['斯里兰卡卢比','LKR'],
        ['圣赫勒拿群岛磅','SHP'],
        ['斯威士兰里兰吉尼','SZL'],
        ['台币','TWD'],
        ['土耳其新里拉','TRY'],
        ['太平洋法郎','XPF'],
        ['坦桑尼亚先令','TZS'],
        ['泰国铢','THB'],
        ['汤加潘加','TOP'],
        ['特立尼达和多巴哥元','TTD'],
        ['突尼斯第纳尔','TND'],
        ['文莱元','BND'],
        ['危地马拉格查尔','GTQ'],
        ['乌克兰赫夫米','UAH'],
        ['乌拉圭新比索','UYU'],
        ['瓦努阿图瓦图','VUV'],
        ['越南盾','VND'],
        ['匈牙利福林','HUF'],
        ['新西兰元','NZD'],
        ['新加坡元','SGD'],
        ['叙利亚镑','SYP'],
        ['英镑','GBP'],
        ['印度卢比','INR'],
        ['印度尼西亚卢比(盾)','IDR'],
        ['伊朗里亚尔','IRR'],
        ['伊拉克第纳尔','IQD'],
        ['以色列镑','ILS'],
        ['牙买加元','JMD'],
        ['约旦第纳尔','JOD'],
        ['也门里亚尔','YER'],
        ['智利比索','CLP'],
        ['直布罗陀镑','GIP'],
        ['铜价盎司','XCP'],
        ['金价盎司','XAU'],
        ['钯价盎司','XPD'],
        ['铂价盎司','XPT'],
        ['银价盎司','XAG']
       ]
    result_list2 = [
        'USD',
        'CNY']
    currenRate=CurrencyRate()
    currenRate.getRate()
    currenRate.driver.quit()

