/*
 * Copyright (C) 2023 KylinSoft Co., Ltd.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */
#include <QDebug>
#include <QTimer>
#include <QGraphicsDropShadowEffect>

#include "mainwindow.h"
#include "toolmodel.h"
#include "cal.h"

const int TAG_INFO = 100;

using namespace std;

ToolModelOutput::ToolModelOutput(QWidget *parent) : QWidget(parent)
{
    /* 初始化组件 */
    this->setWidgetUi();

    /* 设置组件样式 */
    this->setWidgetStyle();
}


// 初始化组件
void ToolModelOutput::setWidgetUi()
{
    /* 汇率刷新 */
    toolLabUpdate = new QLabel(this);
    toolIconUpdate = new QToolButton(this);
    toolLabTime = new QLabel(this);
    toolLabRate = new QLabel(this);
    toolLabUpdate->setContentsMargins(4, 0, 4, 0);
    toolIconUpdate->setFixedSize(24, 24);

    toolUpdateLayout = new QVBoxLayout(this);
    toolUpdateLayout->addStretch(16);
    toolUpdateLayout->addWidget(toolLabUpdate, 33, Qt::AlignCenter);
    toolUpdateLayout->addStretch(36);
    toolUpdateLayout->addWidget(toolIconUpdate, 27, Qt::AlignCenter);
    toolUpdateLayout->addStretch(36);
    toolUpdateLayout->addWidget(toolLabTime, 16, Qt::AlignCenter);
    toolUpdateLayout->addStretch(15);
    toolUpdateLayout->addWidget(toolLabRate, 16, Qt::AlignCenter);
    toolUpdateLayout->addStretch(23);

    toolUpdateWid = new QWidget(this);
    toolUpdateWid->setLayout(toolUpdateLayout);
    toolUpdateWid->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum);

    /* 换算前单位标识 */
    toolLabUnitBef = new QLabel(this);
    toolLabIconBef = new QLabel(this);

    toolLabUnitBef->setFixedWidth(64);
    toolLabUnitBef->setWordWrap(true);

    toolUnitBefLayout = new QHBoxLayout(this);
    toolUnitBefLayout->addStretch(15);
    toolUnitBefLayout->addWidget(toolLabUnitBef, 72, Qt::AlignCenter);
    toolUnitBefLayout->addStretch(240);
    toolUnitBefLayout->addWidget(toolLabIconBef, 21, Qt::AlignCenter);
    toolUnitBefLayout->addStretch(50);

    toolUnitBefWid = new QPushButton(this);
    toolUnitBefWid->setLayout(toolUnitBefLayout);
    toolUnitBefWid->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum);

    /* 换算后单位标识 */
    toolLabUnitAft = new QLabel(this);
    toolLabIconAft = new QLabel(this);

    toolLabUnitAft->setFixedWidth(64);
    toolLabUnitAft->setWordWrap(true);

    toolUnitAftLayout = new QHBoxLayout(this);
    toolUnitAftLayout->addStretch(15);
    toolUnitAftLayout->addWidget(toolLabUnitAft, 72, Qt::AlignCenter);
    toolUnitAftLayout->addStretch(240);
    toolUnitAftLayout->addWidget(toolLabIconAft, 21, Qt::AlignCenter);
    toolUnitAftLayout->addStretch(50);

    toolUnitAftWid = new QPushButton(this);
    toolUnitAftWid->setLayout(toolUnitAftLayout);
    toolUnitAftWid->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum);

    /* 汇率刷新 */
    toolLabUpdate->setText(tr("Rate update"));
    toolIconUpdate->setIcon(QIcon::fromTheme("transform-rotate", QIcon(":/image/update.png")));
    toolIconUpdate->setIconSize(QSize(16, 16));
    toolIconUpdate->setProperty("isWindowButton", 0x1);
    toolIconUpdate->setProperty("useIconHighlightEffect", 0x2);
    toolIconUpdate->setAutoRaise(true);

    /* 默认汇率 */
    toolDouRate = 0.15;
    toolLabTime->setText("2020.09.03 09:30");
    toolLabRate->setText("1 CNY = 0.15 USD");

    connect(toolIconUpdate, &QToolButton::clicked, this, &ToolModelOutput::updateRate);

    /* 换算前单位标识 */
    toolRateNameBef = tr("Chinese Yuan");
    toolRateSymbBef = "CNY";
    toolLabUnitBef->setText(toolRateNameBef + "\n" + toolRateSymbBef);
    toolLabUnitBef->setAlignment(Qt::AlignLeft);
    toolLabIconBef->setPixmap(QIcon::fromTheme("ukui-down-symbolic").pixmap(16, 16));

    /* 换算后单位标识 */
    toolRateNameAft = tr("US Dollar");
    toolRateSymbAft = "USD";
    toolLabUnitAft->setText(toolRateNameAft + "\n" + toolRateSymbAft);
    toolLabUnitAft->setAlignment(Qt::AlignLeft);
    toolLabIconAft->setPixmap(QIcon::fromTheme("ukui-down-symbolic").pixmap(16, 16));

    connect(toolUnitBefWid, SIGNAL(clicked()), this, SLOT(unitListBefShow()));
    connect(toolUnitAftWid, SIGNAL(clicked()), this, SLOT(unitListAftShow()));

    // 数据输出界面
    this->toolLabHis = new QLabel(this);
    this->toolLabBef = new QLabel(this);
    this->toolLabAft = new QLabel(this);

    this->toolLabAft->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    this->toolLabBef->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    this->toolLabAft->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);

    QFont toolLabHisFont("SourceHanSansCN-Light", 40, 15);
    if(isHaWeiKe){
        this->toolLabHis->setAlignment(Qt::AlignLeft | Qt::AlignTop);
    }else{
        this->toolLabHis->setAlignment(Qt::AlignRight | Qt::AlignTop);
    }
    this->toolLabHis->setFont(toolLabHisFont);
    this->toolLabHis->setText("");
    this->toolLabHis->setContentsMargins(0, 0, 20, 0);
    this->toolLabHis->show();

    QFont toolLabBefFont("SourceHanSansCN-Normal;", 48, 15);
    if(isHaWeiKe){
        this->toolLabBef->setAlignment(Qt::AlignLeft | Qt::AlignVCenter);
    }else{
        this->toolLabBef->setAlignment(Qt::AlignRight | Qt::AlignVCenter);
    }
    this->toolLabBef->setFont(toolLabBefFont);
    this->toolLabBef->setText("0");
    this->toolLabBef->setContentsMargins(0, 0, 20, 0);
    this->toolLabBef->show();

    QFont toolLabAftFont("SourceHanSansCN-Normal", 48, 15);
    if(isHaWeiKe){
        this->toolLabAft->setAlignment(Qt::AlignLeft | Qt::AlignBottom);
    }else{
        this->toolLabAft->setAlignment(Qt::AlignRight | Qt::AlignBottom);
    }
    this->toolLabAft->setFont(toolLabAftFont);
    this->toolLabAft->setText("0");
    this->toolLabAft->setContentsMargins(0, 0, 20, 0);
    this->toolLabAft->show();

    // 将数据输出组件和数据单位列表加入布局
    QGridLayout *toolOutputLayout = new QGridLayout(this);
    toolOutputLayout->setColumnStretch(0, 398);
    toolOutputLayout->setColumnStretch(1, 1208);
    toolOutputLayout->setRowStretch(0, 224);
    toolOutputLayout->setRowStretch(1, 107);
    toolOutputLayout->setRowStretch(2, 107);

    toolOutputLayout->addWidget(toolUpdateWid, 0, 0);
    toolOutputLayout->addWidget(toolUnitBefWid, 1, 0);
    toolOutputLayout->addWidget(toolUnitAftWid, 2, 0);
    toolOutputLayout->addWidget(toolLabHis, 0, 1);
    toolOutputLayout->addWidget(toolLabBef, 1, 1);
    toolOutputLayout->addWidget(toolLabAft, 2, 1);

    toolOutputLayout->setSpacing(2);
    toolOutputLayout->setContentsMargins(4, 1, 1, 2);

    this->setLayout(toolOutputLayout);

    // 数据单位列表
    this->unitListBef = new UnitListWidget(this->parentWidget());
    this->unitListAft = new UnitListWidget(this->parentWidget());

   connect(this->unitListBef, &UnitListWidget::itemClicked, this, &ToolModelOutput::listItemClicked);
   connect(this->unitListAft, &UnitListWidget::itemClicked, this, &ToolModelOutput::listItemClicked);

    this->unitListBef->hide();
    this->unitListAft->hide();

    m_picturetowhite = new PictureToWhite();

    rateMap = {{"Algerian dinar", "DZD"},      {"Australian dollar", "AUD"},
               {"Bahrain Dinar", "BHD"},       {"Bolivar Fuerte", "VEF"},
               {"Botswana pula", "BWP"},       {"Brazilian real", "BRL"},
               {"Brunei dollar", "BND"},       {"Canadian dollar", "CAD"},
               {"Chilean peso", "CLP"},        {"Chinese yuan", "CNY"},
               {"Colombian peso", "COP"},      {"Czech koruna", "CZK"},
               {"Danish krone", "DKK"},        {"Euro", "EUR"},
               {"Hungarian Forint", "HUF"},    {"Icelandic Krona", "ISK"},
               {"Indian rupee", "INR"},        {"Indonesian Rupiah", "IDR"},
               {"Iranian Rial", "IRR"},        {"Israeli New Shekel", "ILS"},
               {"Japanese yen", "JPY"},        {"Kazakhstani Tenge", "KZT"},
               {"Korean won", "KRW"},          {"Kuwaiti dinar", "KWD"},
               {"Libyan Dinar", "LYD"},        {"Malaysian ringgit", "MYR"},
               {"Mauritian rupee", "MUR"},     {"Mexican peso", "MXN"},
               {"Nepalese Rupee", "NPR"},      {"New Zealand dollar", "NZD"},
               {"Norwegian krone", "NOK"},     {"Nuevo Sol", "PEN"},
               {"Omani rial", "OMR"},          {"Pakistani Rupee", "PKR"},
               {"Peruvian sol", "PEN"},        {"Philippine peso", "PHP"},
               {"Polish zloty", "PLN"},        {"Qatari riyal", "QAR"},
               {"Rial Omani", "OMR"},          {"Russian ruble", "RUB"},
               {"Saudi Arabian riyal", "SAR"}, {"Singapore dollar", "SGD"},
               {"South African rand", "ZAR"},  {"Sri Lanka Rupee", "LKR"},
               {"Swedish krona", "SEK"},       {"Swiss franc", "CHF"},
               {"Thai baht", "THB"},           {"Trinidadian dollar", "TTD"},
               {"Tunisian Dinar", "TND"},      {"U.A.E. dirham", "AED"},
               {"U.K. pound", "GBP"},          {"Uruguayan peso", "UYU"},
               {"U.S. dollar", "USD"},         {NULL, NULL}};

    // 没有ARS
    currencyInfoUS = {{"AED", "UAE Dirham"},         {"ARS", "Argentinian peso"},
                      {"AUD", "Australian Dollar"},  {"BGN", "Bulgarian Lev"},
                      {"BHD", "Bahraini Dinar"},     {"BND", "Brunei Dollar"},
                      {"BRL", "Brazilian Real"},     {"BSD", "Bahaman Dollar"},
                      {"BWP", "Botswana Pula"},      {"CAD", "Canadian Dollar"},
                      {"CFA", "CFA Franc"},          {"CHF", "Swiss Franc"},
                      {"CLP", "Chilean Peso"},       {"CNY", "Chinese Yuan"},
                      {"COP", "Colombian Peso"},     {"CZK", "Czech Koruna"},
                      {"DKK", "Danish Krone"},       {"DOP", "Dominican peso"},
                      {"DZD", "Algerian Dinar"},     {"EEK", "Estonian Kroon"},
                      {"EGP", "Egyptian pound"},     {"EUR", "Euro"},
                      {"FJD", "Fijian dollar"},      {"GBP", "Pound Sterling"},
                      {"GTQ", "Guatemalan Quetzal"}, {"HKD", "Hong Kong Dollar"},
                      {"HRK", "Croatian Kuna"},      {"HUF", "Hungarian Forint"},
                      {"IDR", "Indonesian Rupiah"},  {"ILS", "Israeli New Shekel"},
                      {"INR", "Indian Rupee"},       {"IRR", "Iranian Rial"},
                      {"ISK", "Icelandic Krona"},    {"JPY", "Japanese Yen"},
                      {"KRW", "South Korean Won"},   {"KWD", "Kuwaiti Dinar"},
                      {"KZT", "Kazakhstani Tenge"},  {"LKR", "Sri Lankan Rupee"},
                      {"LTL", "Lithuanian Litas"},   {"LVL", "Latvian Lats"},
                      {"LYD", "Libyan Dinar"},       {"MUR", "Mauritian Rupee"},
                      {"MVR", "Maldivian Rupee"},    {"MXN", "Mexican Peso"},
                      {"MYR", "Malaysian Ringgit"},  {"NOK", "Norwegian Krone"},
                      {"NPR", "Nepalese Rupee"},     {"NZD", "New Zealand Dollar"},
                      {"OMR", "Omani Rial"},         {"PAB", "Panamanian balbos"},
                      {"PEN", "Peruvian Nuevo Sol"}, {"PHP", "Philippine Peso"},
                      {"PKR", "Pakistani Rupee"},    {"PLN", "Polish Zloty"},
                      {"PYG", "Paraguayan Guaran"},  {"QAR", "Qatari Riyal"},
                      {"RON", "New Romanian Leu"},   {"RUB", "Russian Rouble"},
                      {"SAR", "Saudi Riyal"},        {"SEK", "Swedish Krona"},
                      {"SGD", "Singapore Dollar"},   {"THB", "Thai Baht"},
                      {"TND", "Tunisian Dinar"},     {"TRY", "New Turkish Lira"},
                      {"TTD", "T&T Dollar (TTD)"},   {"TWD", "Taiwan Dollar"},
                      {"UAH", "Ukrainian Hryvnia"},  {"USD", "US Dollar"},
                      {"UYU", "Uruguayan Peso"},     {"VEF", "Venezuelan Bolívar"},
                      {"ZAR", "South African Rand"}, {NULL, NULL}};

    // 新增ARS、BSD、DOP、EGP、FJD、GTQ、MVR、PAB、PYG、TWD、UAH
    currencyInfoCN = {{"AED", "阿联酋迪拉姆"},
                      {"ARS", "阿根廷比索"},
                      {"AUD", "澳大利亚元"},
                      {"BGN", "保加利亚列弗"},
                      {"BHD", "巴林第纳尔"},
                      {"BND", "文莱元"},
                      {"BRL", "巴西雷亚尔"},
                      {"BSD", "巴哈马元"},
                      {"BWP", "博茨瓦纳普拉"},
                      {"CAD", "加拿大元"},
                      {"CFA", "中非法郎"},
                      {"CHF", "瑞士法郎"},
                      {"CLP", "智利比索"},
                      {"CNY", "人民币"},
                      {"COP", "哥伦比亚比索"},
                      {"CZK", "捷克克朗"},
                      {"DKK", "丹麦克朗"},
                      {"DOP", "多米尼加比索"},
                      {"DZD", "阿尔及利亚第纳尔"},
                      {"EEK", "爱沙尼亚克朗"},
                      {"EGP", "埃及镑"},
                      {"EUR", "欧元"},
                      {"FJD", "斐济元"},
                      {"GBP", "英镑"},
                      {"GTQ", "危地马拉格查尔"},
                      {"HKD", "港币"},
                      {"HRK", "克罗地亚库纳"},
                      {"HUF", "匈牙利福林"},
                      {"IDR", "印度尼西亚卢比"},
                      {"ILS", "以色列新谢克尔"},
                      {"INR", "印度卢比"},
                      {"IRR", "伊朗里亚尔"},
                      {"ISK", "冰岛克朗"},
                      {"JPY", "日元"},
                      {"KRW", "韩元"},
                      {"KWD", "科威特第纳尔"},
                      {"KZT", "哈萨克斯坦腾格"},
                      {"LKR", "斯里兰卡卢比"},
                      {"LTL", "立陶宛立特"},
                      {"LVL", "拉脱维亚拉特"},
                      {"LYD", "利比亚第纳尔"},
                      {"MUR", "毛里求斯卢比"},
                      {"MVR", "马尔代夫卢比"},
                      {"MXN", "墨西哥比索"},
                      {"MYR", "马来西亚林吉特"},
                      {"NOK", "挪威克朗"},
                      {"NPR", "尼泊尔卢比"},
                      {"NZD", "新西兰元"},
                      {"OMR", "阿曼里亚尔"},
                      {"PAB", "巴拿马巴波亚"},
                      {"PEN", "秘鲁新索尔"},
                      {"PHP", "菲律宾比索"},
                      {"PKR", "巴基斯坦卢比"},
                      {"PLN", "波兰兹罗提"},
                      {"PYG", "巴拉圭瓜拉尼"},
                      {"QAR", "卡塔尔里亚尔"},
                      {"RON", "新罗马尼亚列伊"},
                      {"RUB", "俄罗斯卢布"},
                      {"SAR", "沙特里亚尔"},
                      {"SEK", "瑞典克朗"},
                      {"SGD", "新加坡元"},
                      {"THB", "泰铢"},
                      {"TND", "突尼斯第纳尔"},
                      {"TRY", "新土尔其里拉"},
                      {"TTD", "特立尼达和多巴哥元"},
                      {"TWD", "台币"},
                      {"UAH", "乌克兰格里夫纳"},
                      {"USD", "美元"},
                      {"UYU", "乌拉圭比索"},
                      {"VEF", "委内瑞拉玻利瓦尔"},
                      {"ZAR", "南非兰特"},
                      {NULL, NULL}};

    m_firstLoad = true;

    defUpdateRate();

    updateRate();

    this->setAutoFillBackground(true);
    this->setBackgroundRole(QPalette::Base);

    toolUnitBefWid->setProperty("isWindowButton", 0x1);
    toolUnitBefWid->setProperty("useIconHighlightEffect", 0x2);

    toolUnitAftWid->setProperty("isWindowButton", 0x1);
    toolUnitAftWid->setProperty("useIconHighlightEffect", 0x2);
}

// 设置组件样式
void ToolModelOutput::setWidgetStyle(bool resetFontSize)
{
    QFont font = toolLabTime->font();
    font.setPixelSize(12);
    toolLabTime->setFont(font);
    toolLabRate->setFont(font);
    if (WidgetStyle::themeColor == WidgetStyle::ThemeColor::LIGHT) {
//        toolLabUpdate->setStyleSheet("font-size:16px;color:#272A2D;");

//        toolLabTime->setStyleSheet("font-size:10px;color:#272A2D;");
//        toolLabRate->setStyleSheet("font-size:10px;color:#272A2D;");
//        toolUpdateWid->setStyleSheet("background:#F3F3F3;opacity:1;");

//        QString unitLabStyle = "font-family:SourceHanSansCN-ExtraLight;font-size:18px;color:#272A2D;line-height:18px;";
//        toolLabUnitBef->setStyleSheet(unitLabStyle);
        toolLabIconBef->setPixmap(QIcon::fromTheme("ukui-down-symbolic").pixmap(16, 16));
        toolLabIconBef->setStyleSheet("border-image:url(:/image/downward.png);");
//        toolUnitBefWid->setStyleSheet("QPushButton{background:#F3F3F3;color:#272A2D;opacity:1;}"
//                                      "QPushButton:hover{background-color:#F3F3F3;}");
//        toolLabUnitAft->setStyleSheet(unitLabStyle);
        toolLabIconAft->setPixmap(QIcon::fromTheme("ukui-down-symbolic").pixmap(16, 16));
        toolLabIconAft->setStyleSheet("border-image:url(:/image/downward.png);");
//        toolUnitAftWid->setStyleSheet("QPushButton{background:#F3F3F3;color:#272A2D;opacity:1;}"
//                                      "QPushButton:hover{background-color:#F3F3F3;}");
        // 数据输出界面
        this->toolLabHis->setStyleSheet("color:#8C8C8C;font-size:12px;font-weight:15px;line-height:50px;");

        if (resetFontSize) {
            this->toolLabAft->setStyleSheet("color:#272A2D;font-size:40px;font-weight:15px;line-height:50px;");
            this->toolLabBef->setStyleSheet("color:#272A2D;font-size:48px;font-weight:15px;");
        } else {
            QString fontSizeStr = QString::number(toolLabAft->font().pixelSize());
            this->toolLabAft->setStyleSheet("color:#272A2D;font-size:" + fontSizeStr
                                            + "px;font-weight:15px;line-height:50px;");
            fontSizeStr = QString::number(toolLabBef->font().pixelSize());
            this->toolLabBef->setStyleSheet("color:#272A2D;font-size:" + fontSizeStr + "px;font-weight:15px;");
        }

        // this->setStyleSheet("background-color:#8C8C8C;border-radius:4px;");

    } else if (WidgetStyle::themeColor == WidgetStyle::ThemeColor::DARK) {
//        toolLabUpdate->setStyleSheet("font-family:SourceHanSansCN-ExtraLight;font-size:16px;color:#FFFFFF;");

//        toolLabTime->setStyleSheet("font-family:NotoSansHans-Light;font-size:10px;color:#A6A6A6;line-height:17px;");
//        toolLabRate->setStyleSheet("font-family:NotoSansHans-Light;font-size:10px;color:#A6A6A6;line-height:17px;");
//        toolUpdateWid->setStyleSheet("background:#18181A;opacity:0.75;");

//        QString unitLabStyle = "font-family:SourceHanSansCN-ExtraLight;font-size:18px;color:#FFFFFF;line-height:22px;";
//        toolLabUnitBef->setStyleSheet(unitLabStyle);
        toolLabIconBef->setPixmap(
            m_picturetowhite->drawSymbolicColoredPixmap(QIcon::fromTheme("ukui-down-symbolic").pixmap(16, 16)));
         toolLabIconBef->setStyleSheet("border-image:url(:/image/downward.png);");
//        toolUnitBefWid->setStyleSheet("QPushButton{background:#18181A;color:#FFFFFF;opacity:0.75;}"
//                                      "QPushButton:hover{background-color:#18181A;}");
//        toolLabUnitAft->setStyleSheet(unitLabStyle);
        toolLabIconAft->setPixmap(
            m_picturetowhite->drawSymbolicColoredPixmap(QIcon::fromTheme("ukui-down-symbolic").pixmap(16, 16)));
         toolLabIconAft->setStyleSheet("border-image:url(:/image/downward.png);");
//        toolUnitAftWid->setStyleSheet("QPushButton{background:#18181A;color:#FFFFFF;opacity:0.75;}"
//                                      "QPushButton:hover{background-color:#18181A;}");

        // 数据输出界面
        this->toolLabHis->setStyleSheet("color:#8C8C8C;font-size:12px;font-weight:15px;line-height:50px;");

        if (resetFontSize) {
            this->toolLabAft->setStyleSheet("color:#FFFFFF;font-size:40px;font-weight:15px;line-height:50px;");
            this->toolLabBef->setStyleSheet("color:#FFFFFF;font-size:48px;font-weight:15px;");
        } else {
            QString fontSizeStr = QString::number(toolLabAft->font().pixelSize());
            this->toolLabAft->setStyleSheet("color:#FFFFFF;font-size:" + fontSizeStr
                                            + "px;font-weight:15px;line-height:50px;");
            fontSizeStr = QString::number(toolLabBef->font().pixelSize());
            this->toolLabBef->setStyleSheet("color:#FFFFFF;font-size:" + fontSizeStr + "px;font-weight:15px;");
        }
    }
}

// 初始化单位列表
void ToolModelOutput::initUnitList(QString listStr)
{
    QStringList unitStrList = listStr.split(",");

    unitListBef->clear();
    unitListAft->clear();

    QListWidgetItem *unitBeforeItem[unitStrList.size()];
    QListWidgetItem *unitAfterItem[unitStrList.size()];

    for (int i = 0; i < unitStrList.size(); i++) {

        // 获取汇率名称
        QMap<QString, QString>::iterator it;
        QString itemName;

        // 筛选需要显示的货币
        QString locale = QLocale::system().name();
        if (locale == "zh_CN") {
            if (currencyInfoCN.contains(unitStrList[i])) {

                it = currencyInfoCN.find(unitStrList[i]);
                if (it != currencyInfoCN.end()) {
                    itemName = it.value();
                } else {
                    continue;
                }
            } else {
                continue;
            }
        } else if (locale == "en_US") {
            if (currencyInfoUS.contains(unitStrList[i])) {

                it = currencyInfoUS.find(unitStrList[i]);
                if (it != currencyInfoUS.end()) {
                    itemName = it.value();
                } else {
                    continue;
                }
            } else {
                continue;
            }
        }

        unitBeforeItem[i] = new QListWidgetItem(unitListBef->getListWidget(), i);
        unitAfterItem[i] = new QListWidgetItem(unitListAft->getListWidget(), i);
        unitBeforeItem[i]->setSizeHint(QSize(240, 36));
        unitAfterItem[i]->setSizeHint(QSize(240, 36));
        unitBeforeItem[i]->setText(itemName + " " + unitStrList[i]);
        unitAfterItem[i]->setText(itemName + " " + unitStrList[i]);
        unitBeforeItem[i]->setData(Qt::DisplayRole + TAG_INFO, unitStrList[i]);
        unitAfterItem[i]->setData(Qt::DisplayRole + TAG_INFO, unitStrList[i]);

        unitListBef->insertItem(i, unitBeforeItem[i]);
        unitListAft->insertItem(i, unitAfterItem[i]);
    }

    unitListBef->setSpacing(2);
    unitListAft->setSpacing(2);

    // 默认汇率选择人民币和美元
    unitListBef->setCurrentRow(12);
    unitListAft->setCurrentRow(63);

    return;
}

/* 将正常计算结果 乘以汇率 进行转换 */
void ToolModelOutput::unitConversion()
{
    QString strBefore = this->toolLabBef->text().remove(QRegExp(","));
    strBefore.replace("×", "*");
    strBefore.replace("÷", "/");
    strBefore.replace(SUB, "-");

    /* 判断获取的表达式是否正常 */
    /* 之前的计算已经进行判断 , 此处判断表达式中含有数字 则认为正常 , 目的在与 排除 inf Error 等表示错误的表达式 */
    bool flag = false;
    std::string stdStr = strBefore.toStdString();
    const char *cStr = stdStr.c_str();
    while (*cStr != '\0') {
        if (*cStr >= '0' && *cStr <= '9') {
            flag = true;
            break;
        }
        cStr++;
    }

    if (!flag) {
        return;
    }

    /* 乘以汇率 */
    double douResult = calculator(calculator(strBefore) + "*" + QString::number(toolDouRate)).toDouble();

    QString strResult = QString::number(douResult);

    if (strResult.contains("inf")) {
        strResult = tr("Error!");
    }

    this->toolLabAft->setText(strResult);

    return;
}

// 单位换算历史记录转换
QString ToolModelOutput::unitConvHistory(QString hisText)
{
    QString resHisText;

    hisText.replace("×", "*");
    hisText.replace("÷", "/");
    hisText.replace(SUB, "-");

    /* 默认使用人民币/美元汇率 */
    if (toolDouRate == 0) {
        toolDouRate = 0.15;
    }

    QStringList singerHisList = (hisText).split("=");
    QString dataBef = singerHisList[singerHisList.size() - 1].remove(QRegExp(",")).remove("\n");
    double douResult = calculator(calculator(dataBef) + "*" + QString::number(toolDouRate)).toDouble();
    QString newHisText =
        dataBef + " " + toolRateSymbBef + " = " + QString::number(douResult) + " " + toolRateSymbAft + "\n";

    toolDisHistory.append(newHisText);

    // 获取历史记录
    int size = toolDisHistory.size();
    int hisIndex = (size - 4 >= 0) ? (size - 4) : 0;
    for (int i = hisIndex; i < size; i++) {
        resHisText = resHisText + toolDisHistory.at(i);
    }

    // 去除末尾换行符
    resHisText.chop(1);

    return resHisText;
}

// 汇率更新函数
void ToolModelOutput::updateRate()
{
    // 暂时隐藏
    //    toolIconUpdate->setEnabled(false);

    //    updateRateThread = new UpdateRateThread();

    //    connect(updateRateThread, &UpdateRateThread::isDone, this, &ToolModelOutput::dealDone);

    //    updateRateThread->start();
    // 更新界面的数据 时间 汇率
    QDateTime date = QDateTime::currentDateTime();
    QString strTime = date.toString("yyyy.MM.dd hh:mm");

    toolLabTime->setText(strTime);
}

void ToolModelOutput::defUpdateRate()
{
    if (m_firstLoad) {
        m_firstLoad = false;

        QString strRateAll =
            "{\"base\":\"CNY\",\"date\":\"2022-08-31\",\"time_last_updated\":1661904002,\"rates\":{\"CNY\":1,"
            "\"AED\":0.532,\"AFN\":12.79,\"ALL\":16.96,\"AMD\":58.69,\"ANG\":0.259,\"AOA\":63.56,\"ARS\":20.04,\"AUD"
            ":0.21,\"AWG\":0.259,\"AZN\":0.246,\"BAM\":0.283,\"BBD\":0.29,\"BDT\":13.68,\"BGN\":0.283,\"BHD"
            ":0.0544,\"BIF\":293.57,\"BMD\":0.145,\"BND\":0.202,\"BOB\":1,\"BRL\":0.73,\"BSD\":0.145,\"BTN\":11.51,"
            "\"BWP"
            ":1.86,\"BYN\":0.368,\"BZD\":0.29,\"CAD\":0.189,\"CDF\":290.88,\"CHF\":0.141,\"CLP\":127.83,\"COP"
            ":632.2,\"CRC\":91.77,\"CUP\":3.48,\"CVE\":15.94,\"CZK\":3.55,\"DJF\":25.73,\"DKK\":1.08,\"DOP\":7.72,\"DZD"
            ":20.38,\"EGP\":2.78,\"ERN\":2.17,\"ETB\":7.62,\"EUR\":0.145,\"FJD\":0.32,\"FKP\":0.124,\"FOK\":1.08,\"GBP"
            ":0.124,\"GEL\":0.422,\"GGP\":0.124,\"GHS\":1.48,\"GIP\":0.124,\"GMD\":7.95,\"GNF\":1248.08,\"GTQ"
            ":1.12,\"GYD\":30.25,\"HKD\":1.14,\"HNL\":3.56,\"HRK\":1.09,\"HTG\":16.75,\"HUF\":58.34,\"IDR"
            ":2140.06,\"ILS\":0.479,\"IMP\":0.124,\"INR\":11.51,\"IQD\":211.05,\"IRR\":6107.09,\"ISK\":20.52,\"JEP"
            ":0.124,\"JMD\":21.82,\"JOD\":0.103,\"JPY\":20.05,\"KES\":17.45,\"KGS\":11.9,\"KHR\":593.1,\"KID"
            ":0.21,\"KMF\":71.12,\"KRW\":195,\"KWD\":0.0434,\"KYD\":0.121,\"KZT\":68.73,\"LAK\":2520.87,\"LBP"
            ":218.29,\"\LKR\":51.24,\"LRD\":22.27,\"LSL\":2.45,\"\LYD\":0.714,\"MAD\":1.53,\"\MDL\":2.8,\"MGA"
            ":594.64,\"MKD\":8.92,\"MMK\":302.63,\"MNT\":461.08,\"MOP\":1.17,\"MRU\":5.45,\"MUR\":6.37,\"MVR"
            ":2.23,\"MWK\":150.35,\"MXN\":2.9,\"MYR\":0.649,\"MZN\":9.23,\"NAD\":2.45,\"NGN\":61.17,\"NIO\":5.2,\"NOK"
            ":1.42,\"NPR\":18.42,\"NZD\":0.236,\"OMR\":0.0557,\"PAB\":0.145,\"PEN\":0.554,\"PGK\":0.51,\"PHP"
            ":8.12,\"PKR\":31.84,\"PLN\":0.682,\"PYG\":995.19,\"QAR\":0.527,\"RON\":0.702,\"RSD\":16.95,\"RUB"
            ":8.79,\"RWF\":155.47,\"SAR\":0.543,\"SBD\":1.18,\"SCR\":1.87,\"\SDG\":81.92,\"SEK\":1.54,\"SGD\":0.202,"
            "\"SHP"
            ":0.124,\"SLE\":2.07,\"SLL\":2067.73,\"SOS\":82.2,\"SRD\":3.54,\"SSP\":93.98,\"STN\":3.54,\"SYP"
            ":364.07,\"SZL\":2.45,\"\THB\":5.27,\"TJS\":1.48,\"TMT\":0.507,\"TND\":0.423,\"TOP\":0.341,\"TRY\":2.63,"
            "\"TTD"
            ":0.983,\"TVD\":0.21,\"TWD\":4.4,\"TZS\":337.14,\"UAH\":5.38,\"UGX\":551.16,\"USD\":0.145,\"UYU\":5.85,"
            "\"UZS"
            ":1584.59,\"VES\":1.14,\"VND\":3394.8,\"VUV\":17.16,\"WST\":0.394,\"XAF\":94.82,\"XCD\":0.391,\"XDR"
            ":0.111,\"XOF\":94.82,\"XPF\":17.25,\"YER\":36.25,\"ZAR\":2.45,\"ZMW\":2.31,\"ZWL\":78.55}}";

        // 格式化处理汇率信息字符串键值对
        strRateList = strRateAll.split(QRegExp("[{} :,\"\n]"));
        strRateList.removeAll("");

        for (int i = 0; i < 7; i++) {
            strRateList.removeAt(0);
        }

        // 获取汇率单位标识
        QString strRateKey = strRateList.at(0);
        for (int i = 2; i < strRateList.size(); i++) {
            if (i % 2 == 0) {
                strRateKey.append(",");
                strRateKey.append(strRateList.at(i));
            }
        }

        // 初始化选择列表的汇率选项
        initUnitList(strRateKey);
    }

    // 更新界面的数据 时间 汇率
    QDateTime date = QDateTime::currentDateTime();
    QString strTime = date.toString("yyyy.MM.dd hh:mm");

    QString rateNameBef = toolRateSymbBef;
    QString rateNameAft = toolRateSymbAft;

    QString labelRate = "1 " + rateNameBef + " = " + QString::number(toolDouRate, 'f', 2) + " " + rateNameAft;
    toolLabTime->setText(strTime);
    toolLabRate->setText(labelRate);

    updateRateName();
}

/* 控制换算前的单位列表 */
void ToolModelOutput::unitListBefShow()
{
    if (!unitListAft->isHidden()) {
        unitListAft->hide();
    }
    if (unitListBef->isHidden()) {

        int b_x;
        if(isHaWeiKe){
            b_x = toolUnitBefWid->x() - 280;
        }else{
            b_x = toolUnitBefWid->x() + toolUnitBefWid->width();
        }
        int b_y = toolUnitBefWid->y();
        if(this->parentWidget()){
            QPoint gloabalPos = this->parentWidget()->mapToGlobal(QPoint(0,0));
            unitListBef->setGeometry(QRect(gloabalPos.x()+b_x,gloabalPos.y()+b_y,280,410));
        } else{
        unitListBef->setGeometry(QRect(b_x, b_y, 280, 410));
        }

        unitListBef->show();
//        unitListBef->raise();
//        unitListBef->setFocus();

        toolUnitBefWid->setBackgroundRole(QPalette::Window);
    } else {
        unitListBef->hide();
        toolUnitBefWid->setBackgroundRole(QPalette::Base);
    }
}

/* 控制换算后的单位列表 */
void ToolModelOutput::unitListAftShow()
{
    if (!unitListBef->isHidden()) {
        unitListBef->hide();
    }
    if (unitListAft->isHidden()) {
        int a_x;
        if(isHaWeiKe){
            a_x = toolUnitAftWid->x() - 280;
        }else{
            a_x = toolUnitAftWid->x() + toolUnitAftWid->width();
        }
        int a_y = toolUnitAftWid->y();
        if(this->parentWidget()){
            QPoint globalPos = this->parentWidget()->mapToGlobal(QPoint(0,0));
            unitListAft->setGeometry(QRect(globalPos.x()+a_x,globalPos.y()+a_y,280,410));
        } else{
        unitListAft->setGeometry(QRect(a_x, a_y, 280, 410));
        }
        unitListAft->show();
//        unitListAft->raise();
//        unitListAft->setFocus();
    } else {
        unitListAft->hide();
    }
}

void ToolModelOutput::listItemClicked(QListWidgetItem *item)
{
    if (unitListAft->isHidden()) {
        toolRateSymbBef = item->data(Qt::DisplayRole + TAG_INFO).toString();
        updateRateName();
        unitListBef->hide();
    } else {
        toolRateSymbAft = item->data(Qt::DisplayRole + TAG_INFO).toString();
        updateRateName();
        unitListAft->hide();
    }
}

void ToolModelOutput::dealDone(QStringList list)
{
    if (list.isEmpty()) {
        return;
    }
    strRateList = list;
    // 获取汇率单位标识
    QString strRateKey = strRateList.at(0);
    for (int i = 2; i < strRateList.size(); i++) {
        if (i % 2 == 0) {
            strRateKey.append(",");
            strRateKey.append(strRateList.at(i));
        }
    }

    // 初始化选择列表的汇率选项
    initUnitList(strRateKey);

    // 更新界面的数据 时间 汇率
    QDateTime date = QDateTime::currentDateTime();
    QString strTime = date.toString("yyyy.MM.dd hh:mm");


    QString rateNameBef = toolRateSymbBef;
    QString rateNameAft = toolRateSymbAft;

    QString labelRate = "1 " + rateNameBef + " = " + QString::number(toolDouRate, 'f', 2) + " " + rateNameAft;
    toolLabTime->setText(strTime);
    toolLabRate->setText(labelRate);

    updateRateName();

    toolIconUpdate->setEnabled(true);

    //停止线程
    updateRateThread->quit();

    //等待线程处理完手头工作
    updateRateThread->wait();
}

// 根据符号更新货币名称并显示
void ToolModelOutput::updateRateName()
{
    /* 获取汇率索引值 */
    int idxRateBef = strRateList.indexOf(toolRateSymbBef) + 1;
    int idxRateAft = strRateList.indexOf(toolRateSymbAft) + 1;

    /* 获取汇率比率 */
    toolDouRate = (strRateList[idxRateAft]).toDouble() / (strRateList[idxRateBef]).toDouble();

    /* 获取汇率名称 */
    QMap<QString, QString>::iterator it;

    QString locale = QLocale::system().name();

    if (locale == "zh_CN") {
        it = currencyInfoCN.find(toolRateSymbBef);
        if (it != currencyInfoCN.end()) {
            toolRateNameBef = it.value();
        }

        it = currencyInfoCN.find(toolRateSymbAft);
        if (it != currencyInfoCN.end()) {
            toolRateNameAft = it.value();
        }
    } else if (locale == "en_US") {
        it = currencyInfoUS.find(toolRateSymbBef);
        if (it != currencyInfoUS.end()) {
            toolRateNameBef = it.value();
        }

        it = currencyInfoUS.find(toolRateSymbAft);
        if (it != currencyInfoUS.end()) {
            toolRateNameAft = it.value();
        }
    }

    // 更新汇率比率显示
    QString labelRate = toolLabRate->text();
    labelRate = "1 " + toolRateSymbBef + " = " + QString::number(toolDouRate, 'f', 2) + " " + toolRateSymbAft;
    toolLabRate->setText(labelRate);

    // 更新汇率名称和符号显示
    toolLabUnitBef->setText(toolRateNameBef + "\n" + toolRateSymbBef);
    toolLabUnitAft->setText(toolRateNameAft + "\n" + toolRateSymbAft);

    QFont font(toolLabUnitBef->font());
    font.setPixelSize(18); // QFont像素大小设置为18，然后再次设置到QLabel中
    toolLabUnitBef->setFont(font);
    toolLabUnitAft->setFont(font);

    QFontMetrics fontmts = toolLabUnitBef->fontMetrics();
    int dif = fontmts.width(toolRateNameBef) - toolLabUnitBef->width();
    if (dif > 0) {
        QString str = fontmts.elidedText(toolRateNameBef, Qt::ElideRight, toolLabUnitBef->width());
        toolLabUnitBef->setText(str + "\n" + toolRateSymbBef);
        toolLabUnitBef->setToolTip(toolRateNameBef);
    }

    fontmts = toolLabUnitAft->fontMetrics();
    dif = fontmts.width(toolRateNameAft) - toolLabUnitAft->width();
    if (dif > 0) {
        QString str = fontmts.elidedText(toolRateNameAft, Qt::ElideRight, toolLabUnitAft->width());
        toolLabUnitAft->setText(str + "\n" + toolRateSymbAft);
        toolLabUnitAft->setToolTip(toolRateNameAft);
    }

    // 更新汇率换算结果
    unitConversion();
}

// 换算器按钮界面
ToolModelButton::ToolModelButton(QWidget *parent) : QWidget(parent)
{
    // 初始化组件
    this->setWidgetUi();
}

// 初始化组件
void ToolModelButton::setWidgetUi()
{
    for (int i = 0; i < 10; i++) {
        btnNum[i] = new BasicButton(this);
        btnNum[i]->setText(QString::number(i));
        btnNum[i]->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
        btnNum[i]->setIconSize(QSize(106, 62));
        btnNum[i]->setProperty("useButtonPalette", true);
    }

    btnClear = new BasicButton(this);
    btnPer = new BasicButton(this);
    btnDelete = new BasicButton(this);

    btnDiv = new BasicButton(this);
    btnMulti = new BasicButton(this);
    btnSub = new BasicButton(this);
    btnAdd = new BasicButton(this);
    btnEqual = new BasicButton(this);

    btnPoint = new BasicButton(this);

    m_picturetowhite = new PictureToWhite();

    // 设置按钮的显示文本
    QString btnList = "C,÷,×,B,ｰ,+,=,%,.";
    QStringList btnNameList = btnList.split(",");
    int index = 0;

    btnClear->setText(btnNameList[index++]);
    btnDiv->setText(btnNameList[index++]);
    btnMulti->setText(btnNameList[index++]);
    btnDelete->setText(btnNameList[index++]);
    btnSub->setText(btnNameList[index++]);
    btnAdd->setText(btnNameList[index++]);
    btnEqual->setText(btnNameList[index++]);
    btnPer->setText(btnNameList[index++]);
    btnPoint->setText(btnNameList[index++]);

    for (int i = 0; i < 10; i++) {
        btnNum[i]->setIcon(QIcon(":/image/newIcon/standard/btnNum" + QString::number(i) + ".svg"));
    }

    btnClear->setIcon(QIcon(":/image/newIcon/standard/btnClear.svg"));
    btnDiv->setIcon(QIcon(":/image/newIcon/standard/btnDiv.svg"));
    btnMulti->setIcon(QIcon(":/image/newIcon/standard/btnMulti.svg"));
    btnDelete->setIcon(QIcon(":/image/newIcon/standard/btnDelete.svg"));
    btnSub->setIcon(QIcon(":/image/newIcon/standard/btnSub.svg"));
    btnAdd->setIcon(QIcon(":/image/newIcon/standard/btnAdd.svg"));
    btnEqual->setIcon(QIcon(":/image/newIcon/standard/btnEqual.svg"));
    btnPer->setIcon(QIcon(":/image/newIcon/standard/btnPer.svg"));
    btnPoint->setIcon(QIcon(":/image/newIcon/standard/btnPoint.svg"));

    btnClear->setIconSize(QSize(106, 62));
    btnDiv->setIconSize(QSize(106, 62));
    btnMulti->setIconSize(QSize(106, 62));
    btnDelete->setIconSize(QSize(85, 50));
    btnSub->setIconSize(QSize(106, 62));
    btnAdd->setIconSize(QSize(106, 62));
    btnEqual->setIconSize(QSize(106, 62));
    btnPer->setIconSize(QSize(106, 62));
    btnPoint->setIconSize(QSize(106, 62));

    // 设置按钮自适应放缩
    btnClear->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    btnDiv->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    btnMulti->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    btnDelete->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    btnSub->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    btnAdd->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    btnEqual->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    btnPer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    btnPoint->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);

    btnClear->setProperty("useButtonPalette", true);
    btnDiv->setProperty("useButtonPalette", true);
    btnMulti->setProperty("useButtonPalette", true);
    btnDelete->setProperty("useButtonPalette", true);
    btnSub->setProperty("useButtonPalette", true);
    btnAdd->setProperty("useButtonPalette", true);
    btnPer->setProperty("useButtonPalette", true);
    btnPoint->setProperty("useButtonPalette", true);

    btnEqual->setProperty("isImportant", true);

    // 将按钮进行网格布局
    QGridLayout *btnLayout = new QGridLayout();
    btnLayout->addWidget(btnClear, 0, 0, 1, 1);
    btnLayout->addWidget(btnPer, 0, 1, 1, 1);
    btnLayout->addWidget(btnDelete, 0, 2, 1, 1);
    btnLayout->addWidget(btnDiv, 0, 3, 1, 1);
    btnLayout->addWidget(btnMulti, 1, 3, 1, 1);
    btnLayout->addWidget(btnSub, 2, 3, 1, 1);
    btnLayout->addWidget(btnAdd, 3, 3, 1, 1);
    btnLayout->addWidget(btnPoint, 4, 2, 1, 1);
    btnLayout->addWidget(btnEqual, 4, 3, 1, 1);

    // 数字按钮布局
    // btnLayout->addWidget(btnDZero, 4, 0, 1, 1);
    btnLayout->addWidget(btnNum[0], 4, 0, 1, 2);
    for (int i = 1; i < 10; i++) {
        btnLayout->addWidget(btnNum[i], 3 - (i - 1) / 3, (i - 1) % 3, 1, 1);
    }

    // 设置间距和背景样式
    btnLayout->setSpacing(2);
    btnLayout->setMargin(1);
    btnLayout->setContentsMargins(4, 0, 4, 4);

    // this->setFixedHeight(320);
    this->setLayout(btnLayout);
}

/* 键盘响应事件 */
void ToolModelButton::keyPressEvent(QKeyEvent *event)
{
    switch (event->key()) {
    case Qt::Key_Period:
        btnPoint->click();
        break;
    case Qt::Key_0:
        btnNum[0]->click();
        break;
    case Qt::Key_1:
        btnNum[1]->click();
        break;
    case Qt::Key_2:
        btnNum[2]->click();
        break;
    case Qt::Key_3:
        btnNum[3]->click();
        break;
    case Qt::Key_4:
        btnNum[4]->click();
        break;
    case Qt::Key_5:
        btnNum[5]->click();
        break;
    case Qt::Key_6:
        btnNum[6]->click();
        break;
    case Qt::Key_7:
        btnNum[7]->click();
        break;
    case Qt::Key_8:
        btnNum[8]->click();
        break;
    case Qt::Key_9:
        btnNum[9]->click();
        break;
    case Qt::Key_Plus:
        btnAdd->click();
        break;
    case Qt::Key_Minus:
        btnSub->click();
        break;
    case Qt::Key_Asterisk:
        btnMulti->click();
        break;
    case Qt::Key_Slash:
        btnDiv->click();
        break;
    case Qt::Key_Escape:
        btnClear->click();
        break;
    case Qt::Key_Percent:
        btnPer->click();
        break;
    case Qt::Key_Backspace:
        btnDelete->click();
        break;
    case Qt::Key_Enter:
        btnEqual->click();
        break;
    case 16777220:
        btnEqual->click();
        break;
    case 0x3d:
        btnEqual->click();
        break;
    default:
        return QWidget::keyPressEvent(event);
    }

    return;
}

UnitListWidget::UnitListWidget(QWidget *parent)
    : QWidget(parent)
    , m_listwidget(new QListWidget)
{
//    QGraphicsDropShadowEffect *shadowEffect = new QGraphicsDropShadowEffect(this);
//    shadowEffect->setOffset(0, 0);
//    shadowEffect->setColor(QGuiApplication::palette().color(QPalette::BrightText));
//    shadowEffect->setBlurRadius(8);
//    setGraphicsEffect(shadowEffect);

    m_listwidget->setFrameShape(QFrame::NoFrame);
    QPalette palette = m_listwidget->palette();
    palette.setColor(QPalette::Base, QColor(Qt::transparent));
    m_listwidget->setPalette(palette);
    connect(m_listwidget, &QListWidget::itemClicked, this, &UnitListWidget::itemClicked);

    QHBoxLayout *hBoxLayout = new QHBoxLayout;
    hBoxLayout->setContentsMargins(5,10,2,10);
    hBoxLayout->addWidget(m_listwidget);
    setLayout(hBoxLayout);
    setAttribute(Qt::WA_TranslucentBackground,true);
    this->setWindowFlags(Qt::Popup | Qt::FramelessWindowHint);
}

UnitListWidget::~UnitListWidget()
{
    /* nothing to do */
}

void UnitListWidget::insertItem(int row, QListWidgetItem *item)
{
    m_listwidget->insertItem(row, item);
}

void UnitListWidget::clear(void)
{
    m_listwidget->clear();
}

void UnitListWidget::setSpacing(int space)
{
    m_listwidget->setSpacing(space);
}

void UnitListWidget::setCurrentRow(int row)
{
    m_listwidget->setCurrentRow(row);
}

QListWidget *UnitListWidget::getListWidget(void)
{
    return m_listwidget;
}

void UnitListWidget::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event);

    QStyleOption opt;
    opt.init(this);

    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);
    painter.setPen(Qt::NoPen);
    painter.setBrush(QGuiApplication::palette().color(QPalette::Base));

    painter.drawRoundedRect(rect(), 8, 8);
    style()->drawPrimitive(QStyle::PE_FrameMenu,&opt,&painter,this);
}

//void UnitListWidget::focusOutEvent(QFocusEvent *event)
//{
//    if (hasFocus())
//        return;

//    hide();
//}

void UpdateRateThread::run()
{
    // 访问汇算换算api
    QString strUrl = "https://api.exchangerate-api.com/v4/latest/CNY";
    QNetworkAccessManager manager;
    QNetworkRequest netRequest;
    QNetworkReply *netReply;
    QEventLoop loop;
    m_timer = new QTimer();
    connect(m_timer, SIGNAL(timeout()), &loop, SLOT(quit()));
    m_timer->start(10000);

    netRequest.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
    netRequest.setUrl(QUrl(strUrl));
    netReply = manager.get(netRequest);

    connect(netReply, SIGNAL(finished()), &loop, SLOT(quit()));
    loop.exec();

    m_timer->stop();

    if (netReply->error() != QNetworkReply::NoError) {
        return;
    }

    QString strRateAll = netReply->readAll();

    if (strRateAll == "") {
        return;
    }

    QStringList strList;
    QByteArray rateJsonBuf = strRateAll.toUtf8();
    QJsonDocument rateJsonDoc = QJsonDocument::fromJson(rateJsonBuf);
    if (rateJsonDoc.isObject()) {
        QJsonValue rateJsonValue = rateJsonDoc.object().value("rates");
        QJsonObject rateJsonObj = rateJsonValue.toObject();
        QStringList rateKeyList = rateJsonObj.keys();

        for (int i = 0; i < rateKeyList.size(); i++) {
            strList << rateKeyList.value(i);
            double rate = rateJsonObj.value(rateKeyList.value(i)).toDouble();
            strList << QString::number(rate);
        }
    }

    emit isDone(strList);

    manager.deleteLater();
    netReply->deleteLater();
    loop.deleteLater();
}
