/*
 * 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 "clock.h"
#include "ui_clock.h"
#include <QMessageBox>
#include "fieldvalidutil.h"
#include <QThread>
#include "mediaplayerpool.h"
#include <QLibraryInfo>
#include "coreplayer/playcontroller.h"
#include "kwidget.h"
#include "kwindowbuttonbar.h"
#include <QDBusReply>
#include "configutil.h"
#include "kwindowsystem.h"
#include <QScrollBar>
#include <kaboutdialog.h>
#include "windowmanager/windowmanager.h"
#include "dbusnoticeshowagainadaptor.h"
#include <QDebug>
using std::string;
using clockInterface::ReturnMsg;
using clockInterface::STATUS_CODE;
using namespace kdk;

extern void qt_blurImage(QImage &blurImage, qreal radius, bool quality, int transposed);
const double PI=3.141592;


#define SWITCH_BTN_HIGHLIGHT_BACK_COLOR 61,107,229,255

const static int DIALOG_MOVE_WIDTH = 24;
const static int DIALOG_WIDTH = 340;

Clock::Clock(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Clock)
{
    //异步初始化
//    MediaPlayerPool::getInstance();
    music = new QMediaPlayer();
    //右键菜单，选择”create new translation file“；项目中会添加一个以”.ts“为后缀的文件，例如”testtranslator_zh.ts“;
    //使用Qt Linguist打开该文件，就可以为指定的字符串设置译文；
    //在相应的“.ts”文件的右键菜单中点击“lupdate”项，才会更新。
    //翻译完成后，点击”文件“菜单下的”发布“项，就会生成.qm文件；
    QTranslator *translator = new QTranslator;
    // Get system locale
    //切换英文
    QLocale en_us = QLocale("en_US");
    QLocale bo_cn = QLocale("bo_CN");
    QLocale current = QLocale();
    if (translator->load(current, QLatin1String("ukui-clock"), QLatin1String("_"), QLatin1String("/usr/share/ukui-clock/ukui31"))){
        QApplication::installTranslator(translator);
    }
    else{
        qDebug() << "cannot load translator ukui-clock_" << QLocale::system().name() << ".qm!";
    }
    //加载sdk翻译
    QTranslator *translator1 = new QTranslator;
    if (translator1->load(current, QLatin1String("gui"), QLatin1String("_"), QLatin1String(":translations"))){
        QApplication::installTranslator(translator1);
    }
    else{
        qDebug() << "cannot load translator gui_" << QLocale::system().name() << ".qm!";
    }
    //加载Qt翻译

    QTranslator * qtTranslator = new QTranslator;
    QString translationsPath = QLibraryInfo::location(QLibraryInfo::TranslationsPath);
    if(qtTranslator->load(QLocale(), QStringLiteral("qt"), QLatin1String("_"), translationsPath)){
        QApplication::installTranslator(qtTranslator);
    }else{
        qDebug()<<"dbq- cannot load qt"<< QLocale::system().name() << ".qm!";
    }

    //ui 构造代码
    ui->setupUi(this);
    //重新构建组件
    //闹钟、倒计时、秒表按钮
    switchWidget = new QWidget(ui->titileWidget);
    // 闹钟
    switchClock = new KPushButton(switchWidget);
    // 倒计时
    switchCountdown = new KPushButton(switchWidget);
    // 秒表
    switchStopwatch = new KPushButton(switchWidget);

    mainWidget = new QStackedWidget(ui->titileWidget);
    // 倒计时页面
    countdownPage = new QWidget(this->mainWidget);
    // 闹钟页面
    alarmPage = new QWidget(this->mainWidget);
    alarmPage->setObjectName("alarmPage");
    alarmPage->setToolTip(alarmPage->objectName());

    // 秒表页面
    stopwatchPage = new QWidget(this->mainWidget);
    addAlarmPage = new QWidget(this->mainWidget);
      //绑定页面
    mainWidget->addWidget(countdownPage);
    mainWidget->addWidget(alarmPage);
    mainWidget->addWidget(stopwatchPage);
    mainWidget->addWidget(addAlarmPage);
    mainWidget->setCurrentIndex(1);

    countdownStackedW = new QStackedWidget(countdownPage);
    // 倒计时设置页面
    countdownSetPage = new QWidget(countdownStackedW);
    // 倒计时页面
    countdownRunPage = new Countdown_Animation(countdownStackedW);
    countdownStackedW->addWidget(countdownSetPage);
    countdownStackedW->addWidget(countdownRunPage);
    countdownStackedW->setCurrentIndex(0);
    // 倒计时-开始
    startCountSingle = new QPushButton(countdownSetPage);
    alarmWidget = new QWidget(countdownRunPage);
    btnWidget = new QWidget(countdownRunPage);
    timeWidget = new QWidget(countdownRunPage);
    tinyWidget = new QWidget(countdownRunPage);
    // 倒计时-run-闹铃
    countdownAlarmIcon = new QLabel(alarmWidget);
    // 倒计时-run-时间
    countdownAlarmTime = new QLabel(alarmWidget);
    startCountdownBtn = new QPushButton(btnWidget);
    suspendCountdownBtn = new QPushButton(btnWidget);
    // 倒计时-数字
    remainTime = new QLabel(timeWidget);
    tinyWindowBtn = new QPushButton(tinyWidget);
    // 闹钟-添加
    addAlarmBtn = new QPushButton(this->alarmPage);
    alarmListWidget = new QListWidget(alarmPage);
    // 闹钟-无闹钟
    noAlarm = new QLabel(alarmPage);
    // 闹钟-无闹钟
    noAlarmIcon = new QLabel(alarmPage);


    //秒表页面
    ringBtn = new QPushButton(stopwatchPage);
    startStopwatch = new QPushButton(stopwatchPage);
    timeListWidget = new QListWidget(stopwatchPage);
    timeShowBig = new QLabel(stopwatchPage);
    timeShowSmall = new QLabel(stopwatchPage);
    timeShowBig->setText("00:00:00");
    timeShowSmall->setText("00:00:00");

    //闹钟编辑页面
    editAlarmPage = new QWidget(addAlarmPage);
    cancelbtnOnEditAlarm = new QPushButton(editAlarmPage);
    saveBtnOnEditAlarm = new QPushButton(editAlarmPage);
    timeFormatOnTimeWheel = new QLabel(editAlarmPage);

    //主屏信息
    primaryManager = new PrimaryManager();

    inidata();
    bool onTablet = GsettingSubject::getInstance()->getOnTablet();
    bool rotations = GsettingSubject::getInstance()->getRotations();
    iniframe(onTablet,rotations);
    currentTheme = new theme();
    //创建或打开数据库
    clock_sql::createConnection();
     //in order to use the same world in English
    this->setWindowTitle(tr(CLOCK_TITLE_NAME));
    ui->titileWidget->setWidgetName(tr(CLOCK_TITLE_NAME));
    //创建用户手册dbus客户端
    createUserGuideDebusClient();
    mousePressed = 0;
    //设置数据库
    model_setup = clock_sql::getSetupTable(this);
    model_setup->select();
    //创建数据库
    m_bellQueryModel = clock_sql::getBellTable(this);
    bellIni();
    //闹钟按钮图片初始化
    buttonImageInit();
    //稍后提醒接口
    publishDbusNoticeShowAgain();
    //倒计时 运行光圈页初始化
    CountdownInit();
    //秒表初始化
    stopwatchInit();
    //闹钟页初始化
    clockInit();
    setupInit();
    /*实现鼠标左键滑动效果
    *Realize the sliding effect of left mouse button*/
    alarmListWidget -> setFrameShape(QListWidget::NoFrame);
    timeListWidget -> setFrameShape(QListWidget::NoFrame);
    QScroller::grabGesture(alarmListWidget,QScroller::LeftMouseButtonGesture); /*设置鼠标左键拖动  Set left mouse drag*/
    QScroller::grabGesture(timeListWidget,QScroller::LeftMouseButtonGesture); /*设置鼠标左键拖动  Set left mouse drag*/
    alarmListWidget -> setVerticalScrollMode(QAbstractItemView::ScrollPerPixel);  /*设置像素级滑动    Set pixel level slide*/
    timeListWidget -> setVerticalScrollMode(QAbstractItemView::ScrollPerPixel); /*设置像素级滑动  Set pixel level slide*/
    alarmListWidget->setProperty("contextMenuPolicy", Qt::CustomContextMenu);    /*重要：设置QListWidget的contextMenuPolicy属性，不然不能显示右键菜单*/
//    alarmListWidget ->setGridSize(QSize(340+8, 108+15));
//    timeListWidget ->setGridSize(QSize(340, 58+10));
    alarmListWidget->setProperty("drawScrollBarGroove", false);
    timeListWidget->setProperty("drawScrollBarGroove", false);
    //闹钟居中
    //move((m_pSreenInfo->m_screenWidth - this->width() + m_pSreenInfo->m_nScreen_x )/2, (m_pSreenInfo->m_screenHeight - this->height())/2);
    utils = new Utils();
    utils->centerToScreen(this);
    //导航栏初始设置
    navigationBtnStyle(switchClock);
    switchClock->setToolTip(tr(CLOCK_TITLE_NAME));
    navigationBtnStyle(switchCountdown);
    switchCountdown->setToolTip(tr("Count down"));
    navigationBtnStyle(switchStopwatch);
    switchStopwatch->setToolTip(tr("Watch"));

    connect(switchCountdown, SIGNAL(clicked()), this, SLOT( CountdownPageSwitch ()));
    connect(switchClock, SIGNAL(clicked()), this, SLOT( AlarmPageSwitch ()));
    connect(switchStopwatch, SIGNAL(clicked()), this, SLOT( StopwatchPageSwitch ()));

     AlarmPageSwitch ();/*初始显示闹钟界面
                               Initial display alarm interface*/

    close_or_hide_page = new close_or_hide(this);

    shadow->installEventFilter(this);
    editAlarmPage->installEventFilter(this);
    alarmListWidget->installEventFilter(this);
    switchClock->installEventFilter(this);
    switchCountdown->installEventFilter(this);
    switchStopwatch->installEventFilter(this);

    //蓝色
    QPalette palette = suspendCountdownBtn->palette();
    QColor ColorPlaceholderText(248,163,76,255);
    QBrush brush3;
    brush3.setColor(ColorPlaceholderText);
    //主题框架1.0.6-5kylin2
    palette.setColor(QPalette::Highlight,QColor(248,163,76,255));
    palette.setColor(QPalette::Button,QColor(248,163,76,255));
    palette.setBrush(QPalette::ButtonText, QBrush(Qt::white));
    //多色按钮切换
//    ui->suspendCountdownBtn->setPalette(palette);
//    setSwitchHighlightColor(ui->suspendCountdownBtn);
    startCountSingle->setEnabled(false);
    countdownStackedW->setCurrentIndex(0);
    drawNoAlarmPrompt();//绘制无闹钟提示图标
    onMin_5btnClicked();//倒计时初始时间默认五分钟
    //字体设置
//    QString selfFont = Utils::loadFontFamilyFromTTF();
//    QFont f(selfFont);
    QFont f;
    f.setFamily("NotoSansCJKsc-Regular");
    f.setWeight(400);
    f.setPixelSize(38);
    timeShowBig->setFont(f);
    //监听主题
    settingsStyle();
    //主题框架1.0.6-5kylin2
    //配置重要按钮

    //添加
    addAlarmBtn->setProperty("isImportant", true);
    //新建闹钟保存
    saveBtnOnEditAlarm->setProperty("isImportant", true);
    //倒计时 滚轮页设置页，开始
    startCountSingle->setProperty("isImportant", true);
    //倒计时，运行页，开始结束
//    ui->count_stat->setProperty("isImportant", true);
    //秒表 开始结束
    startStopwatch->setProperty("isImportant", true);
//    倒计时 暂停继续
    suspendCountdownBtn->setProperty("isImportant", true);
    //倒计时 开始结束
    startCountdownBtn->setProperty("useButtonPalette", true);
    //闹钟编辑 取消
    cancelbtnOnEditAlarm->setProperty("useButtonPalette", true);
    //秒表 计次
    ringBtn->setProperty("useButtonPalette", true);
    //迷你窗口
    updateTinyBtn();
    //倒计时上的小闹钟
//    ui->countdownAlarmIcon->setProperty("useButtonPalette", true);

    iniWaylandWinId();
    //绘制闹钟列表
    updateAlarmClock();
}

Clock::~Clock()
{
    delete timer;
    delete timer_2;
    delete countdown_timer;
    delete model;
    delete model_setup;
    delete dialog_repeat;
    delete dialog_music;
    delete count_music_sellect;
    delete dialog_remind_late;
    delete countdownRunPage;
    delete countdownSetPage;
    delete ui;
    delete utils;
    delete primaryManager;
    delete alarmNoticeDialog;
    delete countdownNoticeDialog;
    delete tinycountdownDia;
    delete currentTheme;
}

void Clock::iniframe(bool tablet,bool rotations)
{
    double dpi = QGuiApplication::primaryScreen()->logicalDotsPerInch()/96;
    //主屏信息
    QRect deskRect = QApplication::desktop()->screenGeometry();
    int desktopX = deskRect.width();
    int desktopY = deskRect.height();
    if(tablet){
        int aa=desktopX;
        int bb=desktopY;
        if(!rotations){
            aa=qMax(desktopX,desktopY);
            bb=qMin(desktopX,desktopY);
        }else{
            aa=qMin(desktopX,desktopY);
            bb=qMax(desktopX,desktopY);
        }
        this->setFixedSize(aa,bb);
        //导航栏
        switchWidget->setGeometry(0,76,this->width(),80);
        switchClock->setFixedSize(QSize(72,72));
        switchCountdown->setFixedSize(QSize(72,72));
        switchStopwatch->setFixedSize(QSize(72,72));
        int iconwh = 36;
        switchClock->move(aa/2-iconwh*3-56,4);
        switchCountdown->move(aa/2-iconwh,4);
        switchStopwatch->move(aa/2+iconwh+56,4);


        //主页
        int HHHeight = 168;
        mainWidget->setGeometry(0,HHHeight,aa-32,bb-HHHeight);
        countdownPage->setGeometry(0,0,aa-156,bb-HHHeight);
        alarmPage->setGeometry(0,0,aa-32,bb-HHHeight);
        stopwatchPage->setGeometry(0,0,aa-156,bb-HHHeight);
        addAlarmPage->setGeometry(0,0,aa-78,bb-HHHeight);


        //倒计时页面
        countdownStackedW->setGeometry(0,0,aa-156,bb-HHHeight);
        countdownSetPage->setGeometry(0,0,aa-156,bb-HHHeight);
        countdownRunPage->setGeometry(0,0,aa-156,bb-HHHeight);
           //倒计时设置页面
        startCountSingle->resize(120,48);
        startCountSingle->move(aa/2-60,bb-168-64-48);
           //倒计时运行页面
        alarmWidget->setGeometry(aa/2-260,bb/2-HHHeight-60-8-40,530,80);
        btnWidget->setGeometry(0,bb-168-64-48,aa-156,bb-168);
        timeWidget->setGeometry(aa/2-260,bb/2-HHHeight-60,530,120);
        tinyWidget->setGeometry(aa/2-260,bb/2-HHHeight+60+48,530,60);

        countdownAlarmIcon->setGeometry(150+80,22,24,26);
        countdownAlarmTime->setGeometry(168+81,9,60,52);
        QFont f;
        f.setFamily("NotoSansCJKsc-Regular");
        f.setPixelSize(24);
        countdownAlarmTime->setFont(f);


        startCountdownBtn->setGeometry(aa/2-28-120,0,120,48);
        suspendCountdownBtn->setGeometry(aa/2+28,0,120,48);

        remainTime->setGeometry(102,9,316,112);
        QFont ff;
        ff.setFamily("NotoSansCJKsc-Regular");
        ff.setWeight(400);
        ff.setPixelSize(76);
        remainTime->setFont(ff);

        tinyWindowBtn->setGeometry(238,9,48,48);
             //倒计时光圈
        countdownRunPage->countdownRunRoundBar->setGeometry(aa/2-250-94,bb/2-460,800,800);

        //闹钟主页
        addAlarmBtn->setGeometry(aa/2-60,bb-280,120,48);
        int numX = (aa-32)/368*dpi;
        int numY = (bb-280)/168*dpi;
        int posX = (aa-numX*368*dpi)/2;
        int HeightY = numY*168*dpi;
        alarmListWidget->setGeometry(posX,8,aa-posX-8,HeightY);
        alarmListWidget->setGridSize(QSize(360+8,160+8));
        noAlarm->setGeometry(aa/2-70,320,140,31);
        noAlarmIcon->setGeometry(aa/2-70,110,256,256);

        //秒表页面
        ringBtn->setGeometry(aa/2-28-120,bb-280,120,48);
        startStopwatch->setGeometry(aa/2+28,bb-280,120,48);
        timeListWidget->setGeometry(aa/2-320,109,656,646/dpi);
        timeListWidget ->setGridSize(QSize(640, 58+10));
        if(!runorsuspend){
            timeShowBig->setGeometry(aa/2-100,(bb-280)/2-70,210,70);
            timeShowSmall->setGeometry(aa/2-100,(bb-280)/2,210,70);
        }else{
            timeShowBig->setGeometry(aa/2-100,4,210,70);
            timeShowSmall->setGeometry(aa/2-100,60,210,70);
        }


        //闹钟编辑页面
        editAlarmPage->setGeometry(aa/2-190,bb/2-401,372,522);


        cancelbtnOnEditAlarm->setGeometry(65,464,120,48);
        saveBtnOnEditAlarm->setGeometry(210,464,120,48);
        timeFormatOnTimeWheel->setGeometry(60,80,41,22);
    }else{
        this->setFixedSize(390,580);
        //导航栏
        switchWidget->setGeometry(0,49,400,60);
        switchClock->setFixedSize(QSize(40,40));
        switchCountdown->setFixedSize(QSize(40,40));
        switchStopwatch->setFixedSize(QSize(40,40));
        switchClock->move(109,9);
        switchCountdown->move(175,9);
        switchStopwatch->move(241,9);


        //主页
        mainWidget->setGeometry(0,106,398,465);
        countdownPage->setGeometry(0,0,398,465);
        alarmPage->setGeometry(0,0,398,465);
        stopwatchPage->setGeometry(0,0,398,465);
        addAlarmPage->setGeometry(0,0,398,465);


        //倒计时页面
        countdownStackedW->setGeometry(0,0,390,477);
        countdownSetPage->setGeometry(0,0,390,477);
        countdownRunPage->setGeometry(0,0,390,477);
           //倒计时设置页面
        startCountSingle->resize(120,34);
        startCountSingle->move(135,401);
           //倒计时运行页面
        alarmWidget->setGeometry(16,60,361,70);
        btnWidget->setGeometry(9,386,361,48);
        timeWidget->setGeometry(14,100,361,77);
        tinyWidget->setGeometry(9,174,361,40);

        countdownAlarmIcon->setGeometry(150,22,24,26);
        countdownAlarmTime->setGeometry(168,9,60,52);
        QFont f;
        f.setFamily("NotoSansCJKsc-Regular");
        f.setPixelSize(20);
        countdownAlarmTime->setFont(f);

        startCountdownBtn->setGeometry(41,9,120,34);
        suspendCountdownBtn->setGeometry(199,9,120,34);

        remainTime->setGeometry(102,9,156,59);
        QFont ff;
        ff.setFamily("NotoSansCJKsc-Regular");
        ff.setWeight(400);
        ff.setPixelSize(40);
        remainTime->setFont(ff);

        tinyWindowBtn->setGeometry(173,9,24,24);
        //倒计时光圈
        countdownRunPage->countdownRunRoundBar->setGeometry(-4, -4, 454, 461);

        //闹钟主页
        addAlarmBtn->setGeometry(135,401,120,34);
        alarmListWidget->setGeometry(25,0,364,354);
        alarmListWidget->setGridSize(QSize(340+8, 108+15));
        noAlarm->setGeometry(122+3,232,140,31);
        noAlarmIcon->setGeometry(116+10,94,149,130);


        //秒表页面
        ringBtn->setGeometry(65,401,120,34);
        startStopwatch->setGeometry(210,401,120,34);
        timeListWidget->setGeometry(25,109,356,277);
        timeListWidget ->setGridSize(QSize(340, 58+10));
        if(!runorsuspend){
            timeShowBig->setGeometry(90,125,210,70);
            timeShowSmall->setGeometry(90,190,210,70);
        }else{
            timeShowBig->setGeometry(90,4,210,70);
            timeShowSmall->setGeometry(90,55,210,70);
        }

        //闹钟编辑页面
        editAlarmPage->setGeometry(0,0,398,465);
        cancelbtnOnEditAlarm->setGeometry(65,401,120,34);
        saveBtnOnEditAlarm->setGeometry(210,401,120,34);
        timeFormatOnTimeWheel->setGeometry(60,80,41,22);
    }
}

void Clock::inidata()
{
    //倒计时页面
       //倒计时设置页面
    startCountSingle->setText(tr("start"));
       //倒计时运行页面
    countdownAlarmTime->setAlignment(Qt::AlignLeft|Qt::AlignVCenter);
    QPalette ptext;
    ptext.setColor(QPalette::WindowText,Qt::gray);
    countdownAlarmTime->setPalette(ptext);

    startCountdownBtn->setText(tr("start"));
    suspendCountdownBtn->setText(tr("suspend"));

    remainTime->setText("00:00:00");

//    tinyWindowBtn->setText("tinybtn");

    //闹钟主页
    addAlarmBtn->setText(tr("add"));
    alarmListWidget->setViewMode(QListView::IconMode);
    //根据listwidget 容器大小, 动态调整布局位置
    alarmListWidget->setResizeMode(QListView::Adjust);
    //禁止拖拽
    alarmListWidget->setMovement(QListView::Static);
    noAlarm->setText(tr("no alarm"));
    connect(addAlarmBtn,&QPushButton::clicked,this,[=]{
        mainWidget->setCurrentIndex(3);
    });


    //秒表页面
    ringBtn->setText(tr("count"));
    startStopwatch->setText(tr("start"));

    //闹钟编辑页面
    cancelbtnOnEditAlarm->setText(Utils::getOmitStr(tr("cancel"),7));
    if(cancelbtnOnEditAlarm->text().contains("...")){
        cancelbtnOnEditAlarm->setToolTip(tr("cancel"));
    }
    saveBtnOnEditAlarm->setText(tr("save"));
    timeFormatOnTimeWheel->setText(tr("AM"));
}
//重写关闭事件
void Clock::closeEvent(QCloseEvent *event)
{
    windowClosingClicked();
//        closeHandel();

//        if(close_or_hide_page->close_flag==1){
//            event->ignore();
//            setWindowState(Qt::WindowMinimized);
//            close_or_hide_page->close_flag = 0;
//        }else if(close_or_hide_page->close_flag==2){
//            event->accept();
//            exit(0);
//        }else{
//            event->ignore();
//        }
//    close_or_hide_page->close_flag=2;
    event->accept();
//    exit(0);
    return;
}

void Clock::closeHandel()
{
    QPointF position = this->pos();
    kdk::UkuiStyleHelper::self()->removeHeader(close_or_hide_page);
//    XAtomHelper::setStandardWindowHint(close_or_hide_page->winId());
    close_or_hide_page->move(position.x()+this->width()/2-close_or_hide_page->width()/2,position.y()+this->height()/2-close_or_hide_page->height()/2);
    close_or_hide_page->exec();
}

void Clock::enableTrayIcon()
{
    if (m_trayIcon) {
        return;
    }
    QAction *quitAction = new QAction(tr("Quit"), this);
    connect(quitAction, &QAction::triggered, qApp,
            [&](){exit(0);});
    QMenu *trayIconMenu = new QMenu();
    trayIconMenu->addAction(quitAction);
    m_trayIcon = new QSystemTrayIcon();
    setDefaultTrayIconTooltip();
    m_trayIcon->setContextMenu(trayIconMenu);
    QIcon trayicon = QIcon::fromTheme("kylin-alarm-clock");
    m_trayIcon->setIcon(trayicon);
    connect(m_trayIcon, &QSystemTrayIcon::activated, this, [=](QSystemTrayIcon::ActivationReason r){
        if (r == QSystemTrayIcon::Trigger) {
            if (isHidden() || !isActiveWindow()) {
                setWindowState(windowState() & ~Qt::WindowMinimized);
                showThisWindow();
                kdk::WindowManager::activateWindow(m_pid);
                }
            }
    });
    m_trayIcon->show();
}
void Clock::updateTrayIconTooltip(QString info)
{
    if (m_trayIcon) {
        m_trayIcon->setToolTip(info);
    }
}

void Clock::setDefaultTrayIconTooltip()
{
    if (m_trayIcon) {
        if(m_trayIconTooltip!=""){
            m_trayIcon->setToolTip(m_trayIconTooltip);
        }else{
            m_trayIcon->setToolTip(tr(CLOCK_TITLE_NAME));
        }
    }
}
void Clock::disableTrayIcon()
{
#if defined(Q_OS_LINUX) || defined(Q_OS_UNIX)
    if (m_trayIcon) {
        m_trayIcon->deleteLater();
    }
#endif
}
/*
*监听主题
*/
void Clock::settingsStyle()
{

    GsettingSubject * subject = GsettingSubject::getInstance();
    connect(subject,&GsettingSubject::blackStyle, this,[=](){
        this->blackStyle();
    });
    connect(subject,&GsettingSubject::whiteStyle, this,[=](){
        this->whiteStyle();
    });
    connect(subject,&GsettingSubject::iconChnaged, this,[=](){
        ui->titileWidget->setIcon("kylin-alarm-clock");
    });

    connect(subject,&GsettingSubject::timeZoneChanged, this,[=](QString timeZone){
        this->m_timeZone =timeZone;
    });

    connect(subject,&GsettingSubject::fontChanged, this,[=](int size){
        this->CURRENT_FONT_SIZE=size;
        this->updateFront(size);
    });
    //平板改变
    connect(subject,&GsettingSubject::tabletModeChange, this,[=](bool currentTablet){
        bool rotations = GsettingSubject::getInstance()->getRotations();
        iniframe(currentTablet,rotations);
        int px = 0;
        int py = 0;
        if(currentTablet){
            ui->titileWidget->windowButtonBar()->setFollowMode(false);
            ui->titileWidget->windowButtonBar()->maximumButton()->hide();
            muteBtn->setFixedSize(40,40);
            muteBtn->move(this->width()-210,13);
            //倒计时运行页面和设置页面的铃声选择项选择隐藏还是显示
            if(countdown_isStarted){
                countdownBellLabelOnRun->hide();
                countdownBellLabelOnSet->hide();
                count_music_sellect->hide();
            }else{
                countdownBellLabelOnRun->show();
                countdownBellLabelOnSet->show();
                count_music_sellect->show();
            }
            countdownBellLabelOnSet->move(this->width()/2-175,this->height()/2-70);
            countdownBellLabelOnRun->move(this->width()/2-175,this->height()/2-70);
            //铃声下拉框
            count_music_sellect->resize(256,48);
            count_music_sellect->move(this->width()/2-95,this->height()/2-80);
            //数字盘
            px = this->width()/2-195;
            py = this->height()/2-406;
            updateClockTimeRing(px,py);

            int selectHeight = 221;
            int selectWidth = 94;
            int selectGap = 56;
            updateClockEditPageLabel(selectHeight,selectGap,9);
            updateClockEditPageBtn(selectWidth,selectHeight,selectGap,48);
        }else{
            ui->titileWidget->windowButtonBar()->setFollowMode(false);
            ui->titileWidget->windowButtonBar()->maximumButton()->hide();
            muteBtn->setFixedSize(30,30);
            muteBtn->move(238,5);
            //铃声
            countdownBellLabelOnRun->show();
            countdownBellLabelOnSet->show();
            count_music_sellect->show();
            int localeNum = m_selectBtnUtil->getCurrentLocale();
            if(localeNum == 6||localeNum == 7||localeNum == 9){
                countdownBellLabelOnSet->move(280,330);
                countdownBellLabelOnRun->move(280,330);
                //铃声下拉框
                count_music_sellect->resize(256,36);
                count_music_sellect->move(20,326);
            }else{
                countdownBellLabelOnSet->move(20,330);
                countdownBellLabelOnRun->move(20,330);
                //铃声下拉框
                count_music_sellect->resize(256,36);
                count_music_sellect->move(100,326);
            }
            //数字盘
            px = 0;
            py = 0;
            updateClockTimeRing(px,py);

            int selectHeight = 218;
            int selectWidth = 100;
            int selectGap = 44;
            updateClockEditPageLabel(selectHeight,selectGap,7);
            updateClockEditPageBtn(selectWidth,selectHeight,selectGap,36);
        }
        model->submitAll();
        int m = model->rowCount();
        for (int i = 0; i < m; i++) {
            if(currentTablet){
                aItem[i]->setSizeHint(QSize(360,160));
            }else{
                aItem[i]->setSizeHint(QSize(340,108));
            }
        }
        //切换模式后，不居中
        this->showThisWindow();
    });
    subject->iniAutoRotations();

    //要设置需要的屏幕方向，才能收到QScreen的orientationChanged信号
    QApplication::primaryScreen()->setOrientationUpdateMask(
                    Qt::PortraitOrientation
                    | Qt::LandscapeOrientation
                | Qt::InvertedLandscapeOrientation
                | Qt::PrimaryOrientation
                | Qt::InvertedPortraitOrientation);
    connect(subject,&GsettingSubject::tabletRotationChange, this,[=](bool currentRotation){
        bool onTablet = GsettingSubject::getInstance()->getOnTablet();
        if(!iniRotationFlag){
            if(QApplication::primaryScreen()->orientation()==Qt::LandscapeOrientation||QApplication::primaryScreen()->orientation()==Qt::InvertedLandscapeOrientation){
                currentRotation = false;
            }else{
                currentRotation = true;
            }
            iniRotationFlag = true;
        }
        iniframe(onTablet,currentRotation);
        if(onTablet){
            muteBtn->setFixedSize(40,40);
            muteBtn->move(this->width()-210,13);
            //铃声
            countdownBellLabelOnSet->move(this->width()/2-195+20,this->height()/2-70);
            countdownBellLabelOnRun->move(this->width()/2-195+20,this->height()/2-70);
            //铃声下拉框
            count_music_sellect->resize(256,48);
            count_music_sellect->move(this->width()/2-95,this->height()/2-80);
            //数字盘
            int px = this->width()/2-195;
            int py = this->height()/2-406;
            updateClockTimeRing(px,py);

            int selectHeight = 221;
            int selectWidth = 94;
            int selectGap = 56;
            updateClockEditPageLabel(selectHeight,selectGap,9);
            updateClockEditPageBtn(selectWidth,selectHeight,selectGap,48);
        }
        this->showThisWindow();
    });

    subject->iniWidgetStyle();
    subject->iniFontSize();
    subject->iniTimeZone();
    subject->iniTabletMode();
    subject->iniRotations();

    //当改变屏幕分辨率时 重新计算 主屏坐标 屏幕宽高
    //这段代码目的：本意是想仅针对分辨率修改的，但貌似旋转方向也影响了。
    connect(QApplication::primaryScreen(), &QScreen::geometryChanged, this, [=](){
        QRect desktop = QApplication::desktop()->screenGeometry();
        int desktopX = desktop.width();
        int desktopY = desktop.height();
        if(desktopX>desktopY){
            subject->setRotations(false);
            emit subject->tabletRotationChange(false);
        }else{
            subject->setRotations(true);
            emit subject->tabletRotationChange(true);
        }
    });

    connect(this,&Clock::timeJump,this,[=](qint64 timeValue){
        qWarning()<<"dbq检测到时间跳跃"<<timeValue;
        closeflag = false;
        //倒计时运行时，做时间跳跃
        if(countdown_isStarted){
            int ringmax = countdown_hour*3600 + countdown_minute*60 + countdown_second;
            qWarning()<<"dbq-当前时间"<<countdown_hour<<countdown_minute<<countdown_second<<ringmax;
            if(timeValue>ringmax){
                //倒计时归零
                countdown_hour = 0;
                countdown_minute = 0;
                countdown_second = 0;
            }else{
                int jumpH = timeValue/3600;
                countdown_hour = countdown_hour-jumpH;
                timeValue = timeValue-jumpH*3600;
                int jumpM = timeValue/60;
                //分钟
                if(countdown_minute>=jumpM){
                    countdown_minute = countdown_minute-jumpM;
                }else{
                    countdown_hour--;
                    countdown_minute = countdown_minute-jumpM+60;
                }
                timeValue = timeValue-jumpM*60;
                //秒
                if(countdown_second>=timeValue){
                    countdown_second = countdown_second-timeValue;
                }else{
                    if(countdown_minute>=1){
                        countdown_minute--;
                    }else{
                        //借小时位
                        countdown_hour--;
                        countdown_minute = 59;
                    }
                    countdown_second = countdown_second-timeValue+60;
                }

            }
            qWarning()<<"dbq-减去跳跃时间"<<countdown_hour<<countdown_minute<<countdown_second;
            updateCountdownTime();
        }
    });

}
void Clock::iniWaylandWinId()
{
    connect(kdk::WindowManager::self(), &kdk::WindowManager::windowAdded, [=](const kdk::WindowId &windowId) {
        if (getpid() == (int)kdk::WindowManager::getPid(windowId)) {
            if(kdk::WindowManager::getWindowTitle(windowId)==tr(CLOCK_TITLE_NAME)&&!otherWindowshown){
                m_pid = windowId.toString();
            }else if(kdk::WindowManager::getWindowTitle(windowId)=="tinyCountdown"){
                kdk::WindowManager::keepWindowAbove(windowId);
            }
        }
        otherWindowshown = false;
    });
}

/**
 * @brief 闹钟按钮图片初始化 Alarm button picture initialization
 */
void Clock::buttonImageInit()
{
    pixmap4 = QPixmap(":/image/icon-4-16x16.png");
    //“重复”下拉框对号勾选
    repeat_on_Pixmap = QPixmap(":/image/object-select-symbolic.png");
    repeat_off_Pixmap = QPixmap("");
    //启用主题框架不需要代码
//    this->setWindowIcon(QIcon::fromTheme("kylin-alarm-clock",QIcon(":/image/kylin-alarm-clock.svg")));
    //左上角闹钟图标
    ui->titileWidget->setIcon("kylin-alarm-clock");
    //倒计时上的小闹钟图标
    countdownAlarmIcon->setPixmap(pixmap4);
    countdownAlarmIcon->setVisible(true);
    countdownAlarmIcon->setFocusPolicy(Qt::NoFocus);
//    ui->countdownAlarmIcon->move(152,100);

    muteBtnStyle();
    minBtnStyle();
    menuBtnStyle();
    closeBtnStyle();
    ui->titileWidget->windowButtonBar()->maximumButton()->hide();
    disconnect(ui->titileWidget->windowButtonBar()->closeButton(), &QPushButton::clicked, this, &KWidget::close);





    //提醒铃声 倒计时设置页
    countdownBellLabelOnSet = new QLabel(countdownSetPage);

    //提醒铃声 倒计时页面运行页
    countdownBellLabelOnRun = new QLabel(countdownRunPage);
    int moveHeight = 330;
    //闹钟名称 新建闹钟
    clockNamelabel = new QLabel(editAlarmPage);

    //重复 新建闹钟
    clockRepeatLabel = new QLabel(editAlarmPage);
    //提醒铃声 新建闹钟
    clockBellLabel = new QLabel(editAlarmPage);
    //稍后提醒 新建闹钟
    clockRemindLabel = new QLabel(editAlarmPage);
    bool onTablet = GsettingSubject::getInstance()->getOnTablet();
    if(onTablet){
        countdownBellLabelOnRun->setFixedWidth(100);//设置固定大小，系统放大字体遮挡
        countdownBellLabelOnRun->setText(tr("  bell"));
        countdownBellLabelOnRun->setAlignment(Qt::AlignLeft|Qt::AlignVCenter);
        countdownBellLabelOnSet->setFixedWidth(100);//设置固定大小，系统放大字体遮挡
        countdownBellLabelOnSet->setText(tr("  bell"));
        countdownBellLabelOnSet->setAlignment(Qt::AlignLeft|Qt::AlignVCenter);
        QFont font;
        font.setPixelSize(14);
        countdownBellLabelOnRun->setFont(font);
        countdownBellLabelOnSet->setFont(font);
        countdownBellLabelOnSet->move(this->width()/2-195+20,this->height()/2-168-238+330);
        countdownBellLabelOnRun->move(this->width()/2-195+20,this->height()/2-168-238+330);
        countdownBellLabelOnRun->hide();

        int selectHeight = 221;
        int selectGap = 56;
        updateClockEditPageLabel(selectHeight,selectGap,9);
    } else{
        updateClockSelectBtnLabel(countdownBellLabelOnSet,moveHeight,tr("  bell"));
        updateClockSelectBtnLabel(countdownBellLabelOnRun,moveHeight,tr("  bell"));

        int selectHeight = 218;
        int selectGap = 44;
        updateClockEditPageLabel(selectHeight,selectGap,7);
    }
}
/*
*倒计时页初始化
*Countdown page initialization
*/
void Clock::CountdownInit()
{
    /*初始化定时器
     Initialize timer*/
    countdown_timer = new QTimer();
    /*信号和槽
     Signals and slots*/
    //倒计时开始-结束
    connect(startCountdownBtn, SIGNAL(clicked()), this, SLOT(startbtnCountdown()) );
//    connect(tinycountdownDia, SIGNAL(finishClick()), this, SLOT(tinyCountdownFinish()) );
    //倒计时执行
    connect(countdown_timer, SIGNAL(timeout()), this, SLOT(statCountdownMsec()));
    /*设置定时器每个多少毫秒发送一个timeout()信号
     Set the timer to send a timeout () signal every milliseconds*/
    countdown_timer->setInterval(10);
    countdown_hour = 0;
    countdown_minute = 0;
    countdown_second = 9;
    countdown_pushflag = 0;

    countdown_isStarted = 0;
    countdown_isStarted_2 = 0;
    countdownRunPage->countdownRunRoundBar->setRange(0,COUNTDOWN_TIME);
    /*初始化倒计时进度圈
     Initialize countdown progress circle*/
    countdownRunPage->countdownRunRoundBar->setValue(COUNTDOWN_TIME);
    //父的顶部
    startCountdownBtn->raise();
    //初始化倒计时弹窗
    countdownNoticeDialog = new Natice_alarm(60,-1);
    countdownNoticeDialog->timer->stop();
    countdownNoticeDialog->timer_xumhuan->stop();
    countdownNoticeDialog->m_musicPlayer->stop();
    //小型窗体
    if(tinycountdownDia==nullptr){
        tinycountdownDia = new tinyCountdown();
    }
    //绑定主窗体操作
    connect(tinycountdownDia,SIGNAL(mainWindowClick()),this,SLOT(activeWindow()));
    //结束
    connect(tinycountdownDia, &tinyCountdown::finishClick, this, [=](){
        tinyCountdownFinish();
    } );
    //暂停
    connect(tinycountdownDia, &tinyCountdown::suspendClick, this, [=](int onRun){
        countdown_isStarted_2 = onRun;
        onCountPushClicked();
    } );
}
void Clock::publishDbusNoticeShowAgain(){
    m_obj = new QObject();
    auto noticePool = NoticeAlarmPoolUtil::getInstance();
    DbusNoticeShowAgainAdaptor *adaptor = new DbusNoticeShowAgainAdaptor(m_obj,noticePool);
    //注册接口
    QDBusConnection::sessionBus().registerObject(CLOCK_DBUS_NOTICE_SHOW_AGAIN_PATH, m_obj);
    //判断是否注册成功
    if (!QDBusConnection::sessionBus().registerService(CLOCK_DBUS_SERVICE_NAME)) {
        qCritical()<<"注册接口失败"<<QDBusConnection::sessionBus().lastError().message();
        exit(1);
    }
    Q_UNUSED(adaptor);
}

/*
*秒表页初始化
*Stopwatch page initialization
*/
void Clock::stopwatchInit()
{
    /*初始化定时器
     Initialize timer*/
    timer = new QTimer();
    /*信号和槽
     Signals and slots*/
    connect(timer, SIGNAL(timeout()), this, SLOT(CountDown()));
    /*设置定时器每个多少毫秒发送一个timeout()信号
     Set the timer to send a timeout () signal every milliseconds*/
    timer->setInterval(10);
    //显示时间大
    timeShowBig->setText("00:00.00");
    //显示时间小
    timeShowSmall->setText("00:00.00");
    QPalette ptext;
    ptext.setColor(QPalette::WindowText,Qt::gray);
    timeShowSmall->setPalette(ptext);
    isStarted = 0;
    runorsuspend = 0;
    hour=0;
    minute=0;
    second=0;
    pushflag=0 ;
    /*时间间隔定时器
     Time interval timer*/
    timer_2 = new QTimer();
    //秒表的 每次计次后清零重新计算的时间
    connect(timer_2, SIGNAL(timeout()), this, SLOT(stopwatchJg()));
    timer_2->setInterval(10);
    stopwatch_hour = 0;
    stopwatch_minute = 0;
    stopwatch_second = 0;
    stopwatch_isStarted = 0;

    startStopwatch->raise();
    ringBtn->raise();
    //计次间隔时间最长，最短
    timeSepOrderIndex = new QMap<long,int>();
    hisLongShortIndex = new QList<int>();
}

/*
*闹钟页初始化
*Alarm page initialization
*/
void Clock::clockInit()
{
//    alarmNoticeDialog = new Natice_alarm(60,-1);
    QTimer *timer_clock = new QTimer(this);
    //动态监控闹钟与本地时间
    connect(timer_clock, SIGNAL(timeout()), this, SLOT(timerUpdate()) );/*动态获取时间
                                                                         Dynamic acquisition time*/
    timer_clock->start(1000);
    connect( addAlarmBtn, SIGNAL(clicked()), this, SLOT(setAlarmClock()) );/*添加闹钟
                                                                                  Add alarm*/
    timeShowBig->setAlignment(Qt::AlignHCenter);
    timeShowSmall->setAlignment(Qt::AlignHCenter);
    remainTime->setAlignment(Qt::AlignHCenter);
    //单个表读取和写入数据库记录的高级接口
    model = new QSqlTableModel(this);
    model->setTable("clock");
    model->setEditStrategy(QSqlTableModel::OnManualSubmit);
    model->select(); /*选取整个表的所有行
                      Select all rows of the entire table*/
    /*初始化一个包含两个Action(Delete和ClearAll)的菜单*/
    popMenu_In_ListWidget_ = new QMenu(this);
    action_Delete_In_ListWidget_ = new QAction(tr("Delete"), this);
    action_Clear_In_ListWidget_ = new QAction(tr("ClearAll"), this);
    action_edit_In_ListWidget_ = new QAction(tr("edit"), this);
    popMenu_In_ListWidget_->addAction(action_edit_In_ListWidget_);
    popMenu_In_ListWidget_->addAction(action_Delete_In_ListWidget_);

    connect(this->action_Delete_In_ListWidget_, SIGNAL(triggered()), this, SLOT(deleteAlarm()));
    //编辑
    connect(this->action_edit_In_ListWidget_, SIGNAL(triggered()), this, SLOT(listdoubleClickslot()));
    connect(alarmListWidget,SIGNAL(itemDoubleClicked(QListWidgetItem*)),this,SLOT(listdoubleClickslot()));
    connect(saveBtnOnEditAlarm, SIGNAL(clicked()), this, SLOT(setAlarmSave()) );
    connect(startStopwatch, SIGNAL(clicked()), this, SLOT(onPushbuttonStartClicked()));
    connect(ringBtn, SIGNAL(clicked()), this, SLOT(onPushbuttonRingClicked()));
    connect(cancelbtnOnEditAlarm, SIGNAL(clicked()), this, SLOT(alarmCancelSave()) );


    //暂停继续按钮
    connect(suspendCountdownBtn, SIGNAL(clicked()), this, SLOT(onCountPushClicked()));


    connect(tinyWindowBtn, SIGNAL(clicked()), this, SLOT(onTinyClicked()));
    /*绑定右键显示菜单：在单击右键之后会执行槽函数， 槽函数中负责弹出右键菜单*/
    connect(alarmListWidget, SIGNAL(customContextMenuRequested(const QPoint &)),
        this, SLOT(onCustomContextMenuRequested(const QPoint &)));

    //初始化SystemTimeFlag，不然初始值可能不为0或者1
    iniSystemTimeFlag();
//    //绘制闹钟列表
//    updateAlarmClock();

}

void Clock::keyPressEvent(QKeyEvent *event)
{
    if(16777264==event->key()){
        callUserGuide();
    }

}

void Clock::callUserGuide()
{
    if(userGuideInterface!=nullptr){
        userGuideInterface->call(QString("showGuide"), "kylin-alarm-clock");
    }
}



/*
* 事件处理函数
*/
void Clock::onCustomContextMenuRequested(const QPoint &pos)
{
    /*弹出右键菜单*/
    if(alarmListWidget->itemAt(pos)!=NULL){
        //右键弹窗与闹钟绑定
        popMenu_In_ListWidget_->exec(QCursor::pos());
    }
}

/*
* 默认初始设置
* Default initial settings
*/
void Clock::setupInit()
{
    countdownSetStartTime();/*倒计时初始化数字转盘
                               Countdown initialization digital turntable*/

    alarmSetStartTime();/*闹钟初始化数字转盘
                            Alarm initialization digital turntable*/
    modelSetupSet(); /*设置数据库初始化
                        Set database initialization*/
    textTimerupdate();
    comboxclickedflag = false;
    //闹钟名称
    clockEditOnClockNew = new QLineEdit(editAlarmPage);
    clockEditOnClockNew->setMaxLength(16);
    connect(clockEditOnClockNew, &QLineEdit::textChanged, this, &Clock::textChanged);
    /*设置输入框无视空格,过滤特殊字符*/
//    QRegExp rx = QRegExp("^[\u4E00-\u9FA5A-Za-z0-9_]+$");
//    QRegExpValidator* validator = new QRegExpValidator(rx);
//    clockEditOnClockNew->setValidator(validator);

    //倒计时的铃声
    QString bellId = model_setup->index(0, 1).data().toString();
    QString bellName = m_selectBtnUtil->getBellNameById(bellId);

    //重复下拉框
    dialog_repeat = new CustomComBox(9,editAlarmPage);
    alarmRepeat();

    //铃声下拉框
    dialog_music = new QComboBox(editAlarmPage);
    dialog_music->setFocusPolicy(Qt::NoFocus);
    setMusicSelectDialogListById(bellId,dialog_music);
    selectAlarmMusic();

    //稍后提醒下拉框
    dialog_remind_late = new QComboBox(editAlarmPage);
    dialog_remind_late->setFocusPolicy(Qt::NoFocus);
    selectRemindLate();

    //倒计时铃声选择
    count_music_sellect = new QComboBox(countdownPage);
    bool onTablet = GsettingSubject::getInstance()->getOnTablet();
    if(onTablet){
        int selectHeight = 221;
        int selectWidth = 100-6;
        int selectGap = 56;
        updateClockEditPageBtn(selectWidth,selectHeight,selectGap,48);

        count_music_sellect->resize(256,48);
        count_music_sellect->move(this->width()/2-95,this->height()/2-80);
    }else{
        int selectHeight = 218;
        int selectWidth = 100;
        int selectGap = 44;
        updateClockEditPageBtn(selectWidth,selectHeight,selectGap,36);

        int localeNum = m_selectBtnUtil->getCurrentLocale();
        if(localeNum == 6||localeNum == 7||localeNum == 9){
            //铃声下拉框
            count_music_sellect->resize(256,36);
            count_music_sellect->move(20,326);
        }else{
            //铃声下拉框
            count_music_sellect->resize(256,36);
            count_music_sellect->move(100,326);
        }
    }
    count_music_sellect->setFocusPolicy(Qt::NoFocus);
    countdownMusicSellect();
    setMusicSelectDialogListById(bellId,count_music_sellect);
  //存储重复选择的星期，默认清零
    for (int i = 0; i < 9; i++) {
        repeat_day[i] = 0;
    }


    //下拉框选择
    connect(dialog_repeat, static_cast<void (QComboBox::*)(int)>(&QComboBox::activated), this, &Clock::repeatListclickslot);
    connect(dialog_music, static_cast<void (QComboBox::*)(int)>(&QComboBox::activated), this, &Clock::musicListclickslot);
    connect(dialog_remind_late, static_cast<void (QComboBox::*)(int)>(&QComboBox::activated), this, &Clock::remindLateListClickSlot);
    connect(count_music_sellect, static_cast<void (QComboBox::*)(int)>(&QComboBox::activated), this, &Clock::countMusicListclickslot);
    indexWeekdayMap = new QHash<int,QString>();
    indexWeekdayMap->insert(0,":monday");
    indexWeekdayMap->insert(1,":tuesday");
    indexWeekdayMap->insert(2,":wednesday");
    indexWeekdayMap->insert(3,":thusday");
    indexWeekdayMap->insert(4,":friday");
    indexWeekdayMap->insert(5,":saturday");
    indexWeekdayMap->insert(6,":sunday");
}

void Clock::bellIni()
{
    m_selectBtnUtil = new SelectBtnUtil();
    int rowNum = m_bellQueryModel->rowCount();
    int localeNum = m_selectBtnUtil->getCurrentLocale();
    if (rowNum < 1) {
        QList<QString> * defaultBell = SelectBtnUtil::getDefaultBellList();
        QList<QString> * defaultBellTr = SelectBtnUtil::getDefaultBellTrList();
        for (int i=0;i<defaultBell->size();i++) {
            m_bellQueryModel->insertRow(i);
            QString temp = defaultBell->at(i);
            QString tempTr = defaultBellTr->at(i);
            if(localeNum !=11){
                m_bellQueryModel->setData(m_bellQueryModel->index(i, localeNum), tempTr);
            }
            m_bellQueryModel->setData(m_bellQueryModel->index(i, 0), Utils::getRandomId());
            m_bellQueryModel->setData(m_bellQueryModel->index(i, 11), temp);
            QString path = DEFAULT_BELL_SAVE_PATH;
            path = path.append(temp).append(".wav");
            m_bellQueryModel->setData(m_bellQueryModel->index(i, 12), path);
            QDateTime time = QDateTime::currentDateTime();   //获取当前时间
            qint64 timeT = time.toMSecsSinceEpoch();
            m_bellQueryModel->setData(m_bellQueryModel->index(i, 13), timeT);
            m_bellQueryModel->setData(m_bellQueryModel->index(i, 14), 0);
            //排序，暂停1ms
            QThread::msleep(1);
        }
        delete defaultBell;
        m_bellQueryModel->submitAll();
        m_selectBtnUtil->refreshBellData();
    }else{
        QList<QString> * defaultBell = SelectBtnUtil::getDefaultBellList();
        if(localeNumBack != localeNum){
            QList<QString> * defaultBellTr = SelectBtnUtil::getDefaultBellTrList();
            if(localeNum !=11){
                for (int i=0;i<defaultBell->size();i++) {
                    QString tempTr = defaultBellTr->at(i);
                    m_bellQueryModel->setData(m_bellQueryModel->index(i, localeNum), tempTr);
                }
            }
            delete defaultBell;
            m_bellQueryModel->submitAll();
            m_selectBtnUtil->refreshBellData();
        }
    }
    localeNumBack = localeNum;
}

/*
 * 时间间隔执行
 * Interval calculation execution callback
 */
void Clock::stopwatchJg()
{
    if (stopwatch_hour < 10) {
        QString hours_str = QString::number(stopwatch_hour);
        stopwatch_jg_h = "0"+hours_str;
    } else {
        stopwatch_jg_h = QString::number(stopwatch_hour);
    }

    if (stopwatch_minute < 10) {
        QString minute_str = QString::number(stopwatch_minute);
        stopwatch_jg_m = "0"+minute_str;
    }else {
        stopwatch_jg_m = QString::number(stopwatch_minute);
    }

    if (stopwatch_second < 10) {
        QString second_str = QString::number(stopwatch_second);
        stopwatch_jg_s = "0"+second_str;
    } else {
        stopwatch_jg_s = QString::number(stopwatch_second);
    }

    timeShowSmall->setText(stopwatch_jg_h+TIME_SEPARATOR+stopwatch_jg_m+"."+stopwatch_jg_s);

    stopwatch_second++;
    if (stopwatch_second==100) {
        stopwatch_minute++; stopwatch_second=0;}
    if (stopwatch_minute==60) {
        stopwatch_hour++; stopwatch_minute=0;}
}

/*
 * 秒表执行
 * Stopwatch execution
 */
void Clock::CountDown()
{
    if (hour < 10) {
        QString hours_str = QString::number(hour);
        stopwatch_h = "0"+hours_str;
    } else {
        stopwatch_h = QString::number(hour);
    }

    if (minute < 10) {
        QString minute_str = QString::number(minute);
        stopwatch_m = "0"+minute_str;
    } else {
        stopwatch_m = QString::number(minute);
    }

    if (second < 10) {
        QString second_str = QString::number(second);
        stopwatch_s = "0"+second_str;
    } else {
        stopwatch_s = QString::number(second);
    }
    timeShowBig->setText(stopwatch_h+TIME_SEPARATOR+stopwatch_m+"."+stopwatch_s);
//    QString selfFont = Utils::loadFontFamilyFromTTF();
//    QFont f(selfFont);
    QFont f;
    f.setFamily("NotoSansCJKsc-Regular");
    f.setWeight(400);
    f.setPixelSize(38);
    timeShowBig->setFont(f);
    //命名很不友好
    //second单位是10ms
    second++;
    //minute单位是秒
    if (second==100){
        minute++; second=0;
    }
    //hour单位是分钟
    if (minute==60){
        hour++; minute=0;
    }

}
/*
 * 秒表开始暂停继续
 * Stopwatch start pause continue
 */
void Clock::onPushbuttonStartClicked()
{
    if (!isStarted) {
        runorsuspend = 1;
        startStopwatch->setText(tr("suspend"));
        QPalette palette = startStopwatch->palette();
        QColor ColorPlaceholderText(248,163,76,255);
        QBrush brush2;
        brush2.setColor(ColorPlaceholderText);
        //主题框架1.0.6-5kylin2
        palette.setColor(QPalette::Highlight,QColor(248,163,76,255));
        palette.setColor(QPalette::Button,QColor(248,163,76,255));
        palette.setBrush(QPalette::ButtonText, QBrush(Qt::white));
        //注释原因：统一多色按钮
//        ui->startStopwatch->setPalette(palette);

        if (stopwatch_isStarted == 0) {
            timer_2->start();
            stopwatch_isStarted = 1;
        }
        timer->start();
        isStarted=1;
        if (!stopwatch_Animation) {
            stopwatchStartAnimation();
            stopwatch_Animation = 1;
        }
        ringBtn->setText(tr("count"));
    } else {
        runorsuspend = 1;
        timer->stop();
        /*查询间隔计时器是否启动
         Query whether the interval timer starts*/
        if (stopwatch_isStarted == 1) {
            timer_2->stop();
            stopwatch_isStarted = 0;
        }
        isStarted=0;
        startStopwatch->setText(tr("continue"));

        QPalette palette = startStopwatch->palette();
        QColor ColorPlaceholderText(248,163,76,255);
        QBrush brush2;
        brush2.setColor(ColorPlaceholderText);
        //主题框架1.0.6-5kylin2
        palette.setColor(QPalette::Highlight,QColor(69, 173, 110,255));
        palette.setColor(QPalette::Button,QColor(69, 173, 110,255));
        palette.setBrush(QPalette::ButtonText, QBrush(Qt::white));
        //注释原因：统一多色按钮
//        ui->startStopwatch->setPalette(palette);
        ringBtn->setText(tr("reset"));
    }
    return;
}

/*
 *倒计时标签动画移动
 *Countdown start animation move
 */
void Clock::stopwatchStartAnimation()
{
    bool onTablet = GsettingSubject::getInstance()->getOnTablet();
    animation1 = new QPropertyAnimation(timeShowBig, "geometry");
    animation1->setDuration(1000);
    if(onTablet){
        //平板模式
        animation1->setKeyValueAt(0, QRect(this->width()/2-100, 300, 210, 70));
        animation1->setEndValue(QRect(this->width()/2-100, 4, 210, 70));
    }else{
        animation1->setKeyValueAt(0, QRect(90, 125, 210, 70));
        animation1->setEndValue(QRect(90, 4, 210, 70));
    }
    animation1->start();

    animation2 = new QPropertyAnimation(timeShowSmall, "geometry");
    animation2->setDuration(1000);
    if(onTablet){
        //平板模式
        animation2->setKeyValueAt(0, QRect(this->width()/2-100, 370, 210, 41));
        animation2->setEndValue(QRect(this->width()/2-100, 60, 210, 41));
    }else{
        animation2->setKeyValueAt(0, QRect(90, 173, 210, 41));
        animation2->setEndValue(QRect(90, 60, 210, 41));
    }
    animation2->start();

    animation3 = new QPropertyAnimation(timeListWidget, "geometry");
    animation3->setDuration(1000);
    if(onTablet){
        //平板模式
        animation3->setKeyValueAt(0, QRect(this->width()/2-328 ,230, 656, 476));
        animation3->setEndValue(QRect(this->width()/2-328, 109, 656, 476));
    }else{
        animation3->setKeyValueAt(0, QRect(25 ,109, 356, 270));
        animation3->setEndValue(QRect(25, 109, 356, 270));
    }
    animation3->start();
}
/*
 * 倒计时开始动画移动
 * Countdown start animation move
 */
void Clock::stopwatchStopAnimation()
{
    bool onTablet = GsettingSubject::getInstance()->getOnTablet();
    animation1 = new QPropertyAnimation(timeShowBig, "geometry");
    animation1->setDuration(1000);
    if(onTablet){
        //平板模式
        animation1->setKeyValueAt(0, QRect(this->width()/2-100, 4, 210, 70));
        animation1->setEndValue(QRect(this->width()/2-100, 300, 210, 70));
    }else{
        animation1->setKeyValueAt(0, QRect(90, 4, 210, 70));
        animation1->setEndValue(QRect(90, 125, 210, 70));
    }
    animation1->start();

    animation2 = new QPropertyAnimation(timeShowSmall, "geometry");
    animation2->setDuration(1000);
    if(onTablet){
        //平板模式
        animation2->setKeyValueAt(0, QRect(this->width()/2-100, 60, 210, 41));
        animation2->setEndValue(QRect(this->width()/2-100, 370, 210, 41));
    }else{
        animation2->setKeyValueAt(0, QRect(90, 55, 210, 41));
        animation2->setEndValue(QRect(90, 183, 210, 41));
    }
    animation2->start();

    animation3 = new QPropertyAnimation(timeListWidget, "geometry");
    animation3->setDuration(1000);
    if(onTablet){
        //平板模式
        animation3->setKeyValueAt(0, QRect(this->width()/2-328 ,109, 356, 270));
        animation3->setEndValue(QRect(this->width()/2-328, 230, 356, 270));
    }else{
        animation3->setKeyValueAt(0, QRect(25 ,109, 656, 476));
        animation3->setEndValue(QRect(25, 230, 656, 476));
    }
    animation3->start();
}

/*
 * 计次
 * times count
 */
void Clock::onPushbuttonRingClicked()
{
    if (!isStarted) {
        //复位
        //清空数据
        runorsuspend = 0;
        timeSepOrderIndex->clear();
        hisLongShortIndex->clear();
        timeListWidget->verticalScrollBar()->setHidden(true);
        if (nullptr != timer) {
            timer->stop();
            timer_2->stop();
            timeShowBig->setText("00:00.00");
            timeShowSmall->setText("00:00.00");
            isStarted = 0;
            stopwatch_isStarted = 0;
            hour = 0; minute = 0;second = 0;
            stopwatch_hour = 0;
            stopwatch_minute = 0;
            stopwatch_second = 0;
            startStopwatch->setText(tr("start"));
            startStopwatch->setPalette(addAlarmBtn->palette());
            for (int i=0; i < stopwatch_item_flag; i++) {
                delete stopwatch_w[i];
                delete stopwatch_aItem[i];
            }
            stopwatch_item_flag = 0;
            if (stopwatch_Animation) {
                stopwatchStopAnimation();
                stopwatch_Animation = 0;
            }
        }
    }else{
        //计次
        if (stopwatch_isStarted == 0) {
            timer_2->start();
            stopwatch_isStarted = 1;
        }
        if (stopwatch_item_flag < 100) {
            stopwatch_aItem[stopwatch_item_flag] =new QListWidgetItem;
//            stopwatch_aItem[stopwatch_item_flag]->setSizeHint(QSize(340,58));
            stopwatch_aItem[stopwatch_item_flag]->setSizeHint(QSize(600,58));
            stopwatch_aItem[stopwatch_item_flag]->setTextColor(QColor(255, 0, 0, 255));
            timeListWidget->insertItem(0,stopwatch_aItem[stopwatch_item_flag]);

            timeListWidget->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
            timeListWidget->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
            timeListWidget->verticalScrollBar()->setHidden(true);
            if(stopwatch_item_flag>2){
                timeListWidget->verticalScrollBar()->setHidden(false);
            }
            stopwatch_w[stopwatch_item_flag] = new stopwatch_item(timeListWidget);

            stopwatch_w[stopwatch_item_flag]->stopwatch1->setText(tr("count")+QString::number(stopwatch_item_flag+1));
            stopwatch_w[stopwatch_item_flag]->stopwatch2->setText(tr("interval ")+stopwatch_jg_h+TIME_SEPARATOR+stopwatch_jg_m+"."+stopwatch_jg_s);
            //间隔时间存入列表
            long sepTime = stopwatch_hour*3600+stopwatch_minute*60+stopwatch_second;
            timeSepOrderIndex->insert(sepTime,stopwatch_item_flag);
            //添加标签
            updateLongestShortLabel();

            stopwatch_w[stopwatch_item_flag]->stopwatch3->setText(stopwatch_h+TIME_SEPARATOR+stopwatch_m+"."+stopwatch_s);
//            QString selfFont = Utils::loadFontFamilyFromTTF();
//            QFont f(selfFont);
            QFont f;
            f.setFamily("NotoSansCJKsc-Regular");
            f.setWeight(400);
            f.setPixelSize(24);
            stopwatch_w[stopwatch_item_flag]->stopwatch3->setFont(f);

            timeListWidget->setItemWidget(stopwatch_aItem[stopwatch_item_flag],stopwatch_w[stopwatch_item_flag]);

            stopwatch_hour = 0;
            stopwatch_minute = 0;
            stopwatch_second = 0;

            stopwatch_item_flag++;

        } else if(stopwatch_item_flag >= 100) {
            QToolTip::showText(mapToGlobal(timeListWidget->pos()+QPoint(90,340)),tr("up to 100 times"),this);
        }
    }


    //秒表页面子项字体更新
    updateStopwatchItemFront(CURRENT_FONT_SIZE);
}

void Clock::updateLongestShortLabel()
{
    QListIterator<int> iterator(*hisLongShortIndex);
    while (iterator.hasNext()) {
        int index = iterator.next();
        stopwatch_w[index]->updateTipCommonStyle();
    }
    long shortIndex = timeSepOrderIndex->first();
    stopwatch_w[shortIndex]->updateTipShortestStyle();
    int longIndex = timeSepOrderIndex->last();
    stopwatch_w[longIndex]->updateTipLongestStyle();
    //存储到历史
    hisLongShortIndex->clear();
    hisLongShortIndex->append(shortIndex);
    hisLongShortIndex->append(longIndex);


}

/*
 *复位
 *reset
 */
void Clock::onPushbuttonTimeselectClicked()
{
    if (nullptr != timer) {
        if (isStarted)
            return;
        timer->stop();
        timer_2->stop();
        timeShowBig->setText("00:00.00");
        timeShowSmall->setText("00:00.00");
        isStarted = 0;
        stopwatch_isStarted = 0;
        hour = 0; minute = 0;second = 0;
        stopwatch_hour = 0;
        stopwatch_minute = 0;
        stopwatch_second = 0;
        startStopwatch->setText(tr("start"));
        startStopwatch->setPalette(addAlarmBtn->palette());

        for (int i=0; i < stopwatch_item_flag; i++) {
            delete stopwatch_w[i];
            delete stopwatch_aItem[i];
        }
        stopwatch_item_flag = 0;
        if (stopwatch_Animation) {
            stopwatchStopAnimation();
            stopwatch_Animation = 0;
        }
    }
}

/*
 * 窗口关闭
 * window closing
 */
void Clock::windowClosingClicked()
{
    ui->titileWidget->setVisible(true);
    this->hide();
    //加入托盘
    enableTrayIcon();
    close_or_hide_page->close_flag = 0;
//    closeHandel();

//    if(close_or_hide_page->close_flag==1){
////        setWindowState(Qt::WindowMinimized);
//        this->hide();
//        //加入托盘
//        enableTrayIcon();
//        close_or_hide_page->close_flag = 0;
//    }else if(close_or_hide_page->close_flag==2){
//        exit(0);
//    }
}

/*
 *窗口最小化
 *window minimizing
 */
void Clock::windowMinimizingClicked()
{
    this->showNormal();
    this->showMinimized();
}

void Clock::muteAllBell()
{
    //静音反转
    m_muteOn = !m_muteOn;
    QPixmap pixmap = QPixmap(":/image/miniIcon/mute-off.png");
    if(currentTheme->themetype == 0){
        pixmap = QPixmap(":/image/miniIcon/mute-off.png");
    }else{
        pixmap = QPixmap(":/image/miniIcon/mute-off-dark.png");
    }
    if(m_muteOn){
        pixmap = QPixmap(":/image/miniIcon/mute-on.png");
    }
    muteBtn->setIcon(pixmap);
    if(m_muteOn){
        m_commonToolTip->setText(tr("All bells are off"));
        m_commonToolTip->showThisToolTip();
        QPoint position = frameGeometry().center();
        int x = 0;
        int y = 0;
        if(primaryManager->checkWayland()){
            x = this->width()/2-m_commonToolTip->width()/2;
            y = this->height()/2-m_commonToolTip->height()/2;
        }else{
            x = position.x()-m_commonToolTip->geometry().width()/2;
            y = position.y()-m_commonToolTip->geometry().height()/2;
        }
        m_commonToolTip ->move(x,y);
        kdk::WindowManager::setGeometry(m_commonToolTip->windowHandle(),m_commonToolTip->geometry());
        //存储静音到数据库
        model_setup->setData(model_setup->index(0, 0), 1);//静音    Mute
        if(countdownNoticeDialog->getNoticeId()==1){
            if(countdownNoticeDialog->m_musicPlayer->state()!= MMediaPlayer::State::PausedState){
                countdownNoticeDialog->m_musicPlayer->pause();
            }
        }else{
            countdownNoticeDialog->m_musicPlayer->stop();
        }
        if(alarmNoticeDialog){
            if(alarmNoticeDialog->getNoticeId()==1)
            {
                if(alarmNoticeDialog->m_musicPlayer->state() != MMediaPlayer::State::PausedState){
                    alarmNoticeDialog->m_musicPlayer->pause();
                }
            }else{
                alarmNoticeDialog->m_musicPlayer->stop();
            }
        }
        //试听音乐开启静音
        if(playController::getInstance().getState() == playController::PlayState::PLAY_STATE){
            playController::getInstance().pause();
        }
    }else{
//        m_commonToolTip->setText(tr("All bells are on"));
//        m_commonToolTip->showThisToolTip();
//        QPoint position = frameGeometry().center();
//        int x = 0;
//        int y = 0;
//        if(primaryManager->checkWayland()){
//            x = this->width()/2-m_commonToolTip->width()/2;
//            y = this->height()/2-m_commonToolTip->height()/2;
//        }else{
//            x = position.x()-m_commonToolTip->geometry().width()/2;
//            y = position.y()-m_commonToolTip->geometry().height()/2;
//        }
//        m_commonToolTip ->move(x,y);
        model_setup->setData(model_setup->index(0, 0), 0);//静音    Mute
        if(countdownNoticeDialog->getNoticeId()==1){
            ringContinueWhenMute(countdownNoticeDialog);
        }else{
            countdownNoticeDialog->m_musicPlayer->stop();
        }
        if(alarmNoticeDialog){
            if(alarmNoticeDialog->m_musicPlayer->state()!=MMediaPlayer::State::PausedState){
                alarmNoticeDialog->m_musicPlayer->pause();
            }
            if(alarmNoticeDialog->getNoticeId()==1){
                if(alarmNoticeDialog->m_musicPlayer->state()==MMediaPlayer::State::PlayingState){
                    alarmNoticeDialog->m_musicPlayer->pause();
                }
                ringContinueWhenMute(alarmNoticeDialog);
            }else{
                alarmNoticeDialog->m_musicPlayer->stop();
            }
        }
        //试听音乐取消静音
        auto sumtime = playController::getInstance().getPlayer()->duration();
        QTime time = QTime::currentTime();
        int timeH = time.hour()-musicStartTime.hour();
        int timeM = time.minute()-musicStartTime.minute();
        int timeS = time.second()-musicStartTime.second();
        auto restarttime = (timeH*3600+timeM*60+timeS) * 1000;
        if(playController::getInstance().getState() == playController::PlayState::PLAY_STATE){
            playController::getInstance().getPlayer()->pause();
        }
        if(restarttime<sumtime && playController::getInstance().getState() == playController::PlayState::PAUSED_STATE){
            playController::getInstance().getPlayer()->setPosition(restarttime);
        }
   }
        model_setup->submitAll();
}

void Clock::ringContinueWhenMute(Natice_alarm *tempdialog)
{
    auto startpos = tempdialog->timer_value * 1000;
    auto starttime = 60000-startpos;
    auto sumtime = tempdialog->m_musicPlayer->duration();
    int num = 0;
    if(tempdialog == countdownNoticeDialog){
        num=count_music_sellect->currentIndex();
    }else if(tempdialog == alarmNoticeDialog){
        //根据id查询数据
        auto sqlQuery = getClockByPK(tempdialog->getClockId());
        QString bellId =  sqlQuery.value( 2).toString();
        num=m_selectBtnUtil->getBellIndexById(bellId);
    }
    //调整自定义铃声的播放位置
    if(num<5){
        tempdialog->m_musicPlayer->pause();
    }else{
        if(sumtime>1){
            if(starttime>sumtime){
                starttime = starttime%sumtime;
            }
            tempdialog->m_musicPlayer->setPosition(starttime);
        }else{
            tempdialog->m_musicPlayer->pause();
        }
    }
}



/*
 * 倒计时切换
 * Countdown switch
 */
void Clock:: CountdownPageSwitch ()
{
    setSwitchHighlightColor(switchCountdown);
    setSwitchDefaultColor(switchClock);
    setSwitchDefaultColor(switchStopwatch);
    mainWidget->setCurrentIndex(0);
    alarmPage->hide();
}
void Clock::setBtnIcon(KPushButton *btn, QString imgUrl, QString localUrl)
{
    QIcon icon=Utils::getQIcon(imgUrl,localUrl);
//    btn->setIcon(QIcon::fromTheme(imgUrl));
    btn->setIcon(icon);
    btn->setIconSize(QSize(18, 18));
    if(theme::themetype==0 || theme::themetype==2){
        btn->setIconColor(Qt::black);
    }else{
        btn->setIconColor(Qt::white);
    }
    QPainter p(btn);
//    表示引擎应尽可能对图元的边缘进行抗锯齿。
    p.setRenderHint(QPainter::Antialiasing);
    btn->setStyleSheet("QListWidget{background-color: rgba(0, 0, 0, 0);}\
                       QListWidget::Item{background-color: rgba(0, 0, 0, 0);border-radius:0px;}\
                       QListWidget::item::selected{background-color:rgba(233, 233, 233,255);border-radius:0px;border:1px solid rgba(131, 131, 131,0);}\
                       QListWidget::item:hover{background-color:rgba(233, 233, 233,255);border-radius:0px;}\
                       ");

}
void Clock::setDefaultIcon(KPushButton *btn)
{
    if(btn==switchClock){
        setBtnIcon(switchClock,"ukui-alarm-symbolic",":/image/alarm.png");
    }else if(btn==switchCountdown){
        setBtnIcon(switchCountdown,"ukui-countselect-symbolic",":/image/count.png");
    }else if(btn==switchStopwatch){
        setBtnIcon(switchStopwatch,"stopwatch-symbolic",":/image/stopwatch.png");
    }
    if(theme::themetype==1 || theme::themetype==3){
        changeIconHeight(btn);
    }

}
QColor Clock::getHighlightActive()
{
    return palette().color(QPalette::Active,QPalette::Highlight);
}

QColor Clock::getButtonActive()
{
    return palette().color(QPalette::Active,QPalette::Button);
}
void Clock::setSwitchDefaultColor(KPushButton * btn)
{
//    auto pa = btn->palette();
//    QColor btnAcCol = getButtonActive();
//    pa.setColor(QPalette::Active,QPalette::Button,btnAcCol);
//    btn->setPalette(pa);
    btn->setBackgroundColorHighlight(false);
    setDefaultIcon(btn);
}
void Clock::setSwitchHighlightColor(KPushButton * btn)
{

    //    auto pa = btn->palette();
    //    QColor highAcCol = getHighlightActive();
    //    pa.setColor(QPalette::Active,QPalette::Button,highAcCol);
    //    btn->setPalette(pa);
        btn->setBackgroundColorHighlight(true);
        //修改图标颜色
        btn->setIconColor(Qt::white);
    //    changeIconHeight(btn);

}
/*
 * 闹钟窗口切换
 * Alarm window switchin
 */
void Clock:: AlarmPageSwitch ()
{
    setSwitchDefaultColor(switchCountdown);
    setSwitchHighlightColor(switchClock);
    setSwitchDefaultColor(switchStopwatch);
    mainWidget->setCurrentIndex(1);
}
void Clock::changeIconHeight(KPushButton *btn)
{
    QPixmap pix = btn->icon().pixmap(btn->iconSize());
    QPixmap tarPix=theme::changeIconColor(pix,palette().highlightedText().color());
    btn->setIcon(QIcon(tarPix));
}
/*
 * 秒表窗口切换
 * Stopwatch window switch
 */
void Clock:: StopwatchPageSwitch ()
{
    setSwitchDefaultColor(switchCountdown);
    setSwitchDefaultColor(switchClock);
    setSwitchHighlightColor(switchStopwatch);
    mainWidget->setCurrentIndex(2);
    alarmPage->hide();
}


/**
 * @brief 闹钟列表项
 */
void Clock::textTimerupdate()
{
    //闹钟表条数
    int rowNum = model->rowCount();
    model_setup->select();
    QTime time = QTime::currentTime();
    int time_H = time.hour();
    int time_M = time.minute();
    int time_S = time.second();
    //Timeformat
    //系统24时
    if (checkSystem24()) {
        set24ClockItem(time_H,time_M,time_S,rowNum);
    } else {
        //系统12时制
        set12ClockItem(time_H,time_M,time_S,rowNum);
    }
}

/**
 * @brief 设置24时制闹钟
 */
void Clock::set24ClockItem(int time_H,int time_M,int time_S,int rowNum)
{
    if(system_time_flag == 0){
        system_time_flag = 1;
        clearClockItem( rowNum);
    } else {
        system_time_flag = 1;
    }
}
/**
 * @brief 设置12时制闹钟
 */
void Clock::set12ClockItem(int time_H,int time_M,int time_S,int rowNum)
{
    //原来是24时，则重新构建
    if (system_time_flag == 1) {
        system_time_flag = 0;
        clearClockItem(rowNum);
    } else {
        system_time_flag = 0;
    }
}
/**
 * @brief 清理重新构建闹钟列表
 */
void Clock::clearClockItem(int rowNum)
{
    for(int i=0; i<rowNum; i++) {
        delete aItem[i];
        delete w1[i];
    }
    updateAlarmClock();
}
/**
 * @brief 初始化系统时间标识
 */
void Clock::iniSystemTimeFlag()
{
    //跟随系统
    if(checkSystem24()){
        system_time_flag = 1;
    }else{
        system_time_flag = 0;
    }

}
/**
 * @brief 判断系统是否是24时制
 */
bool Clock::checkSystem24()
{
    //Qt提供了一个QProcess类用于启动外部程序并与之通信
    QProcess process;
    process.start("gsettings get org.ukui.control-center.panel.plugins hoursystem");
    //阻塞，直到外部程序结束
    process.waitForFinished();
    QByteArray output = process.readAllStandardOutput();
    QString str_output = output;
    return str_output.compare("'24'\n") == 0;
}

void Clock::muteBtnStyle()
{
    muteBtn = new QPushButton(ui->titileWidget);
    bool onTablet = GsettingSubject::getInstance()->getOnTablet();
    if(onTablet){
        muteBtn->setFixedSize(40,40);
        muteBtn->move(this->width()-210,13);
    }else{
        muteBtn->setFixedSize(30,30);
        muteBtn->move(238,5);
    }
    int mute = model_setup->index(0, 0).data().toInt();
    m_muteOn = mute==1?true:false;
    muteBtn->setIconSize(QSize(32, 32));
    QPainter p(muteBtn);
    //表示引擎应尽可能对图元的边缘进行抗锯齿。
    p.setRenderHint(QPainter::Antialiasing);
    //同三联样式
    muteBtn->setProperty("isWindowButton", 0x1);
    muteBtn->setProperty("useIconHighlightEffect", 0x2);
    muteBtn->setFlat(true);
    muteBtn->setVisible(true);
    muteBtn->setFocusPolicy(Qt::NoFocus);
    muteBtn->setToolTip(tr("mute"));
    //弹窗初始化
    m_commonToolTip = new CommonToolTip(this);
    connect(muteBtn, SIGNAL(clicked()), this, SLOT(muteAllBell()));


}
/**
 * @brief 最小化按钮样式
 */
void Clock::minBtnStyle()
{
    //窗口最小化
    QPushButton* btn = ui->titileWidget->windowButtonBar()->minimumButton();
    btn->setToolTip(tr("Minimize"));
    connect(btn, SIGNAL(clicked()), this, SLOT(windowMinimizingClicked()));
}
/**
 * @brief 关闭按钮样式
 */
void Clock::closeBtnStyle()
{
    //适配sdk
    QPushButton* btn = ui->titileWidget->windowButtonBar()->closeButton();
    btn->setToolTip(tr("Close"));
    disconnect(ui->titileWidget->windowButtonBar()->closeButton(), &QPushButton::clicked, this, &KWidget::close);
    connect(btn, SIGNAL(clicked()), this, SLOT(windowClosingClicked()));
}
/**
 * @brief 菜单按钮样式
 */
void Clock::menuBtnStyle()
{
    //适配sdk
    //删除原sdk中的多余选项
    KMenuButton* btn = ui->titileWidget->windowButtonBar()->menuButton();
    btn->setToolTip(tr("Option"));
    QMenu* menu = ui->titileWidget->windowButtonBar()->menuButton()->menu();
    QAction* settingAction = ui->titileWidget->windowButtonBar()->menuButton()->settingAction();
    QAction* themeAction = ui->titileWidget->windowButtonBar()->menuButton()->themeAction();
    menu->removeAction(settingAction);
    menu->removeAction(themeAction);
    //帮助
    QAction* m_helpAction = ui->titileWidget->windowButtonBar()->menuButton()->assistAction();
    //关于
    QAction* m_aboutAction = ui->titileWidget->windowButtonBar()->menuButton()->aboutAction();
    //关闭
    QAction* m_closeAction = ui->titileWidget->windowButtonBar()->menuButton()->quitAction();
    m_helpAction->setText(tr("Help"));
    m_aboutAction->setText(tr("About"));
    m_closeAction->setText(tr("Quit"));
    connect(m_helpAction, &QAction::triggered, this, [=](){
        qDebug() << "help clicked";
        callUserGuide();
    });
    connect(m_aboutAction, &QAction::triggered, this, [=](){
        QApplication::setApplicationName(tr(CLOCK_TITLE_NAME));
        QString version = utils->getClockVersion();
        KAboutDialog *aboutDialog = new KAboutDialog(this,QIcon::fromTheme("kylin-alarm-clock"),tr(CLOCK_TITLE_NAME),tr("Version：")+version);
        kdk::UkuiStyleHelper::self()->removeHeader(aboutDialog);
        aboutDialog->setBodyTextVisiable(true);
        otherWindowshown =true;
        aboutDialog->exec();
    });
//    connect(m_closeAction, SIGNAL(triggered()), this, SLOT(windowClosingClicked()));
    connect(m_closeAction, &QAction::triggered, this, [=](){
        exit(0);
    });
}
/*
 * @brief 检查小窗体是否初始化
 */
bool Clock::checkTinyCountdownDia()
{
    return tinycountdownDia!=nullptr?true:false;
}

void Clock::navigationBtnStyle(KPushButton * btn)
{
    setDefaultIcon(btn);;
    //不使用主题高亮
    btn->setProperty("useIconHighlightEffect", false);
    //使用灰按钮
    btn->setProperty("useButtonPalette", true);

}

void Clock::updateClockSelectBtnStyle(SelectBtn *temp, int moveHeight)
{
    temp->move(25,moveHeight);
}

void Clock::updateCountdownSelectBtnStyle(SelectBtn *temp, int moveWidth, int moveHeight)
{
    temp->move(moveWidth,moveHeight);
}

void Clock::updateClockSelectBtnStyle(Btn_new *temp, int moveHeight)
{
    temp->move(DIALOG_MOVE_WIDTH,moveHeight);
}

void Clock::updateCountdownSelectBtnStyle(Btn_new *temp, int moveWidth, int moveHeight)
{
    temp->move(moveWidth,moveHeight);
}

void Clock::updateClockSelectBtnLabel(QLabel *temp, int moveHeight, QString text)
{
    temp->setFixedWidth(100);//设置固定大小，系统放大字体遮挡
    temp->setText(text);
    int labelLeftSpace;
    QString systemLang = QLocale::system().name();
    if(systemLang=="ug_CN"||systemLang=="kk_KZ"||systemLang=="ky_KG"){
        temp->setAlignment(Qt::AlignLeft|Qt::AlignVCenter);
        labelLeftSpace = 280;
    }else{
        temp->setAlignment(Qt::AlignLeft|Qt::AlignVCenter);
        labelLeftSpace = 20;
    }
    QFont font;
    font.setPixelSize(14);
    temp->setFont(font);
//    temp->setStyleSheet("font-size:14px;");
//    int labelLeftSpace = 20;
    temp->move(labelLeftSpace, moveHeight);
}

void Clock::updateClockTimeRing(int ringWidthOffset, int ringHeightOffset)
{
    int ringMoveWidth = 67+ringWidthOffset;
    int ringMoveHeight = 30+ringHeightOffset;
    int timeSep = 100;
    int labelSep = 74;
    int timeLabelMoveHeight = 125+ringHeightOffset;
    hourTimerRing->move(ringMoveWidth, ringMoveHeight);
    h_in_m->move(ringMoveWidth+labelSep,timeLabelMoveHeight);
    ringMoveWidth+=timeSep;
    minuteTimeRing->move(ringMoveWidth, ringMoveHeight);
    m_in_s->move(ringMoveWidth+labelSep,timeLabelMoveHeight);
    ringMoveWidth+=timeSep;
    secondTimeRing->move(ringMoveWidth, ringMoveHeight);
    after_s->move(ringMoveWidth+labelSep,timeLabelMoveHeight);
}

void Clock::updateClockEditPageLabel(int selectHeight, int selectGap, int labelHeightOffset)
{
    //闹钟名称
    updateClockSelectBtnLabel(clockNamelabel,selectHeight+labelHeightOffset,tr("  name"));
    selectHeight+=selectGap;
    //重复下拉框
    updateClockSelectBtnLabel(clockRepeatLabel,selectHeight+labelHeightOffset,tr("  repeat"));
    selectHeight+=selectGap;
    //铃声下拉框
    updateClockSelectBtnLabel(clockBellLabel,selectHeight+labelHeightOffset,tr("  bell"));
    selectHeight+=selectGap;
    //稍后提醒下拉框
    updateClockSelectBtnLabel(clockRemindLabel,selectHeight+labelHeightOffset,tr("  remind"));
}

void Clock::updateClockEditPageBtn(int selectMoveWidth, int selectMoveHeight, int selectGap, int btnHeight)
{
    int localeNum = m_selectBtnUtil->getCurrentLocale();
    if(localeNum == 6||localeNum == 7||localeNum == 9){
        selectMoveWidth = selectMoveWidth-80;
    }
    int btnWidth = 256;
    //闹钟名称
    clockEditOnClockNew->resize(btnWidth,btnHeight);
    clockEditOnClockNew->move(selectMoveWidth,selectMoveHeight);
    selectMoveHeight+=selectGap;
    //重复下拉框
    dialog_repeat->resize(btnWidth,btnHeight);
    dialog_repeat->move(selectMoveWidth,selectMoveHeight);
    selectMoveHeight+=selectGap;
    //铃声下拉框
    dialog_music->resize(btnWidth,btnHeight);
    dialog_music->move(selectMoveWidth,selectMoveHeight);
    selectMoveHeight+=selectGap;
    //稍后提醒下拉框
    dialog_remind_late->resize(btnWidth,btnHeight);
    dialog_remind_late->move(selectMoveWidth,selectMoveHeight);

}

void Clock::widgetListWhiteStyle(QListWidget *listWidget)
{
    QString listBackColor = getDefaultGreyColor();
    if(theme::themetype==2){
        listWidget->setStyleSheet("QListWidget{background-color: rgba(0, 0, 0, 0);}\
                                      QListWidget::Item{background-color:"+listBackColor+";border-radius:0px;}\
                                      QListWidget::item::selected{background-color:rgba(233, 233, 233,255);border-radius:0px;border:1px solid rgba(131, 131, 131,0);}\
                                      QListWidget::item:hover{background-color:rgba(233, 233, 233,255);border-radius:0px;}\
                                      ");
    }else{
        QString selectItemRadius = QString::number(SELECT_ITEM_RADIUS);
        listWidget->setStyleSheet("QListWidget{background-color: rgba(0, 0, 0, 0);}\
                                      QListWidget::Item{background-color:"+listBackColor+";border-radius:"+selectItemRadius+"px;}\
                                      QListWidget::item::selected{background-color:rgba(233, 233, 233,255);border-radius:"+selectItemRadius+"px;border:1px solid rgba(131, 131, 131,0);}\
                                      QListWidget::item:hover{background-color:rgba(233, 233, 233,255);border-radius:"+selectItemRadius+"px;}\
                                      ");
    }
}

void Clock::widgetListBlackStyle(QListWidget *listWidget)
{
    if(theme::themetype==3){
        listWidget->setStyleSheet("QListWidget{background-color: rgba(0, 0, 0, 0);}\
                                      QListWidget::Item{background-color:rgba(41, 41, 41, 255);border-radius:0px;}\
                                      QListWidget::item::selected{background-color:rgba(55, 55, 59, 255);border-radius:0px;border:1px solid rgba(131, 131, 131,0);}\
                                      QListWidget::item:hover{background-color:rgba(55, 55, 59, 255);border-radius:0px;}\
                                      ");
    }else{
        QString selectItemRadius = QString::number(SELECT_ITEM_RADIUS);
        listWidget->setStyleSheet("QListWidget{background-color: rgba(0, 0, 0, 0);}\
                                      QListWidget::Item{background-color:rgba(41, 41, 41, 255);border-radius:"+selectItemRadius+"px;}\
                                      QListWidget::item::selected{background-color:rgba(55, 55, 59, 255);border-radius:"+selectItemRadius+"px;border:1px solid rgba(131, 131, 131,0);}\
                                      QListWidget::item:hover{background-color:rgba(55, 55, 59, 255);border-radius:"+selectItemRadius+"px;}\
                                      ");
    }

}
void Clock::watchTimeJump()
{
    QTime time = QTime::currentTime();
    int timeH = time.hour();
    int timeM = time.minute();
    int timeS = time.second();
    auto dateTimeSecs = QDateTime::currentSecsSinceEpoch();
//    qDebug()<<"dbq-闹钟"<<timeH<<":"<<timeM<<":"<<timeS<<dateTimeSecs;
    auto watchTimeModel = clock_sql::getWatchTimeTable(this);
    int rowCount = watchTimeModel->rowCount();
    QString timeInfo =QString::number(dateTimeSecs);
    qint64 lastTimeInfo = 0;
    int index = 0;
    if(rowCount<1){
        //新建
        watchTimeModel->insertRow(index);
        watchTimeModel->setData(watchTimeModel->index(index, 0), Utils::getRandomId());
        watchTimeModel->setData(watchTimeModel->index(index, 1), timeInfo);
    }else{
        QString lastTimeInfoStr = watchTimeModel->index(index, 1).data().toString();
        lastTimeInfo = lastTimeInfoStr.toLong();
//        qDebug()<<"dbq-lastTimeInfoStr"<<lastTimeInfoStr<<"lastTimeInfo"<<lastTimeInfo;
        int timeGap = dateTimeSecs-lastTimeInfo;
        if(timeGap>1){
//            qDebug()<<"dbq-timeGap"<<timeGap;
            emit timeJump(timeGap);
        }
        watchTimeModel->setData(watchTimeModel->index(index, 1), timeInfo);
    }
    watchTimeModel->submitAll();

}
/*
 * 动态监控闹钟与本地时间
 * Dynamic monitoring alarm clock and local time
 */
void Clock::timerUpdate()
{
    QTime time = QTime::currentTime();
    int timeH = time.hour();
    int timeM = time.minute();
    int timeS = time.second();

    watchTimeJump();

    model_setup->select();
    //更新闹钟列表项
    textTimerupdate();

    int rowNum = model->rowCount();
    bool hasNextAlarm = false;
    QString nextAlarmClock = "";
    //记录最近的闹钟时间差
    int spanTime = 0;
    //遍历闹钟
    for (int i = 0; i < rowNum; i++) {
        /*判断星期
         Judgment week*/
        QDateTime current_date_time = QDateTime::currentDateTime();
        //今天没提醒闹钟，则continue
        //缩写的本地化日期名称
        if (current_date_time.toString("ddd").compare("周一")==0 &&  model->index(i, 6).data().toInt() == 0)
             continue;
         if (current_date_time.toString("ddd").compare("周二")==0 &&  model->index(i, 7).data().toInt() == 0)
             continue;
         if (current_date_time.toString("ddd").compare("周三")==0 &&  model->index(i, 8).data().toInt() == 0)
             continue;
         if (current_date_time.toString("ddd").compare("周四")==0 &&  model->index(i, 9).data().toInt() == 0)
             continue;
         if (current_date_time.toString("ddd").compare("周五")==0 &&  model->index(i, 10).data().toInt() == 0)
             continue;
         if (current_date_time.toString("ddd").compare("周六")==0 &&  model->index(i, 11).data().toInt() == 0)
             continue;
         if (current_date_time.toString("ddd").compare("周日")==0 &&  model->index(i, 12).data().toInt() == 0)
             continue;

        /*判断开关
         Judgment switch*/
         //闹钟关闭 则 continue
        if ( model->index(i, 3).data().toInt() == 1)
            continue;
        //闹钟时间到
        int alarmH = model->index(i, 0).data().toInt();
        int alarmM = model->index(i, 1).data().toInt();
        if (timeH == alarmH
                && timeM == alarmM
                && timeS == 0) {
            double music_time = 30;
            if (model->index(i, 13).data().toString().compare(tr("2min"))==0) {
                music_time = 2*60;
            } else if (model->index(i, 13).data().toString().compare(tr("3min"))==0) {
                music_time = 3*60;
            } else if (model->index(i, 13).data().toString().compare(tr("4min"))==0) {
                music_time = 4*60;
            } else if (model->index(i, 13).data().toString().compare(tr("6min"))==0) {
                music_time = 6*60;
            } else {
                music_time = 60;
            }
            QString id = model->index(i, 14).data().toString();
            noticeDialogShow(music_time, i ,id);
            if(model->index(i, 5).data().toString().compare(tr("No repetition"))==0)
                offAlarm(i);
        }else{
            int tempSpan = (alarmH-timeH)*60+alarmM-timeM;
            if(tempSpan>0){
                hasNextAlarm = true;
                if(spanTime==0){
                    spanTime=tempSpan;
                    nextAlarmClock = changeNumToStrWithAm(alarmH)+TIME_SEPARATOR+changeNumToStr(alarmM);
                }else{
                    if(tempSpan<spanTime){
                        spanTime=tempSpan;
                        nextAlarmClock = changeNumToStrWithAm(alarmH)+TIME_SEPARATOR+changeNumToStr(alarmM);
                    }

                }
            }
        }
    }
    if(hasNextAlarm){
        m_trayIconTooltip=tr("recent alarm")+TIME_SEPARATOR_CN+nextAlarmClock;
    }else{
        m_trayIconTooltip="";
    }
    setDefaultTrayIconTooltip();
    //触发一次paintEvent
    update();
    //更新闹钟页面子项字体
    updateAlarmItemFront(CURRENT_FONT_SIZE);
    //刷新倒计时上 时间格式
    getCountdownOverTime();
    //刷新上下午滚轮
    timerAlarmStartUpdate();
}

/*
 * 通知弹窗
 * Notification Popup
 */
void Clock::noticeDialogShow(int close_time, int alarm_num, QString id)
{
    model_setup->select();
    //闹钟弹窗
    alarmNoticeDialog = new Natice_alarm(close_time,alarm_num,nullptr,id);
    alarmNoticeDialog->playMusic();
    NoticeAlarmPoolUtil::getInstance()->
            inseartNoticesMap(alarmNoticeDialog->getNoticeId(),alarmNoticeDialog);
}


/**
 * @brief 重绘窗口，更新闹钟 Redraw window, update alarm clock
 */
void Clock::updateAlarmClock()
{
    int rowNum = model->rowCount();
    int hour_now;
    int min_now;
    if(rowNum){
        noAlarm->hide();
        noAlarmIcon->hide();
    }else{
        noAlarm->show();
        noAlarmIcon->show();
    }
    auto sqlQuery = clock_sql::getQSqlQuery();
    sqlQuery.exec("select * from clock order by Hour ASC,Minute ASC");
    int alarmNum = 0;
    //实现id补偿，原表设计没有主键，为实现旧数据兼容
//    QList<int> * needIdNumList = new QList<int>();
//    QHash<int,int> * numToIndex =new QHash<int,int>();
    while (sqlQuery.next()) {
        //窗体
        aItem[alarmNum] =new QListWidgetItem;
        bool onTablet = GsettingSubject::getInstance()->getOnTablet();
        if(onTablet){
            aItem[alarmNum]->setSizeHint(QSize(360,160));
        }else{
            aItem[alarmNum]->setSizeHint(QSize(340,108));
        }
        aItem[alarmNum]->setTextColor(QColor(255, 0, 0, 255));
        alarmListWidget->addItem(aItem[alarmNum]);
        //避免滚动条因占据item空间而使item发生变化
//        alarmListWidget->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
        alarmListWidget->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
//        alarmListWidget->verticalScrollBar()->setHidden(true);
//        connect(alarmListWidget->verticalScrollBar(),&QScrollBar::rangeChanged,this, [=](){
//            if (alarmListWidget->verticalScrollBar()->maximum() == 0) {
//                alarmListWidget->verticalScrollBar()->setHidden(true);
//            } else {
//                alarmListWidget->verticalScrollBar()->setHidden(false);
//            }
//        });
        //闹钟信息
        int value = sqlQuery.value(3).toInt();
        w1[alarmNum] = new item_new(alarmListWidget);
        //信息与展示窗体绑定
        alarmListWidget->setItemWidget(aItem[alarmNum],w1[alarmNum]);
        //绑定Id到闹钟子项
        auto hisId =  sqlQuery.value(14).toString();
        w1[alarmNum]->setId(hisId);
        hour_now =sqlQuery.value( 0).toInt();
        min_now =sqlQuery.value( 1).toInt();
        int onOff = sqlQuery.value(3).toInt();
        if(onOff==1){
            w1[alarmNum]->closeStyle(CURRENT_FONT_SIZE);
        }else{
            w1[alarmNum]->openStyle(CURRENT_FONT_SIZE);
        }
        if (system_time_flag) {
            //24时制
            changeTimeNum(hour_now,min_now);//转换int为QString
            // Convert int to qstring
            w1[alarmNum]->alarmLabel0->setText(alarmHour_str+TIME_SEPARATOR+alarmMinute_str);
            QString selfFont = Utils::loadFontFamilyFromTTF();
            QFont f(selfFont);
            f.setPixelSize(38);
            w1[alarmNum]->alarmLabel0->setFont(f);

            w1[alarmNum]->alarmLabel1->hide();
        } else {
            //12时制
            if (hour_now >= 12) {
                w1[alarmNum]->alarmLabel1->setText(tr("PM"));
                if (hour_now == 12) {
                    w1[alarmNum]->alarmLabel0->setText(changeNumToStr(hour_now)+" : "+changeNumToStr(min_now));
                } else {
                    w1[alarmNum]->alarmLabel0->setText(changeNumToStr(hour_now-12)+" : "+changeNumToStr(min_now));
                }
            } else {
                w1[alarmNum]->alarmLabel1->setText(tr("AM"));
                if (hour_now == 0) {
                    w1[alarmNum]->alarmLabel0->setText(changeNumToStr(12)+" : "+changeNumToStr(min_now));
                } else {
                    w1[alarmNum]->alarmLabel0->setText(changeNumToStr(hour_now)+" : "+changeNumToStr(min_now));
                }
            }
        }
        /*闹钟开关
         Alarm switch*/
        //onoroff
        if (sqlQuery.value( 3).toInt() == 1) {
            w1[alarmNum]->alarm_on_off0->setChecked(false);
        } else {
            w1[alarmNum]->alarm_on_off0->setChecked(true);
        }
        //Name 闹钟名
        QString clockName = sqlQuery.value( 13).toString();
        int sizeLimit = 8;
        if(clockName.length()>sizeLimit){
            w1[alarmNum]->alarmLabel_w0->setToolTip(clockName);
            //名字超长
            clockName = clockName.left(sizeLimit);
            clockName = clockName+"..";
        }
        w1[alarmNum]->alarmLabel_w0->setText(clockName);
        //repeat 重复
        QString werk_str = sqlQuery.value( 5).toString();
        QString werk_day ;
        int werk = 0;
        for (int i=0; i<7; i++) {
            //从周一到周日开始判断 为1
            if (sqlQuery.value( 6+i).toInt()) {
                //拼接werk_day
                if(i == 0){
                    werk_day = werk_day + tr("Mon")+"  ";
                }else if(i == 1){
                    werk_day = werk_day + tr("Tue")+"  ";
                }else if(i == 2){
                    werk_day = werk_day + tr("Wed")+"  ";
                }else if(i == 3){
                    werk_day = werk_day + tr("Thu")+"  ";
                }else if(i == 4){
                    werk_day = werk_day + tr("Fri")+"  ";
                }else if(i == 5){
                    werk_day = werk_day + tr("Sat")+"  ";
                }else if(i == 6){
                    werk_day = werk_day + tr("Sun")+"  ";
                }
            }else{
                //不是全为1
                werk = 1;
            }
        }
        if(werk){
            w1[alarmNum]->alarmLabel_s0->setText(werk_day);
        }else {
            if(werk_str == tr("Every day") || werk_str == "每天"){
                w1[alarmNum]->alarmLabel_s0->setText(tr("Every day"));
            }else if(werk_str == "Workingday" || werk_str == "工作日"){
                w1[alarmNum]->alarmLabel_s0->setText(tr("Workingday"));
            }else if(werk_str == "No repetition" || werk_str == "不重复"){
                w1[alarmNum]->alarmLabel_s0->setText(tr("No repetition"));
            }
        }
        updateLabelStrCnEn(w1[alarmNum]->alarmLabel_s0,20,25);
        //闹钟开关绑定
        connect(w1[alarmNum]->alarm_on_off0,SIGNAL(stateChanged(bool)),this, SLOT(OnOffAlarm()));
        alarmNum++;
    }
//    updateClockIdByNum(needIdNumList,numToIndex);

}

void Clock::timerAlarmStartUpdate()
{
    if(system_time_flag==1){
        timer_alarm_startAPM->hide();
    }else{
        timer_alarm_startAPM->show();
    }
}

/*
 * 绘制无闹钟提示
 * Draw no alarm prompt
 */
void Clock::drawNoAlarmPrompt()
{
    noAlarmIcon->setPixmap(QPixmap(":/image/noClockWhite.png"));//.pixmap(164,194)
    noAlarm->setAlignment(Qt::AlignHCenter);
}

void Clock::textChanged(const QString &arg1)
{
    QString str = arg1;
    str.replace("~", "");
    str.replace("`", "");
    str.replace("!", "");
    str.replace("@", "");
    str.replace("#", "");
    str.replace("$", "");
    str.replace("%", "");
    str.replace("^", "");
    str.replace("&", "");
    str.replace("*", "");
    str.replace("(", "");
    str.replace(")", "");
    str.replace("_", "");
    str.replace("-", "");
    str.replace("+", "");
    str.replace("=", "");
    str.replace("[", "");
    str.replace("]", "");
    str.replace("{", "");
    str.replace("}", "");
    str.replace("\\", "");
    str.replace("|", "");
    str.replace("'", "");
    str.replace(",", "");
    str.replace(".", "");
    str.replace("?", "");
    str.replace("<", "");
    str.replace(">", "");
    str.replace(" ", "");

    clockEditOnClockNew->setText(str);

}

/*
 * 修改时间单数 为两位数
 * Modify time singular to two digits
 */
void Clock::changeTimeNum(int alarmHour, int alarmMinute)
{
    if (alarmHour < 10) {
        QString hours_str = QString::number(alarmHour);
        alarmHour_str = "0"+hours_str;
    } else {
        alarmHour_str = QString::number(alarmHour);
    }
    if (alarmMinute < 10) {
        QString minute_str = QString::number(alarmMinute);
        alarmMinute_str = "0"+minute_str;
    } else {
        alarmMinute_str = QString::number(alarmMinute);
    }
}




/*
 * 新建闹钟按钮回调
 * New alarm button callback
 */
void Clock::setAlarmClock()
{
    onEditPage = false;
    //新建闹钟页
    mainWidget->setCurrentIndex(3);
    alarmPage->show();
    //取消
    cancelbtnOnEditAlarm->show();
    repeat_new_or_edit_flag = 0;

    model_setup->select();/*调用默认设置
                           Call default settings*/
    repeat_str_model = tr("Workingday");
    //数字盘时间设置为当前时间
    QTime time = QTime::currentTime();
    int timeH = time.hour();
    int timeM = time.minute();
    timer_alarm_start24->m_currentValue = timeH;
    timer_alarm_start60->m_currentValue = timeM;
    if(timer_alarm_start24->m_currentValue>=12){
        timer_alarm_startAPM->m_currentValue=2;
    }else{
        timer_alarm_startAPM->m_currentValue=1;
    }
    //工作日默认
    dialog_repeat->line_edit_->setText(repeat_str_model+tr("(default)"));
    //工作日设置的逻辑
    //存储重复选择的星期，默认清零
    for (int i = 0; i < 9; i++) {
          repeat_day[i] = 0;
    }
    for (int i=0; i<5; i++) {
        repeat_day[i] = 1;
    }
    remind_late_str_model= tr("none");
    //设置新建闹钟默认铃声
    QString defaultBellId = m_selectBtnUtil->getDefaultBellId();
    QString bellName = m_selectBtnUtil->getBellNameById(defaultBellId);
    dialog_music->setCurrentText(bellName);
    setMusicSelectDialogListById(defaultBellId,dialog_music);
    //设置默认稍后提醒
    setRemindLateSelectDialogListByName(remind_late_str_model,dialog_remind_late);
    clock_name = tr(CLOCK_TITLE_NAME);
    clockEditOnClockNew->setText(clock_name);
}
/**
 * @brief 设置新建闹钟的铃声的默认值
 * @param name
 */
void Clock::setMusicSelectDialogListById(QString bellId, QComboBox *temp)
{
    int status = m_selectBtnUtil->getBellIndexById(bellId);
    temp->setCurrentIndex(status);
}

void Clock::setRemindLateSelectDialogListByName(QString name, QComboBox *temp)
{
    int status = getRemindStatusByName(name);
    temp->setCurrentIndex(status);
}

int Clock::getRemindStatusByName(QString name)
{
    int status = 0;
    if(name.compare("none") == 0 || name.compare("不需要") == 0){
        status = 0;
    }else if(name.compare("five mins late") == 0 || name.compare("5分钟后") == 0){
        status = 1;
    }else if(name.compare("ten mins late") == 0 || name.compare("10分钟后") == 0){
        status = 2;
    }else if(name.compare("twenty mins late") == 0 || name.compare("20分钟后") == 0){
        status = 3;
    }else if(name.compare("thirsty mins late") == 0 || name.compare("30分钟后") == 0){
        status = 4;
    }else if(name.compare("one hour late") == 0 || name.compare("1小时后") == 0){
        status = 5;
    }
    return status;
}

/*
 * 闹钟新建界面保存回调
 * Alarm new interface save callback
 */
void Clock::setAlarmSave()
{
    //12小时制时间转化
    if(system_time_flag==0){
        int apmindex = timer_alarm_startAPM->m_currentValue-1;
        int time_24 = timer_alarm_start24->m_currentValue;
        timer_alarm_start24->m_currentValue=time_24%12+apmindex*12;
    }
    if(onEditPage){
        //编辑页面保存
        QString clockName = clockEditOnClockNew->text();
        if(clockName.isEmpty()){
            delete_msg *deletemsg = new delete_msg(this);
            deletemsg->ui->msgInfo->setText(tr("Please set alarm name!"));
            deletemsg->exec();
            return ;
        }
        auto curentId = getClockPkByCurrentNum();
        auto sqlQuery = clock_sql::getQSqlQuery();
        sqlQuery.prepare("update clock set hour=:hour,minute=:minute,bell_id=:music,repeat=:repeat,"
                         "name=:name,monday=:monday,tuesday=:tuesday,wednesday=:wednesday,thursday=:thusday,"
                         "friday=:friday,saturday=:saturday,sunday=:sunday,remind_status=:remind_status,editstatus=:editstatus where id=:id");
        sqlQuery.bindValue(":id",curentId);
        sqlQuery.bindValue(":hour",timer_alarm_start24->m_currentValue);
        sqlQuery.bindValue(":minute",timer_alarm_start60->m_currentValue);
        QString bellId = getSelectBellId(dialog_music);
        sqlQuery.bindValue(":music",bellId);
        sqlQuery.bindValue(":repeat",repeat_str_model);
        sqlQuery.bindValue(":remind_status",remind_late_str_model);
        sqlQuery.bindValue(":name",clockName);
        sqlQuery.bindValue(":editstatus",true);
        for (int i=0; i<7; i++) {
            QString day = indexWeekdayMap->value(i);
            if (repeat_day[i]) {
                sqlQuery.bindValue(day,1);
            } else {
                sqlQuery.bindValue(day,0);
            }
        }
        sqlQuery.exec();
        model->submitAll();
        int m = model->rowCount();
        /*每次updateAlarmClock()之前，删除全部闹钟相关控件
          Delete all alarm related controls before updatealrmclock()*/
        for (int i = 0; i < m; i++) {
            delete aItem[i];
            delete w1[i];
        }
        updateAlarmClock();
        updateAlarmItemFront(CURRENT_FONT_SIZE);
        mainWidget->setCurrentIndex(1);
        mainWidget->raise();/*将页面放置最前方
                                    Put the page at the front*/

    }else{
        //新建页面保存
        clockEditOnClockNew->setText(clockEditOnClockNew->text().remove(QRegExp("\\s")));//去除所以空格
        if(clockEditOnClockNew->text().isEmpty()){
            delete_msg *deletemsg = new delete_msg(this);
            deletemsg->ui->msgInfo->setText(tr("Please set alarm name!"));
            deletemsg->exec();
            return ;
        }
        int rowNum;
        rowNum = model->rowCount();

        qDebug() << rowNum << "闹钟数";
        if (rowNum < 20) {
            saveClockToDatabase(rowNum);
        } else {
            QMessageBox::warning(this, tr("warning"), tr("the number of alarms reaches limit!！"), tr("yes"));
        }

        mainWidget->setCurrentIndex(1);
        mainWidget->raise();//将页面放置最前方
                                   // Put the page at the front

    }
    updateAlarmItemFront(CURRENT_FONT_SIZE);
    playController::getInstance().stop();
}

void Clock::saveClockToDatabase(int rowNum)
{
    QString clockName = clockEditOnClockNew->text();
    model->insertRow(rowNum);

    model->setData(model->index(rowNum, 0), timer_alarm_start24->m_currentValue);
    model->setData(model->index(rowNum, 1), timer_alarm_start60->m_currentValue);
    QString bellId = getSelectBellId(dialog_music);
    model->setData(model->index(rowNum, 2), bellId);
    model->setData(model->index(rowNum, 15), remind_late_str_model);
    model->setData(model->index(rowNum, 3), int(0));
    model->setData(model->index(rowNum, 4), int(model->index(rowNum-1, 4).data().toInt()+1));
    model->setData(model->index(rowNum, 5), repeat_str_model);
    model->setData(model->index(rowNum, 13), clockName);
    model->setData(model->index(rowNum,16),true);
    //主键
    auto id = Utils::getRandomId();
    model->setData(model->index(rowNum, 14), id);
    for (int i=0; i<7; i++) {
        model->setData(model->index(rowNum, i+6), repeat_day[i]);
    }
    model->submitAll();

    for (int i=0; i<rowNum; i++) {
        delete aItem[i];
        delete w1[i];
    }
    qDebug() << model->index(rowNum, 0).data().toString()
             << model->index(rowNum, 1).data().toString()
             << QFileInfo( model->index(rowNum, 2).data().toString() ).fileName();
    updateAlarmClock();
}

void Clock::setTimerAlarmStart()
{
    int localNum = m_selectBtnUtil->getCurrentLocale();
    int ringMoveHeight=timer_alarm_start24->pos().y()+6;
    if(localNum==1||localNum==2){
        timer_alarm_startAPM->move(64,ringMoveHeight);
    }else{
        timer_alarm_startAPM->move(268,ringMoveHeight);
    }
    int apmIndex = timer_alarm_startAPM->m_currentValue-1;
    int hourNum = timer_alarm_start24->m_currentValue;
    timer_alarm_start24->m_currentValue = hourNum%12+apmIndex*12;
    timer_alarm_start24->homing();
}

QString Clock::getSelectBellId(QComboBox *temp)
{
    int num=temp->currentIndex();
    QString id = m_selectBtnUtil->getBellIdByIndex(num);
    return id;
}

QString Clock::addAlarm(clockInterface::RequestParams param)
{
    return addAlarm(param.clockName,param.hour,param.minute);
}

QString Clock::addAlarmJosn(QString param)
{
    neb::CJsonObject oJson(param.toStdString());
    QString clockName = QString::fromStdString(oJson["clockName"].ToString());
    QString hour = QString::fromStdString(oJson["hour"].ToString());
    QString minute = QString::fromStdString(oJson["minute"].ToString());
    if(FieldValidUtil::isNull(hour)){
        return formatReturnMsg(clockInterface::FAIL,"小时为空");
    }
    if(FieldValidUtil::isNull(minute)){
        return formatReturnMsg(clockInterface::FAIL,"分钟为空");
    }
    return addAlarm(clockName,  hour.toInt(),  minute.toInt());
}

QString Clock::updateClockByIdJosn(QString param)
{
    neb::CJsonObject oJson(param.toStdString());
    QString id = QString::fromStdString(oJson["id"].ToString());
    if(FieldValidUtil::isNull(id)){
        return formatReturnMsg(clockInterface::FAIL,"主键id为空");
    }
    id = FieldValidUtil::QStringFilter(id);
    QString clockName = QString::fromStdString(oJson["clockName"].ToString());
    QString hour = QString::fromStdString(oJson["hour"].ToString());
    QString minute = QString::fromStdString(oJson["minute"].ToString());
    if(FieldValidUtil::isNull(clockName)&&FieldValidUtil::isNull(hour)&&FieldValidUtil::isNull(minute)){
        return formatReturnMsg(clockInterface::FAIL,"没有需要修改的数据");
    }
    updateClockDatabase(id,clockName,hour,minute,0);
    return formatReturnMsg(clockInterface::SUCCESS,"闹钟修改成功");
}

QString Clock::selectClockByIdJosn(QString param)
{
    neb::CJsonObject oJson(param.toStdString());
    QString id = QString::fromStdString(oJson["id"].ToString());
    if(FieldValidUtil::isNull(id)){
        return formatReturnMsg(clockInterface::FAIL,"主键id为空");
    }
    id = FieldValidUtil::QStringFilter(id);
    auto sqlQuery = getClockByPK(id);
    QString queryId = sqlQuery.value(14).toString();
    if(FieldValidUtil::isNull(queryId)){
        return formatReturnMsg(clockInterface::FAIL,"查询结果为空");
    }
    oJson.Add("name",sqlQuery.value(13).toString().toStdString());
    oJson.Add("hour",sqlQuery.value( 0).toInt());
    oJson.Add("minute",sqlQuery.value( 1).toInt());
    return formatReturnMsg(oJson,clockInterface::SUCCESS,"闹钟查询成功");
}

QString Clock::deleteClockByIdJosn(QString param)
{
    neb::CJsonObject oJson(param.toStdString());
    QString id = QString::fromStdString(oJson["id"].ToString());
    if(FieldValidUtil::isNull(id)){
        return formatReturnMsg(clockInterface::FAIL,"主键id为空");
    }
    id = FieldValidUtil::QStringFilter(id);
    deleteAlarmDatabase(id);
    return formatReturnMsg(clockInterface::SUCCESS,"闹钟删除成功");
}

QString Clock::addAlarm(QString clockName, int hour, int minute)
{
    //表单验证
    if(FieldValidUtil::isNull(clockName)){
        return formatReturnMsg(clockInterface::FAIL,"闹钟名为空");
    }
    QString clockNameQstr = FieldValidUtil::QStringFilter(clockName);
    if(clockNameQstr.length()>16){
        return formatReturnMsg(clockInterface::FAIL,"闹钟名超过16个字");
    }
    if(!FieldValidUtil::isValueBetweenRange(hour,0,23)){
        return formatReturnMsg(clockInterface::FAIL,"小时位不是0-23之间的整数");
    }
    if(!FieldValidUtil::isValueBetweenRange(minute,0,59)){
        return formatReturnMsg(clockInterface::FAIL,"分钟位不是0-59之间的整数");
    }
    int rowNum;
    rowNum = model->rowCount();
    if(rowNum>=20){
        return formatReturnMsg(clockInterface::FAIL,"闹钟数已达上限");
    }

    //存储到数据库
    model->insertRow(rowNum);
    model->setData(model->index(rowNum, 0), hour);
    model->setData(model->index(rowNum, 1), minute);
    model->setData(model->index(rowNum, 2), tr("glass"));
    model->setData(model->index(rowNum, 3), int(0));
    model->setData(model->index(rowNum, 4), int(model->index(rowNum-1, 4).data().toInt()+1));
    model->setData(model->index(rowNum, 5), tr("No repetition"));
    model->setData(model->index(rowNum, 13), clockNameQstr);
    //主键
    auto id = Utils::getRandomId();
    model->setData(model->index(rowNum, 14), id);
    for (int i=0; i<7; i++) {
        model->setData(model->index(rowNum, i+6), 1);
    }
    model->submitAll();
    for (int i=0; i<rowNum; i++) {
        delete aItem[i];
        delete w1[i];
    }
    updateAlarmClock();
    updateAlarmItemFront(CURRENT_FONT_SIZE);
    neb::CJsonObject oJson;
    oJson.Add("id",id.toStdString());
    return formatReturnMsg(oJson,clockInterface::SUCCESS,"闹钟添加成功");
}

QString Clock::formatReturnMsg(neb::CJsonObject oJson, clockInterface::STATUS_CODE status, std::string msg)
{
    oJson.Add("status",status);
    oJson.Add("msg",msg);
    return QString::fromStdString(oJson.ToString());
}
/**
 * @brief 构造返回值
 * @param status 状态
 * @param msg 返回信息
 * @return
 */
QString Clock::formatReturnMsg(STATUS_CODE status, string msg)
{

    neb::CJsonObject oJson;
    oJson.Add("status",status);
    oJson.Add("msg",msg);
    return QString::fromStdString(oJson.ToString());
}





/*
 *闹钟新建界面取消回调
 * Cancel callback in alarm new interface
 */
void Clock::alarmCancelSave()
{
    mainWidget->setCurrentIndex(1);
    mainWidget->raise();
    playController::getInstance().stop();
}

/*
 * 双击闹钟打开重编辑页面
 * Double click the alarm clock to open the re edit page
 */
void Clock::listdoubleClickslot()
{
    onEditPage = true;
    mainWidget->setCurrentIndex(3);
    alarmPage->show();
    //以链表序号找寻数据
    auto curentId = getClockPkByCurrentNum();
    //根据id查询数据
    auto sqlQuery = getClockByPK(curentId);
    timer_alarm_start24->m_currentValue=sqlQuery.value( 0).toInt();
    timer_alarm_start60->m_currentValue=sqlQuery.value( 1).toInt();
    if(timer_alarm_start24->m_currentValue>=12){
        timer_alarm_startAPM->m_currentValue=2;
    }else{
        timer_alarm_startAPM->m_currentValue=1;
    }
    repeat_new_or_edit_flag = 1;
    QString werk_day ;
    int werk = 0;
    for (int i=0; i<7; i++) {
        if (sqlQuery.value( 6+i).toInt()) {
            if(i == 0){
                werk_day = werk_day + tr("Mon")+"  ";
            }else if(i == 1){
                werk_day = werk_day + tr("Tue")+"  ";
            }else if(i == 2){
                werk_day = werk_day + tr("Wed")+"  ";
            }else if(i == 3){
                werk_day = werk_day + tr("Thu")+"  ";
            }else if(i == 4){
                werk_day = werk_day + tr("Fri")+"  ";
            }else if(i == 5){
                werk_day = werk_day + tr("Sat")+"  ";
            }else if(i == 6){
                werk_day = werk_day + tr("Sun")+"  ";
            }
        }else{
            werk = 1;
        }
    }
    if(werk){
        dialog_repeat->line_edit_->setText(werk_day);
    }else {
        dialog_repeat->line_edit_->setText(tr("Every day"));
    }
    if(sqlQuery.value( 5).toString() == tr("  work") || sqlQuery.value( 5).toString() == tr("  工作日")){
        dialog_repeat->line_edit_->setText(tr("  work"));
    }
    if(sqlQuery.value( 5).toString() == tr("No repetition") || sqlQuery.value( 5).toString() == tr("不重复")){
        dialog_repeat->line_edit_->setText(tr("No repetition"));
    }
    repeat_str_model = sqlQuery.value( 5).toString();

    updateRepeatLineEditStr(dialog_repeat->line_edit_);

    QString bellId =  sqlQuery.value( 2).toString();
    auto name = m_selectBtnUtil->getBellNameById(bellId);
    dialog_music->setCurrentText(name);
    setMusicSelectDialogListById(bellId,dialog_music);

    //重复
    remind_late_str_model =  sqlQuery.value( 15).toString();
    qDebug()<<"从数据库查稍后"<<remind_late_str_model;
    int status = getRemindStatusByName(remind_late_str_model);
    remind_late_str_model = getRemindLateStrFromNum(status);
    setRemindLateSelectDialogListByName(remind_late_str_model,dialog_remind_late);

    clock_name = sqlQuery.value( 13).toString();
    clockEditOnClockNew->setText(clock_name);
    QString systemLang = QLocale::system().name();
//    if(systemLang=="ug_CN"||systemLang=="kk_KZ"||systemLang=="ky_KG"){
//        clockEditOnClockNew->setAlignment(Qt::AlignRight);
//    }else{
//        clockEditOnClockNew->setAlignment(Qt::AlignLeft);
//    }


    for (int i=0; i<7; i++) {
        if (sqlQuery.value( 6+i).toInt()) {
            repeat_day[i] = 1;
        } else {
            repeat_day[i] = 0;
        }
    }
}

QString Clock::getClockPkByCurrentNum()
{
    int num = alarmListWidget->currentRow();
    auto widgetItem = static_cast<item_new *>(alarmListWidget->itemWidget(aItem[num]));
    auto curentId = widgetItem->id();
    return curentId;
}

QSqlQuery Clock::getClockByPK(QString id)
{
    auto sqlQuery = clock_sql::getQSqlQuery();
    sqlQuery.prepare("select * from clock where id=:id");
    sqlQuery.bindValue(":id",id);
    sqlQuery.exec();
    sqlQuery.next();
    return sqlQuery;
}



/*
 * 闹钟重编辑页面删除闹钟回调
 * Alarm re edit page delete alarm callback
 */
void Clock::deleteAlarm()
{
    int rowNum = model->rowCount();


/*
    delete_msg *deletemsg = new delete_msg();
    QPointF position = this->pos();
    deletemsg->move(position.x()+35,position.y()+200);
    deletemsg->exec();
*/

/*
 * 重新适配QMessageBox控件
 * Refit the qmessagebox control
 */
    int ret;
    QMessageBox msg(this);

    msg.setIcon(QMessageBox::Question);
    msg.setWindowTitle(QObject::tr("Hint"));
    msg.setText(QObject::tr("Are you sure to delete？"));
    msg.addButton(QObject::tr("sure"), QMessageBox::AcceptRole);
    msg.addButton(QObject::tr("cancel"), QMessageBox::RejectRole);
    kdk::UkuiStyleHelper::self()->removeHeader(&msg);


    ret = msg.exec();

    if (ret == QMessageBox::RejectRole) {
        qDebug()<<"dbq-不删除";
    } else {
        //删除数据
        auto curentId = getClockPkByCurrentNum();
        deleteAlarmDatabase(curentId);
        rowNum = model->rowCount();
        qDebug() << rowNum;

    }
    //闹钟页面子项
    updateAlarmItemFront(CURRENT_FONT_SIZE);
}

void Clock::deleteAlarmDatabase(QString id)
{
    int rowNum = model->rowCount();
    auto sqlQuery = clock_sql::getQSqlQuery();
    sqlQuery.prepare("delete from clock where id=:id");
    sqlQuery.bindValue(":id",id);
    sqlQuery.exec();
    for (int i=0; i<rowNum; i++) {
                delete w1[i];
                delete aItem[i];
    }
    model->submitAll();
    updateAlarmClock();
    updateAlarmItemFront(CURRENT_FONT_SIZE);
}

void Clock::updateClockDatabase(QString id, QString name, QString hour, QString minute, int onOff)
{
    QString sql = "update clock set ";
    if(FieldValidUtil::isNotNull(name)){
        sql = sql.append(" Name=:clockName , ");
    }
    if(FieldValidUtil::isNotNull(hour)){
        sql = sql.append(" Hour=:hour , ");
    }
    if(FieldValidUtil::isNotNull(minute)){
        sql = sql.append(" Minute=:minute , ");
    }
    sql = sql.append(" on_or_off=:onOff , ");
    sql = sql.remove(sql.length()-2,2);
    sql = sql.append(" where Id=:id");
    int rowNum = model->rowCount();
    auto sqlQuery = clock_sql::getQSqlQuery();
    sqlQuery.prepare(sql);
    sqlQuery.bindValue(":id",id);
    //绑定数据
    if(FieldValidUtil::isNotNull(name)){
        name = FieldValidUtil::QStringFilter(name);
        sqlQuery.bindValue(":clockName",name);
    }
    if(FieldValidUtil::isNotNull(hour)){
        sqlQuery.bindValue(":hour",hour.toInt());
    }
    if(FieldValidUtil::isNotNull(minute)){
        sqlQuery.bindValue(":minute",minute.toInt());
    }
    sqlQuery.bindValue(":onOff",onOff);
    sqlQuery.exec();
    model->submitAll();
    if(FieldValidUtil::isNotNull(name)||FieldValidUtil::isNotNull(hour)||FieldValidUtil::isNotNull(minute)){
        for (int i=0; i<rowNum; i++) {
                    delete w1[i];
                    delete aItem[i];
        }
        updateAlarmClock();
        updateAlarmItemFront(CURRENT_FONT_SIZE);
    }
}



/*
 * 闹钟开关
 * Alarm switch
 */
void Clock::OnOffAlarm()
{
    int i=0 ;
    KSwitchButton *btn = qobject_cast<KSwitchButton*>(QObject::sender());
    while (btn != w1[i]->alarm_on_off0) {
        i++;
    }
    QString id = w1[i]->id();
    auto sqlQuery  = getClockByPK(id);
    if (sqlQuery.value(3).toInt() == 0) {
        w1[i]->closeStyle(CURRENT_FONT_SIZE);
        updateClockDatabase(id,nullptr,nullptr,nullptr,1);
    } else {
        w1[i]->openStyle(CURRENT_FONT_SIZE);
        updateClockDatabase(id,nullptr,nullptr,nullptr,0);
    }
}
/*
 * 不重复时单独关闭闹钟
 * Turn off the alarm separately if it is not repeated
 */
void Clock::offAlarm(int i)
{
    w1[i]->alarm_on_off0->setChecked(false);
    model->setData(model->index(i, 3), int(1));
    model->submitAll();

    int rowNum = model->rowCount();
    for (int i = 0; i < rowNum; i++) {
        delete aItem[i];
        delete w1[i];
    }
    updateAlarmClock();
}

/*
 * 倒计时音乐选择
 * Countdown music selection
 */

void Clock::countdownMusicSellect()
{
    refreshMusicSelectList(count_music_sellect);
}

/*
 * 闹钟初始化工作日选择界面绘制回调
 * Alarm clock initialization workday selection interface drawing callback
 */
void Clock::alarmRepeat()
{
    int num;
    //repeat_new_or_edit_flag 编辑是1
    if(repeat_new_or_edit_flag)
        num = alarmListWidget->currentRow();
    else {
        num= model->rowCount();
    }
        dialog_repeat->btn[0]->textLabel->setText(tr("No repetition"));
        dialog_repeat->btn[1]->textLabel->setText(tr("Workingday"));
        dialog_repeat->btn[2]->textLabel->setText(tr("Mon"));
        dialog_repeat->btn[3]->textLabel->setText(tr("Tue"));
        dialog_repeat->btn[4]->textLabel->setText(tr("Wed"));
        dialog_repeat->btn[5]->textLabel->setText(tr("Thu"));
        dialog_repeat->btn[6]->textLabel->setText(tr("Fri"));
        dialog_repeat->btn[7]->textLabel->setText(tr("Sat"));
        dialog_repeat->btn[8]->textLabel->setText(tr("Sun"));
        connect(dialog_repeat,&CustomComBox::comboxPopup,this,[=](){
            for (int i=0; i<7; i++) {
                if (repeat_day[i]) {
                    //前两个是不重复和工作日
                    dialog_repeat->btn[i+2]->iconLabel->setPixmap(repeat_on_Pixmap);
                } else {
                    dialog_repeat->btn[i+2]->iconLabel->setPixmap(repeat_off_Pixmap);
                }
            }
        });
        connect(dialog_repeat->list_widget_,&CustomListWidget::getPosition,this,[=](QPointF position){
            int honum=0;
            if(comboxclickedflag){
                honum = dialog_repeat->list_widget_->currentRow();
            }else{
                honum=dialog_repeat->list_widget_->row(dialog_repeat->list_widget_->itemAt(position.x(),position.y()));
                dialog_repeat->setCurrentHoverNum(honum);
            }
            dialog_repeat->setTextHoverStyle(honum);
        });
}

/*
 * 倒计时音乐选择单机回调
 * Countdown music selection single callback
 */
void Clock::countMusicListclickslot()
{
    int num=count_music_sellect->currentIndex();
    int size=count_music_sellect->count();
    //最后一个自定义铃声
    if(num==(size-1)){
        addDivBell(count_music_sellect,Clock::count_down);
    }else{
        QString id = m_selectBtnUtil->getBellIdByIndex(num);
        QString path = m_selectBtnUtil->getBellPathById(id);
        QString name = m_selectBtnUtil->getBellNameById(id);
        //排除无
        if(num==0){
            path="";
        }
        playMusicFromPath(path);
        model_setup->setData(model_setup->index(0, 1), id);
        model_setup->submitAll();
    }
}

void Clock::playMusicFromPath(QString path)
{
//    delete musicSelectPlay;
//    musicSelectPlay = new QMediaPlayer(this);
    //停止上次播放
//    stopHisPlay();

//    delete music;
//    music = new QMediaPlayer();
//    music->setMedia(QUrl::fromLocalFile(path));
//    music->play();

    if(m_muteOn){
        playController::getInstance().playSingleSong(path,0);
            playController::getInstance().pause();
    }else{
        playController::getInstance().playSingleSong(path,0);
    }
    musicStartTime = QTime::currentTime();
}

void Clock::stopHisPlay()
{
    if(hisPlayer!=nullptr){
        hisPlayer->stop();
    }
}
//TODO 加按钮
void Clock::addDivBell(QComboBox *temp, btnType type)
{
    QString filePath = m_selectBtnUtil->openAudioFileDialog(temp);
    int size=count_music_sellect->count();
    if(FieldValidUtil::isNotNull(filePath)){
        qWarning()<<"dbq-开始复制"<<filePath;
        //复制文件
        QString toPatn = m_selectBtnUtil->copyAudioFile(filePath);
        if(!toPatn.isEmpty()){
            //存储到数据库
            QString bellId = m_selectBtnUtil->saveToBellTable(toPatn);
            QString name = m_selectBtnUtil->getBellNameById(bellId);

            if(type==Clock::count_down){
                count_music_sellect->insertItem(size-1,name);
                count_music_sellect->setCurrentIndex(size-1);
            }else{
                dialog_music->insertItem(size-1,name);
                dialog_music->setCurrentIndex(size-1);
            }

            playMusicFromPath(toPatn);
        }

    }
}

//倒计时执行
// Countdown execution
void Clock::statCountdown(){
    //减1算法
    if(countdown_second>0){
        countdown_second--;
    }else if(countdown_second==0&&countdown_minute>=1){
        countdown_minute--;
        countdown_second=59;
    }else if(countdown_second==0&&countdown_minute==0&&countdown_hour>=1){
        countdown_hour--;
        countdown_minute=59;
        countdown_second=59;
    }

    QString h; QString m; QString s;
    if (countdown_hour < 10){
        QString hours_str = QString::number(countdown_hour);
        h = "0"+hours_str;
    } else {
        h = QString::number(countdown_hour);
    }
    if (countdown_minute < 10) {
        QString minute_str = QString::number(countdown_minute);
        m = "0"+minute_str;
    } else {
        m = QString::number(countdown_minute);
    }

    if (countdown_second < 10) {
        QString second_str = QString::number(countdown_second);
        s = "0"+second_str;
    }else {
        s = QString::number(countdown_second);
    }
    remainTime->setText(h+TIME_SEPARATOR+m+TIME_SEPARATOR+s);
//    QString selfFont = Utils::loadFontFamilyFromTTF();
//    QFont f(selfFont);
    QFont f;
    f.setFamily("NotoSansCJKsc-Regular");
    f.setWeight(400);
    bool onTablet = GsettingSubject::getInstance()->getOnTablet();
    if(onTablet){
        f.setPixelSize(76);
    }else{
        f.setPixelSize(40);
    }
    remainTime->setFont(f);

    //设置倒计时托盘tooltip
    QString tooltip = tr("Count down");
    tooltip +=TIME_SEPARATOR_CN+h+TIME_SEPARATOR+m+TIME_SEPARATOR+s;
    updateTrayIconTooltip(tooltip);

    //小型倒计时 显示倒计时时间
    if(this->m_selectTinyCountdown){
        if(checkTinyCountdownDia()){
            tinycountdownDia->updateTimeInfo(h+TIME_SEPARATOR+m+TIME_SEPARATOR+s);
        }
    }
    //时间归零
    if (countdown_hour==0 && countdown_minute==0 && (countdown_second)==0) {
        startbtnCountdown();
        countdown_timer->stop();
        //托盘恢复默认
        setDefaultTrayIconTooltip();
        //倒计时通知弹窗
        countdownNoticeDialogShow();
    }
}

void Clock::statCountdownMsec()
{
    countdown_msec-=10;
    if(countdown_msec<=0){
        //减1算法
        if(countdown_second>0){
            countdown_second--;
        }else if(countdown_second==0&&countdown_minute>=1){
            countdown_minute--;
            countdown_second=59;
        }else if(countdown_second==0&&countdown_minute==0&&countdown_hour>=1){
            countdown_hour--;
            countdown_minute=59;
            countdown_second=59;
        }
        countdown_msec=1000;
    }
    updateCountdownTime();

}

void Clock::updateCountdownTime()
{
    //设置当前时间
    int ringmax = countdown_hour*3600 + countdown_minute*60 + countdown_second;
    countdownRunPage->countdownRunRoundBar->setValue(ringmax);

    QString h; QString m; QString s;
    if (countdown_hour < 10){
        QString hours_str = QString::number(countdown_hour);
        h = "0"+hours_str;
    } else {
        h = QString::number(countdown_hour);
    }
    if (countdown_minute < 10) {
        QString minute_str = QString::number(countdown_minute);
        m = "0"+minute_str;
    } else {
        m = QString::number(countdown_minute);
    }

    if (countdown_second < 10) {
        QString second_str = QString::number(countdown_second);
        s = "0"+second_str;
    }else {
        s = QString::number(countdown_second);
    }
    remainTime->setText(h+TIME_SEPARATOR+m+TIME_SEPARATOR+s);
//    QString selfFont = Utils::loadFontFamilyFromTTF();
//    QFont f(selfFont);
    QFont f;
    f.setFamily("NotoSansCJKsc-Regular");
    f.setWeight(400);
    bool onTablet = GsettingSubject::getInstance()->getOnTablet();
    if(onTablet){
        f.setPixelSize(76);
    }else{
        f.setPixelSize(40);
    }
    remainTime->setFont(f);
    //设置倒计时托盘tooltip
    QString tooltip = tr("Count down");
    tooltip +=TIME_SEPARATOR_CN+h+TIME_SEPARATOR+m+TIME_SEPARATOR+s;
    updateTrayIconTooltip(tooltip);

    //小型倒计时 显示倒计时时间
    if(this->m_selectTinyCountdown){
        if(checkTinyCountdownDia()){
            tinycountdownDia->updateTimeInfo(h+TIME_SEPARATOR+m+TIME_SEPARATOR+s);
        }
    }
//    qDebug()<<"dbq-倒计时"<<countdown_hour<<":"<<countdown_minute<<":"<<countdown_second;
    //时间归零
    if (countdown_hour==0 && countdown_minute==0 && (countdown_second)==0) {
        startbtnCountdown();
        countdown_timer->stop();
        //托盘恢复默认
        setDefaultTrayIconTooltip();
        //倒计时通知弹窗
        countdownNoticeDialogShow();
    }
}

/*
 * 倒计时通知弹窗
 * Countdown notification pop-up
 */
void Clock::countdownNoticeDialogShow()
{
    //关闭tiny倒计时
    if(checkTinyCountdownDia()){
        tinycountdownDia->set_dialog_close();
    }
    model_setup->select();
    countdownNoticeDialog->playMusic();
    NoticeAlarmPoolUtil::getInstance()->
            inseartNoticesMap(countdownNoticeDialog->getNoticeId(),countdownNoticeDialog);
}



/*
 * 倒计时开始-结束
 * Countdown start end callback
 */
void Clock::startbtnCountdown(){
    if (!countdown_isStarted) {
        playController::getInstance().stop();

        //点击了开始
        if (hourTimerRing->m_currentValue==0 && minuteTimeRing->m_currentValue==0 && secondTimeRing->m_currentValue==0) {
            return;
        }
        //当前剩余时间，单位秒
        int ringmax = hourTimerRing->m_currentValue*3600 + minuteTimeRing->m_currentValue*60 + secondTimeRing->m_currentValue;
        //进度圈
        countdownRunPage->countdownRunRoundBar->setRange(0,ringmax);
        //切换进度条颜色
        countdownRunPage->countdownRunRoundBar->switchRunRingColor();
        startCountdownBtn->setStyleSheet("");
        countdown_isStarted=1;
        //结束
        startCountdownBtn->setText(tr("End"));
        //点击开始，刷新数值
        refreshCountdownLabel11Flag = true;
        //设置倒计时初始时间label9 中间数字
        setcoutdownNumber(hourTimerRing->m_currentValue, minuteTimeRing->m_currentValue, secondTimeRing->m_currentValue);//获取转轮当前值
        //倒计时页面
        countdownStackedW->setCurrentIndex(1);
        countdown_timer->start();
        //光圈的进度值修改定时启动
        bool onTablet = GsettingSubject::getInstance()->getOnTablet();
        if(onTablet){
            countdownBellLabelOnRun->hide();
            countdownBellLabelOnSet->hide();
            count_music_sellect->hide();
        }else{
            countdownBellLabelOnRun->show();
            countdownBellLabelOnSet->show();
            count_music_sellect->show();
        }

    } else {
        //点击了结束，或者时间耗尽
        countdownRunPage->countdownRunRoundBar->setRange(0,COUNTDOWN_TIME);
        countdownRunPage->countdownRunRoundBar->setValue(COUNTDOWN_TIME);/*初始化倒计时进度圈
                                               Initialize countdown progress circle*/
        countdown_timer->stop();
        countdown_isStarted=0;
        countdown_isStarted_2=0;
        hourTimerRing->m_currentValue = 0;
        minuteTimeRing->m_currentValue = 0;
        secondTimeRing->m_currentValue = 0;
        startCountdownBtn->setText(tr("start"));
        remainTime->setText("00:00:00");
        //切换到倒计时滚轮页
        countdownStackedW->setCurrentIndex(0);
        //暂停
        suspendCountdownBtn->setText(tr("suspend"));

        QPalette palette = suspendCountdownBtn->palette();
        QColor ColorPlaceholderText(248,163,76,255);
        QBrush brush2;
        brush2.setColor(ColorPlaceholderText);
        //主题框架1.0.6-5kylin2
        palette.setColor(QPalette::Highlight,QColor(248,163,76,255));
        palette.setColor(QPalette::Button,QColor(248,163,76,255));
        palette.setBrush(QPalette::ButtonText, QBrush(Qt::white));
//        ui->suspendCountdownBtn->setPalette(palette);
        //小窗体清零，隐藏
        if(checkTinyCountdownDia()){
            tinycountdownDia->clearData();
        }
        //恢复默认托盘
        setDefaultTrayIconTooltip();

        count_music_sellect->show();
        countdownBellLabelOnRun->show();
        countdownBellLabelOnSet->show();
    }
    return;
}

void Clock::tinyCountdownFinish()
{
    tinycountdownDia->set_dialog_close();
    activeWindow();
    startbtnCountdown();
}

/*
 * 设置倒计时初始时间
 * Set the initial countdown time
 */
void Clock::setcoutdownNumber(int h1, int m1, int s1){
    countdown_hour=h1; countdown_minute=m1 ; countdown_second=s1;

    QString h; QString m; QString s;

    if (countdown_hour < 10){
        QString hours_str = QString::number(countdown_hour);
        h = "0"+hours_str;
    } else {
        h = QString::number(countdown_hour);
    }

    if (countdown_minute < 10) {
        QString minute_str = QString::number(countdown_minute);
        m = "0"+minute_str;
    } else {
        m = QString::number(countdown_minute);
    }

    if (countdown_second < 10) {
        QString second_str = QString::number(countdown_second);
        s = "0"+second_str;
    } else {
        s = QString::number(countdown_second);
    }

    remainTime->setText(h+TIME_SEPARATOR+m+TIME_SEPARATOR+s);
//    QString selfFont = Utils::loadFontFamilyFromTTF();
//    QFont f(selfFont);
    QFont f;
    f.setFamily("NotoSansCJKsc-Regular");
    f.setWeight(400);
    bool onTablet = GsettingSubject::getInstance()->getOnTablet();
    if(onTablet){
        f.setPixelSize(76);
    }else{
        f.setPixelSize(40);
    }
    remainTime->setFont(f);
    //获取倒计时结束时间
    getCountdownOverTime();
}

/*
 * 倒计时5分钟
 * Countdown 5 minutes set callback
 */
void Clock::onMin_5btnClicked()
{
    hourTimerRing->m_currentValue = 0;
    minuteTimeRing->m_currentValue = 5;
    secondTimeRing->m_currentValue = 0;
    setcoutdownNumber(0, 5, 0);
}

/*
 * 获取倒计时结束时间
 * Get countdown end time
 */
void Clock::getCountdownOverTime()
{
    QTime time = QTime::currentTime();
    int timeH = time.hour();
    int timeM = time.minute();
    int timeS = time.second();
    if(refreshCountdownLabel11Flag){
        x_h = countdown_hour + timeH;
        x_m = countdown_minute + timeM;
        //分钟位进1
        if(countdown_second+timeS>=60){
            x_m+=1;
        }
        refreshCountdownLabel11Flag = false;
        if (x_m >= 60) {
            x_m = x_m - 60;
            x_h ++;
        }
    }
    if (x_h >= 48) {
         x_h = x_h - 48;
         countdownAlarmTime->setText(tr("after tomorrow")+formatX_h(x_h)+TIME_SEPARATOR+changeNumToStr(x_m));
     } else if (x_h >= 24) {
         x_h = x_h - 24;
         countdownAlarmTime->setText(tr("Tomorrow")+formatX_h(x_h)+TIME_SEPARATOR+changeNumToStr(x_m));
    } else{
        countdownAlarmTime->setText(formatX_h(x_h)+TIME_SEPARATOR+changeNumToStr(x_m));
    }
}
//上下午格式
QString Clock::get12hourStr(int x_h)
{
    QString str;
    //12时
   if (x_h >= 12) {
       x_h = x_h - 12;
       str=tr("PM")+" "+changeNumToStr(x_h);
   } else {
       str=tr("AM")+" "+changeNumToStr(x_h);
   }
   return str;
}
/**
 * @brief 创建用户手册dbus客户端
 */
void Clock::createUserGuideDebusClient()
{
    // 用户手册
    QString serviceName = "com.kylinUserGuide.hotel"
                          + QString("%1%2").arg("_").arg(QString::number(getuid()));
    //创建dbus-client
    userGuideInterface = new QDBusInterface(serviceName,
                                            "/",
                                            "com.guide.hotel",
                                            QDBusConnection::sessionBus());
    qDebug() << "connect to kylinUserGuide" << userGuideInterface->isValid();
    if (!userGuideInterface->isValid()) {
        qDebug() << "fail to connect to kylinUserGuide";
        qDebug() << qPrintable(QDBusConnection::sessionBus().lastError().message());
        return;
    }
}

void Clock::onTinyClicked()
{
    this->m_selectTinyCountdown=true;
    //主窗体最小化
//    kdk::WindowManager::minimizeWindow(m_pid);
    setWindowState(Qt::WindowMinimized);
    tinycountdownDia->showThisWindow();
    primaryManager->moveUnderMultiScreen(PrimaryManager::UP_RIGHT,tinycountdownDia,1);
}

void Clock::activeWindow()
{
    if(primaryManager->checkWayland()){
        setWindowState(windowState() & ~Qt::WindowMinimized);
        kdk::WindowManager::activateWindow(m_pid);
        showThisWindow();
    }else{
        setWindowState(Qt::WindowActive);
    }
}
void Clock::showThisWindow()
{
    kdk::UkuiStyleHelper::self()->removeHeader(this);
    this->show();
    QRect rect = utils->centerToScreenQRect(this);
    qWarning()<<"dbq-showThisWindow"<<rect;
    kdk::WindowManager::setGeometry(this->windowHandle(),rect);
}

void Clock::selectRemindLate()
{
    dialog_remind_late->addItem(tr("none"));
    dialog_remind_late->addItem(tr("five mins late"));
    dialog_remind_late->addItem(tr("ten mins late"));
    dialog_remind_late->addItem(tr("twenty mins late"));
    dialog_remind_late->addItem(tr("thirsty mins late"));
    dialog_remind_late->addItem(tr("one hour late"));
}

//刷新时间格式
QString Clock::formatX_h(int x_h)
{
    QString str;
    //跟随系统时间
   if(m_timeZone == "24"){
       str=changeNumToStr(x_h);
   }else{
       //12时
      str =get12hourStr(x_h);
   }
    return str;
}
/*
 * 单位变双位
 * Integer to character
 */
QString Clock::changeNumToStr(int alarmHour)
{
    QString str;
    if (alarmHour < 10) {
        QString hours_str = QString::number(alarmHour);
        str = "0"+hours_str;
    } else {
        str = QString::number(alarmHour);
    }
    return str;
}
QString Clock::changeNumToStrWithAm(int alarmHour)
{
    QString str;
    if (system_time_flag) {
        //24时制
        str = changeNumToStr(alarmHour);//转换int为QString
    } else {
        //12时制
        if (alarmHour >= 12) {
            str+=tr("PM")+" ";
            if (alarmHour == 12) {
                str+=changeNumToStr(alarmHour);
            } else {
                str+=changeNumToStr(alarmHour-12);
            }
        } else {
            str+=tr("AM")+" ";
            if (alarmHour == 0) {
                str+=changeNumToStr(12);
            } else {
                str+=changeNumToStr(alarmHour);
            }
        }
    }
    return str;
}
/*
 * 倒计时-暂停继续
 * Countdown - pause resume callback
 */
void Clock::onCountPushClicked()
{
    tinycountdownDia->updateOnRunState(countdown_isStarted_2);
    if (countdown_isStarted_2){
        //点击了继续
        suspendCountdownBtn->setText(tr("suspend"));
        //切换进度条颜色
        countdownRunPage->countdownRunRoundBar->switchRunRingColor();

        QPalette palette = suspendCountdownBtn->palette();
        QColor ColorPlaceholderText(248,163,76,255);
        QBrush brush2;
        brush2.setColor(ColorPlaceholderText);
        //主题框架1.0.6-5kylin2
        palette.setColor(QPalette::Highlight,QColor(248,163,76,255));
        palette.setColor(QPalette::Button,QColor(248,163,76,255));
        palette.setBrush(QPalette::ButtonText, QBrush(Qt::white));
//        ui->suspendCountdownBtn->setPalette(palette);

        countdown_timer->start();
        countdown_isStarted_2=0;
        refreshCountdownLabel11Flag = true;
        getCountdownOverTime();
    } else {
        //点击了暂停
        suspendCountdownBtn->setText(tr("continue"));
        //切换进度条颜色
        countdownRunPage->countdownRunRoundBar->switchStopRingColor();

        QPalette palette = suspendCountdownBtn->palette();
        QColor ColorPlaceholderText(SWITCH_BTN_HIGHLIGHT_BACK_COLOR);
        QBrush brush2;
        brush2.setColor(ColorPlaceholderText);
        //主题框架1.0.6-5kylin2
        palette.setColor(QPalette::Highlight,QColor(69, 173, 110,255));
        palette.setColor(QPalette::Button,QColor(69, 173, 110,255));
        palette.setBrush(QPalette::ButtonText, QBrush(Qt::white));
//        ui->suspendCountdownBtn->setPalette(palette);

        countdown_timer->stop();
        countdown_isStarted_2=1;
    }

    return;
}

/*
 * 倒计时初始数字转盘
 * Countdown initial digital dial
 */
void Clock::countdownSetStartTime()
{

    //倒计时小时滚轮
    hourTimerRing = new VerticalScroll_99(countdownSetPage);
    h_in_m = new QLabel (countdownSetPage);
    //倒计时分钟
    minuteTimeRing = new VerticalScroll_60(countdownSetPage);
    m_in_s = new QLabel (countdownSetPage);
    //倒计时秒
    secondTimeRing = new VerticalScroll_60(countdownSetPage);
    after_s = new QLabel (countdownSetPage);

    hourTimerRing->resize(60,228);
    minuteTimeRing->resize(60,228);
    secondTimeRing->resize(60,228);

    after_s->hide();

    h_in_m->resize(50,30);
    h_in_m->setText(TIME_SEPARATOR);
    QFont font;
    font.setPointSize(25);
    h_in_m->setFont(font);
//    h_in_m->setText(tr("hour"));
//    h_in_m->setStyleSheet("font: 30pt 'Sans Serif';");
    m_in_s->resize(50,30);
    m_in_s->setText(TIME_SEPARATOR);
    m_in_s->setFont(font);
//    m_in_s->setText(tr("min"));
//    m_in_s->setStyleSheet("font: 30pt 'Sans Serif';");
    after_s->resize(50,30);
    after_s->setText(tr("sec"));
//    after_s->setStyleSheet("font: 30pt 'Sans Serif';");
    bool onTablet = GsettingSubject::getInstance()->getOnTablet();
    int px = 0;
    int py = 0;
    if(!onTablet){
        px = 0;
        py = 0;
    }else{
        px = this->width()/2-195;
        py = this->height()/2-168-238;
    }
    int ringMoveWidth = 67+px;
    int ringMoveHeight = 30+py;
    int timeSep = 100;
    int labelSep = 74;
    int timeLabelMoveHeight = 125+py;
    hourTimerRing->move(ringMoveWidth, ringMoveHeight);
    h_in_m->move(ringMoveWidth+labelSep,timeLabelMoveHeight);
    //hour 要比min长
    if(Utils::checkLocalUs()){
        ringMoveWidth+=timeSep+4;
    }else{
        ringMoveWidth+=timeSep;
    }
    minuteTimeRing->move(ringMoveWidth, ringMoveHeight);
    m_in_s->move(ringMoveWidth+labelSep,timeLabelMoveHeight);
    ringMoveWidth+=timeSep;
    secondTimeRing->move(ringMoveWidth, ringMoveHeight);
    after_s->move(ringMoveWidth+labelSep,timeLabelMoveHeight);
    //配置倒计时页的开始按钮
    connect(startCountSingle, SIGNAL(clicked()), this, SLOT(startbtnCountdown()) );

    QPalette palette2 = startCountSingle->palette();
    QColor ColorPlaceholderText2(233,233,233,255);
    QBrush brush2;
    brush2.setColor(ColorPlaceholderText2);
    palette2.setColor(QPalette::Button,QColor(233,233,233,255));
    //palette2.setBrush(QPalette::ButtonText, QBrush(Qt::white));
    startCountSingle->setPalette(palette2);

    QTimer *timer_count_start;
    timer_count_start = new QTimer();
    connect(timer_count_start, SIGNAL(timeout()), this, SLOT(countStatBtnGray()));
    timer_count_start->setInterval(100);
    timer_count_start->start();

    connect(hourTimerRing,&VerticalScroll_99::BaseVerticalScroll::srcollDoubleClicked,this,[=](){
        hourTimerRing->timeEdit_99->show();
        hourTimerRing->timeEdit_99->setFocus();
    });
    connect(hourTimerRing->timeEdit_99,&QLineEdit::editingFinished,this,[=](){
        int timevalue = hourTimerRing->timeEdit_99->text().toInt();
        hourTimerRing->m_currentValue = timevalue;
        hourTimerRing->homing();
        hourTimerRing->timeEdit_99->hide();
    });
    connect(minuteTimeRing,&VerticalScroll_99::BaseVerticalScroll::srcollDoubleClicked,this,[=](){
        minuteTimeRing->timeEdit_60->show();
        minuteTimeRing->timeEdit_60->setFocus();
    });
    connect(minuteTimeRing->timeEdit_60,&QLineEdit::editingFinished,this,[=](){
        int timevalue = minuteTimeRing->timeEdit_60->text().toInt();
        minuteTimeRing->m_currentValue = timevalue;
        minuteTimeRing->homing();
        minuteTimeRing->timeEdit_60->hide();
    });
    connect(secondTimeRing,&VerticalScroll_99::BaseVerticalScroll::srcollDoubleClicked,this,[=](){
        secondTimeRing->timeEdit_60->show();
        secondTimeRing->timeEdit_60->setFocus();
    });
    connect(secondTimeRing->timeEdit_60,&QLineEdit::editingFinished,this,[=](){
        int timevalue = secondTimeRing->timeEdit_60->text().toInt();
        secondTimeRing->m_currentValue = timevalue;
        secondTimeRing->homing();
        secondTimeRing->timeEdit_60->hide();
    });
}

/*
 * 倒计时页开始键致灰
 *  Start button of countdown page grays out
 */
void Clock::countStatBtnGray()
{
    if(hourTimerRing->m_currentValue==0 && minuteTimeRing->m_currentValue==0 && secondTimeRing->m_currentValue==0) {
        startCountSingle->setEnabled(false);
        QStyleOption opt;
        opt.init(this);

        if(theme::themetype==0 || theme::themetype==2){
//            qInfo() << "11111111111111111111";
            QPalette palette2 = startCountSingle->palette();
            QColor ColorPlaceholderText2(233,233,233,255);
            QBrush brush2;
            brush2.setColor(ColorPlaceholderText2);
            palette2.setColor(QPalette::Button,QColor(233,233,233,255));
            palette2.setBrush(QPalette::ButtonText, QBrush(QColor(158,158,158,255)));
            startCountSingle->setPalette(palette2);
        }else{
//            qInfo() << "------------------";
            QPalette palette2 = startCountSingle->palette();
            QColor ColorPlaceholderText2(45,45,48,255);
            QBrush brush2;
            brush2.setColor(ColorPlaceholderText2);
            palette2.setColor(QPalette::Button,QColor(45,45,48,255));
            palette2.setBrush(QPalette::ButtonText, QBrush(QColor(58,58,58,255)));
            startCountSingle->setPalette(palette2);
        }
    }else{
        startCountSingle->setEnabled(true);
        QPalette palette2 = startCountSingle->palette();
        QBrush brush2;
        if(theme::themetype==2){
            QColor ColorPlaceholderText2(248,248,248,255);
            brush2.setColor(ColorPlaceholderText2);
            palette2.setColor(QPalette::Button,QColor(248,248,248,255));
            palette2.setBrush(QPalette::ButtonText, QBrush(Qt::black));
            startCountSingle->setPalette(palette2);

        }else if(theme::themetype==3){
            QColor ColorPlaceholderText2(65,65,65,255);
            brush2.setColor(ColorPlaceholderText2);
            palette2.setColor(QPalette::Button,QColor(65,65,65,255));
            palette2.setBrush(QPalette::ButtonText, QColor(233,233,233,255));
            startCountSingle->setPalette(palette2);
        }
    }
}


void Clock::updateLabelFront(QLabel *label, int size)
{
    QString styleSheet = "font-size:";
    styleSheet.append(QString::number(size)).append("px;");
    label->setStyleSheet(styleSheet);
}

void Clock::updateQLineEditFront(QLineEdit *lineEdit, int size)
{
    QFont font ;
    font.setPixelSize(size);
    lineEdit->setFont(font);
}
/**
 * @brief 放大闹钟子项字体
 */
void Clock::updateAlarmItemFront(int size)
{
    QListWidget * alarmList = alarmListWidget;
    for (int i=0;i<alarmList->count() ;i++ ) {
        QListWidgetItem * varItem =  alarmList->item(i);
        item_new * varWidget = static_cast<item_new*>(alarmList->itemWidget(varItem)) ;
        varWidget->commonStyle(size);
    }
}

void Clock::updateStopwatchItemFront(int size)
{
    QListWidget * stopwatchList = timeListWidget;
    for (int i=0;i<stopwatchList->count() ;i++ ) {
        QListWidgetItem * varItem =  stopwatchList->item(i);
        stopwatch_item * varWidget = static_cast<stopwatch_item*>(stopwatchList->itemWidget(varItem)) ;
        updateLabelFront(varWidget->stopwatch1,round(1.1*size));
        updateLabelFront(varWidget->stopwatch2,round(1.1*size));
        updateLabelFront(varWidget->stopwatch3,round(2.2*size));
    }
}
void Clock::updateFront(const int size)
{

    //闹钟页面子项
    updateAlarmItemFront(size);
    //秒表页面 两个时间
    updateLabelFront(timeShowBig,round(3.2*size));
    updateLabelFront(timeShowSmall,round(1.73*size));
    //秒表页面子项
    updateStopwatchItemFront(size);
    double font = 1.15;
    double lineEditFont = 1.3;
    //闹钟编辑页面
    //重复
    updateLabelFront(clockRepeatLabel,round(font*size));
    updateQLineEditFront(dialog_repeat->line_edit_,round(lineEditFont*size));
    //提醒铃声
    updateLabelFront(clockBellLabel,round(font*size));
    //稍后提醒
    updateLabelFront(clockRemindLabel,round(font*size));
    //倒计时 set 铃声
    updateLabelFront(countdownBellLabelOnSet,round(font*size));
    //倒计时 run 铃声
    updateLabelFront(countdownBellLabelOnRun,round(font*size));
    //闹钟名
    updateLabelFront(clockNamelabel,round(font*size));
    //闹钟编辑
    updateQLineEditFront(clockEditOnClockNew,round(lineEditFont*size));
}
void Clock::updateRepeatStr(QLabel *label)
{
    if(Utils::checkLocalChina()){
        updateLabelTextByLength(label,15);
    }
    if(Utils::checkLocalUs()){
        updateLabelTextByLength(label,25);
    }
}

void Clock::updateLabelStrCnEn(QLabel *label, int cnLimit, int enLimit)
{
    if(Utils::checkLocalChina()){
        updateLabelTextByLength(label,cnLimit);
    }
    if(Utils::checkLocalUs()){
        updateLabelTextByLength(label,enLimit);
    }
}
void Clock::updateLabelTextByLength(QLabel *label, int limitSize)
{
    QString str = label->text();
    if(str.length()>limitSize){
        label->setToolTip(str);
        str = Utils::getOmitStr(str,limitSize);
    }
    label->setText(str);
}
void Clock::updateRepeatLineEditStr(QLineEdit *temp)
{
    if(Utils::checkLocalChina()){
        updateLineEditTextByLength(temp,15);
    }
    if(Utils::checkLocalUs()){
        updateLineEditTextByLength(temp,25);
    }
}

void Clock::updateLineEditStrCnEn(QLineEdit *temp, int cnLimit, int enLimit)
{
    if(Utils::checkLocalChina()){
        updateLineEditTextByLength(temp,cnLimit);
    }
    if(Utils::checkLocalUs()){
        updateLineEditTextByLength(temp,enLimit);
    }
}

void Clock::updateLineEditTextByLength(QLineEdit *temp, int limitSize)
{
    QString str = temp->text();
    if(str.length()>limitSize){
        temp->setToolTip(str);
        str = Utils::getOmitStr(str,limitSize);
    }
    temp->setText(str);
}


/*
 * 闹钟初始化数字转盘
 * Alarm clock initialization digital turntable drawing
 */
void Clock::alarmSetStartTime()
{
    shadow = new QWidget(editAlarmPage);
    shadow->move(115,58);
    shadow->resize(160,58);
    //闹钟小时滚轮
    timer_alarm_start24 = new VerticalScroll_24(editAlarmPage, this);
    QLabel * h_in_m = new QLabel (editAlarmPage);
    //闹钟分钟滚轮
    timer_alarm_start60 = new VerticalScroll_60(editAlarmPage);
    //闹中上下午滚轮
    timer_alarm_startAPM = new VerticalScroll_APM(editAlarmPage);

    timer_alarm_start24->resize(63,228);
    timer_alarm_start60->resize(63,228);
    timer_alarm_startAPM->resize(50,228);

    QLabel * hour_ring = new QLabel (editAlarmPage);
    QLabel * min_ring = new QLabel (editAlarmPage);

    hour_ring->hide();
    min_ring->hide();

    hour_ring->setAlignment(Qt::AlignHCenter);
    min_ring->setAlignment(Qt::AlignHCenter);

    h_in_m->resize(10,40);
    h_in_m->setText(TIME_SEPARATOR);
    h_in_m->setStyleSheet("font: 25pt;");

    hour_ring->resize(50,30);
    hour_ring->setText(tr("hour"));
    hour_ring->setStyleSheet("font: 13pt ;color: rgb(148, 148, 148);");
    min_ring->resize(50,30);
    min_ring->setText(tr("min"));
    min_ring->setStyleSheet("font: 13pt ;color: rgb(148, 148, 148);");
    int ringMoveHeight = -12;
    timer_alarm_start24->move(116, ringMoveHeight);
    hour_ring->move(140,7);
    h_in_m->move(189,78);
    timer_alarm_start60->move(206, ringMoveHeight);
    min_ring->move(212,7);

    //上下午滚轮初始化
    setTimerAlarmStart();

    connect(timer_alarm_start24,&VerticalScroll_24::BaseVerticalScroll::srcollDoubleClicked,this,[=](){
        timer_alarm_start24->timeEdit_24->show();
        timer_alarm_start24->timeEdit_24->setFocus();
    });
    connect(timer_alarm_start24->timeEdit_24,&QLineEdit::editingFinished,this,[=](){
        int timevalue = timer_alarm_start24->timeEdit_24->text().toInt();
        timer_alarm_start24->m_currentValue = timevalue;
        timer_alarm_start24->homing();
        timer_alarm_start24->timeEdit_24->hide();
    });
    connect(timer_alarm_start60,&VerticalScroll_99::BaseVerticalScroll::srcollDoubleClicked,this,[=](){
        timer_alarm_start60->timeEdit_60->show();
        timer_alarm_start60->timeEdit_60->setFocus();
    });
    connect(timer_alarm_start60->timeEdit_60,&QLineEdit::editingFinished,this,[=](){
        int timevalue = timer_alarm_start60->timeEdit_60->text().toInt();
        timer_alarm_start60->m_currentValue = timevalue;
        timer_alarm_start60->homing();
        timer_alarm_start60->timeEdit_60->hide();
    });
}

/*
 * 重复选项单击回调
 * Repeat option click callback
 */
void Clock::repeatListclickslot(int num)
{
    dialog_repeat->comboxClicked=true;
    dialog_repeat->setCurrentHoverNum(num);
//    dialog_repeat->setTextHoverStyle(num);
    comboxclickedflag = true;
    QString day[7] ;
    day[0]= tr("Mon")+"  ";
    day[1] = tr("Tue")+"  ";
    day[2] = tr("Wed")+"  ";
    day[3] = tr("Thu")+"  ";
    day[4] = tr("Fri")+"  ";
    day[5] = tr("Sat")+"  ";
    day[6] = tr("Sun")+"  ";
    //存储"重复"数据
    switch (num)
    {
    case 0:
        dialog_repeat->line_edit_->setText(tr("No repetition"));
        repeat_str_model = tr("No repetition");
        //不重复
        for (int i=0; i<7; i++) {
            // 周一到周日 全存1
            repeat_day[i] = 1;
            qDebug() << repeat_day[i];
            //周一到周日 设为不选中 但后续会被覆盖？
            dialog_repeat->btn[i+2]->iconLabel->setPixmap(repeat_on_Pixmap);
        }

        return;
        break;
    case 1:
        dialog_repeat->line_edit_->setText(tr("Workingday"));
        repeat_str_model = tr("Workingday");
        for (int i=0; i<7; i++) {
            if(i<5) {
                repeat_day[i] = 1;
                dialog_repeat->btn[i+2]->iconLabel->setPixmap(repeat_on_Pixmap);
            } else {
                repeat_day[i] = 0;
                dialog_repeat->btn[i+2]->iconLabel->setPixmap(repeat_off_Pixmap);
            }
        }
        dialog_repeat->btn[7]->iconLabel->setPixmap(repeat_off_Pixmap);
        dialog_repeat->btn[8]->iconLabel->setPixmap(repeat_off_Pixmap);
        return;
        break;
    case 2:
        if (repeat_day[0] == 0 ) {
            repeat_day[0] = 1;
            dialog_repeat->btn[2]->iconLabel->setPixmap(repeat_on_Pixmap);
        } else {
            if(repeat_day[1]== 0 && repeat_day[2]== 0 && repeat_day[3]== 0 && repeat_day[4]== 0 && repeat_day[5]== 0 && repeat_day[6]== 0){
                 //防止全部勾选被取消
            }else{
            repeat_day[0] = 0;
            dialog_repeat->btn[2]->iconLabel->setPixmap(repeat_off_Pixmap);
            }
        }
        dialog_repeat->showPopup();
        break;
    case 3:
        if(repeat_day[1] == 0 ) {
            repeat_day[1] = 1;
            dialog_repeat->btn[3]->iconLabel->setPixmap(repeat_on_Pixmap);
        } else {
            if(repeat_day[0]== 0 && repeat_day[2]== 0 && repeat_day[3]== 0 && repeat_day[4]== 0 && repeat_day[5]== 0 && repeat_day[6]== 0){

            }else{
            repeat_day[1] = 0;
            dialog_repeat->btn[3]->iconLabel->setPixmap(repeat_off_Pixmap);
            }
        }
        dialog_repeat->showPopup();
        break;
    case 4:
        if (repeat_day[2] == 0 ) {
            repeat_day[2] = 1;
            dialog_repeat->btn[4]->iconLabel->setPixmap(repeat_on_Pixmap);
        } else {
            if(repeat_day[1]== 0 && repeat_day[0]== 0 && repeat_day[3]== 0 && repeat_day[4]== 0 && repeat_day[5]== 0 && repeat_day[6]== 0){

            }else{
            repeat_day[2] = 0;
            dialog_repeat->btn[4]->iconLabel->setPixmap(repeat_off_Pixmap);
            }
        }
        dialog_repeat->showPopup();
        break;
    case 5:
        if (repeat_day[3] == 0 ) {
            repeat_day[3] = 1;
            dialog_repeat->btn[5]->iconLabel->setPixmap(repeat_on_Pixmap);
        } else {
            if(repeat_day[1]== 0 && repeat_day[2]== 0 && repeat_day[0]== 0 && repeat_day[4]== 0 && repeat_day[5]== 0 && repeat_day[6]== 0){

            }else{
            repeat_day[3] = 0;
            dialog_repeat->btn[5]->iconLabel->setPixmap(repeat_off_Pixmap);
            }
        }
        dialog_repeat->showPopup();
        break;
    case 6:
        if (repeat_day[4] == 0 ) {
            repeat_day[4] = 1;
            dialog_repeat->btn[6]->iconLabel->setPixmap(repeat_on_Pixmap);
        } else {
            if(repeat_day[1]== 0 && repeat_day[2]== 0 && repeat_day[3]== 0 && repeat_day[0]== 0 && repeat_day[5]== 0 && repeat_day[6]== 0){

            }else{
            repeat_day[4] = 0;
            dialog_repeat->btn[6]->iconLabel->setPixmap(repeat_off_Pixmap);
            }
        }
        dialog_repeat->showPopup();
        break;
    case 7:
        if (repeat_day[5] == 0 ) {
            repeat_day[5] = 1;
            dialog_repeat->btn[7]->iconLabel->setPixmap(repeat_on_Pixmap);
        } else {
            if(repeat_day[1]== 0 && repeat_day[2]== 0 && repeat_day[3]== 0 && repeat_day[4]== 0 && repeat_day[0]== 0 && repeat_day[6]== 0){

            }else{
            repeat_day[5] = 0;
            dialog_repeat->btn[7]->iconLabel->setPixmap(repeat_off_Pixmap);
            }
        }
        dialog_repeat->showPopup();
        break;
    case 8:
        if (repeat_day[6] == 0 ) {
            repeat_day[6] = 1;
            dialog_repeat->btn[8]->iconLabel->setPixmap(repeat_on_Pixmap);
        } else {
            if(repeat_day[1]== 0 && repeat_day[2]== 0 && repeat_day[3]== 0 && repeat_day[4]== 0 && repeat_day[5]== 0 && repeat_day[0]== 0){

            }else{
            repeat_day[6] = 0;
            dialog_repeat->btn[8]->iconLabel->setPixmap(repeat_off_Pixmap);
            }
        }
        dialog_repeat->showPopup();
        break;
    default:
        break;
    }
    //构造重复repeat_str
    for (int i=0; i<7; i++) {
        if (repeat_day[i]) {
            repeat_str=repeat_str+day[i];
        }
    }
    if(repeat_day[0]&&repeat_day[1]&&repeat_day[2]&&repeat_day[3]&&repeat_day[4]&&repeat_day[5]&&repeat_day[6])
        repeat_str = tr("Every day");
    dialog_repeat->line_edit_->setText(repeat_str);
    repeat_str_model = repeat_str;
    repeat_str="";
    updateRepeatLineEditStr(dialog_repeat->line_edit_);
}

/*
 * 闹钟初始化音乐选择界面回调
 * Alarm clock initialization music selection interface callback
 */
void Clock::selectAlarmMusic()
{
    refreshMusicSelectList(dialog_music);
}

void Clock::refreshMusicSelectList(QComboBox *temp)
{
    QList<QString> * bellList = m_selectBtnUtil->getAllBellItem();
    int newSize = bellList->size();
    int currentSize = temp->count();
    if(currentSize<newSize){
//        qWarning()<<"zds-添加后选项数目不一致";
    }
    for (int i=0;i<bellList->size();i++) {
        temp->addItem(bellList->at(i));
    }
}



/*
 * 闹钟初始化单击选择音乐
 * Alarm initialization Click to select music
 */
void Clock::musicListclickslot()
{
    int num=dialog_music->currentIndex();
    int size = dialog_music->count();
    //最后一个自定义铃声
    if(num==(size-1)){
        addDivBell(dialog_music,Clock::add_clock);
    }else{
        QString id = m_selectBtnUtil->getBellIdByIndex(num);
        QString path = m_selectBtnUtil->getBellPathById(id);
        QString name = m_selectBtnUtil->getBellNameById(id);
        dialog_music->setCurrentText(name);
        //排除无
        if(num==0){
            path="";
        }
        playMusicFromPath(path);
    }
}

void Clock::remindLateListClickSlot(int num)
{
    remind_late_str_model =getRemindLateStrFromNum(num);
//    remindSelectOnClockNew->textLabel->setText(remind_late_str_model);
}

QString Clock::getRemindLateStrFromNum(int num)
{
    QString temp=tr("none");
    switch (num)
    {
    case 0:
        temp=tr("none");
        break;
    case 1:
        temp=tr("five mins late");
        break;
    case 2:
        temp=tr("ten mins late");
        break;
    case 3:
        temp=tr("twenty mins late");
        break;
    case 4:
        temp=tr("thirsty mins late");
        break;
    case 5:
        temp=tr("one hour late");
        break;
    default:
        temp=tr("none");
        break;
    }
    return temp;
}



/*
 * Default setting database data initialization
 * 默认设置数据库数据初始化
 */
void Clock::modelSetupSet()
{
    int setup_rowNum;
    setup_rowNum = model_setup->rowCount();
    if (setup_rowNum < 1) {
        model_setup->insertRow(setup_rowNum);
        model_setup->setData(model_setup->index(setup_rowNum, 0), int(0));//静音    Mute
        QString id = m_selectBtnUtil->getDefaultBellId();
        model_setup->setData(model_setup->index(setup_rowNum, 1), id);
    }
    model_setup->submitAll();
}



void Clock::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event);
    QPainter p(this);
    p.setRenderHint(QPainter::Antialiasing);  // 反锯齿;
    QPainterPath rectPath;
    rectPath.addRoundedRect(this->rect(), 0, 0); // 左上右下

    QPainter painter(this);
    QStyleOption opt;
    opt.init(this);
    painter.setBrush(opt.palette.color(QPalette::Base));

    QColor mainColor;
    mainColor = palette().color(QPalette::Base);
    p.fillPath(rectPath,QBrush(mainColor));
    if(theme::themetype == 0 || theme::themetype == 2){
        widgetListWhiteStyle(alarmListWidget);
        widgetListWhiteStyle(timeListWidget);
    }else{
        widgetListBlackStyle(alarmListWidget);
        widgetListBlackStyle(timeListWidget);
    }
}



bool Clock::eventFilter(QObject *watched, QEvent *event)
{
    if(watched == editAlarmPage && event->type() == QEvent::Paint)
    {
        showPaint(); //响应函数
    }

    if(watched == shadow && event->type() == QEvent::Paint)
    {
//        showPaint7();
    }
    int index = mainWidget->currentIndex();
    if(watched == switchClock && event->type() == QEvent::HoverEnter){
        if(index==0||index==2){
            QColor backgroundColor = palette().color(QPalette::Button);
            switchClock->setBackgroundColor(backgroundColor);
        }
    }
    if(watched == switchCountdown && event->type() == QEvent::HoverEnter){
        if(index!=0){
            QColor backgroundColor = palette().color(QPalette::Button);
            switchCountdown->setBackgroundColor(backgroundColor);
        }
    }
    if(watched == switchStopwatch && event->type() == QEvent::HoverEnter){
        if(index!=2){
            QColor backgroundColor = palette().color(QPalette::Button);
            switchStopwatch->setBackgroundColor(backgroundColor);
        }
    }
    return QWidget::eventFilter(watched,event);
}

/*
 * 实现响应函数设置页
*/
void Clock::showPaint()
{
    bool onTablet = GsettingSubject::getInstance()->getOnTablet();
    if(onTablet){
        QPainter p(editAlarmPage);
        p.setRenderHint(QPainter::Antialiasing);
        QPainterPath rectPath;
        if(theme::themetype == 0 || theme::themetype == 1)
            rectPath.addRoundedRect(editAlarmPage->rect().adjusted(6, 6, -6, -6), WINDOWN_RADIUS, WINDOWN_RADIUS);
        else
            rectPath.addRoundedRect(editAlarmPage->rect().adjusted(0, 0, 0, 0), 0, 0);
        // 画一个黑底
        QPixmap pixmap(editAlarmPage->rect().size());
        pixmap.fill(Qt::transparent);
        QPainter pixmapPainter(&pixmap);
        pixmapPainter.setRenderHint(QPainter::Antialiasing);
        auto shadowColor = palette().text().color();
        shadowColor.setAlphaF(SHADOWCOLOR_ALPHAF);
        pixmapPainter.setBrush(shadowColor);
        pixmapPainter.setPen(Qt::transparent);
        pixmapPainter.drawPath(rectPath);
        pixmapPainter.end();
        // 模糊这个黑底
        QImage img = pixmap.toImage();
        qt_blurImage(img, VAGUE_RADIUS, false, false);
        // 挖掉中心
        pixmap = QPixmap::fromImage(img);
        QPainter pixmapPainter2(&pixmap);
        pixmapPainter2.setRenderHint(QPainter::Antialiasing);
        pixmapPainter2.setCompositionMode(QPainter::CompositionMode_Clear);
        pixmapPainter2.setPen(Qt::transparent);
        pixmapPainter2.setBrush(Qt::transparent);
        pixmapPainter2.drawPath(rectPath);
        // 绘制阴影
        p.drawPixmap(editAlarmPage->rect(), pixmap, pixmap.rect());
        QStyleOption opt;
        opt.init(editAlarmPage);
        // 绘制一个背景
        p.save();
        //描边
        QColor borderColor = palette().text().color();
        borderColor.setAlphaF(BORDERCOLOR_ALPHAF);
        p.setPen(borderColor);
        p.translate(BORDER_RANGE, BORDER_RANGE);
        p.setBrush(palette().color(QPalette::Base));
        p.drawPath(rectPath);
        p.restore();
    }else{
        QPainter p(editAlarmPage);
        p.setRenderHint(QPainter::Antialiasing);  // 反锯齿;
        QPainterPath rectPath;
        rectPath.addRect(editAlarmPage->rect());
        p.fillPath(rectPath,palette().color(QPalette::Base));
        p.setBrush(palette().color(QPalette::Base));
        p.setPen(Qt::transparent);
        p.drawPath(rectPath);
    }
}



/*
 * 实现响应函数设置页
*/
void Clock::showPaint7()
{
    QPainter painter(shadow);
    painter.setPen(Qt::gray);
    painter.setBrush(Qt::green);
    QStyleOption opt;
    opt.init(this);
    painter.setBrush(opt.palette.color(QPalette::Base));


    painter.setBrush(QColor(theme::timeScrollBackColor));

    painter.setPen(Qt::transparent);
    QRect rect = shadow->rect();
    rect.setWidth(rect.width() - 0);
    rect.setHeight(rect.height() - 0);
    if(theme::themetype == 0 || theme::themetype == 1){
        painter.drawRoundedRect(rect, 7, 7);
        {
            QPainterPath painterPath;
            painterPath.addRoundedRect(rect, 8, 8);
            painter.drawPath(painterPath);
        }
    }else{
        painter.drawRoundedRect(rect, 0, 0);
        {
            QPainterPath painterPath;
            painterPath.addRoundedRect(rect, 0, 0);
            painter.drawPath(painterPath);
        }
    }
}



void Clock::updateTinyBtn()
{
    QPixmap pixmap = QPixmap(":image/switchIconB.png");
    tinyWindowBtn->setProperty("useButtonPalette", true);
    tinyWindowBtn->setIcon(pixmap);
    tinyWindowBtn->setIconSize(QSize(24,24));
    tinyWindowBtn->setToolTip(tr("mini window"));
//    ui->tinyWindowBtn->setFlat(true);
}
void Clock::updateSwitchBtnStyle()
{
    int index=mainWidget->currentIndex();
    if(index==1){
        AlarmPageSwitch();
    }else if(index==0){
        CountdownPageSwitch ();
    }else if(index==2){
        StopwatchPageSwitch ();
    }
}
//黑色主题
void  Clock::blackStyle()
{
    // welcome 环境下，窗口底层一直处于未激活状态，修改完主题设置后重新激活窗口，保证显示正常
    kdk::WindowManager::activateWindow(m_pid);
    timeShowBig->setStyleSheet("color: rgba(255, 255, 255, 0.9);font-size:38px;");
//    QString selfFont = Utils::loadFontFamilyFromTTF();
//    QFont f(selfFont);
    QFont f;
    f.setFamily("NotoSansCJKsc-Regular");
    f.setWeight(400);
    f.setPixelSize(38);
    timeShowBig->setFont(f);
    remainTime->setStyleSheet("color: rgba(255, 255, 255, 0.9)");
    noAlarmIcon->setPixmap(QPixmap(":/image/noClockBlack.png"));
    noAlarm->setStyleSheet("color: rgba(255, 255, 255, 0.6);font-size:16px;");

    widgetListBlackStyle(alarmListWidget);
    widgetListBlackStyle(timeListWidget);
    QString itemRadius = QString::number(ITEM_RADIUS);
    tinyWindowBtn->setIcon(QIcon(":image/switchIconW.png"));
    QPixmap pixmap = QPixmap(":/image/miniIcon/mute-off-dark.png");
    if(m_muteOn){
        pixmap = QPixmap(":/image/miniIcon/mute-on.png");
    }
    muteBtn->setIcon(pixmap);
    updateSwitchBtnStyle();
    repeat_on_Pixmap=theme::changeIconColor(repeat_on_Pixmap,palette().highlightedText().color());
}
//白色主题
void  Clock::whiteStyle()
{
    // welcome 环境下，窗口底层一直处于未激活状态，修改完主题设置后重新激活窗口，保证显示正常
    kdk::WindowManager::activateWindow(m_pid);
    timeShowBig->setStyleSheet("color: rgba(49, 66, 89, 1);font-size:38px;");
//    QString selfFont = Utils::loadFontFamilyFromTTF();
//    QFont f(selfFont);
    QFont f;
    f.setFamily("NotoSansCJKsc-Regular");
    f.setWeight(400);
    f.setPixelSize(38);
    timeShowBig->setFont(f);
    remainTime->setStyleSheet("color: rgba(49, 66, 89, 1)");
    noAlarmIcon->setPixmap(QPixmap(":/image/noClockWhite.png"));
    noAlarm->setStyleSheet("color: rgba(49, 66, 89, 0.6);font-size:16px;");
    widgetListWhiteStyle(alarmListWidget);
    widgetListWhiteStyle(timeListWidget);
    QString itemRadius = QString::number(ITEM_RADIUS);
    tinyWindowBtn->setIcon(QIcon(":image/switchIconB.png"));
    QPixmap pixmap = QPixmap(":/image/miniIcon/mute-off.png");
    if(m_muteOn){
        pixmap = QPixmap(":/image/miniIcon/mute-on.png");
    }
    muteBtn->setIcon(pixmap);
    updateSwitchBtnStyle();
    repeat_on_Pixmap = QPixmap(":/image/object-select-symbolic.png");
}

QString Clock::getDefaultGreyColor()
{
    QColor color = QColor(COUNTDOWN_RING_BACKCOLOR_WHITE_STYLE);
    QString str = theme::getColorStr(color);
    return str;
}





