/*
 * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., Ltd.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU  Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1, 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 <http://www.gnu.org/licenses/&gt;.
 *
 */
#include "lunarcalendarwidget.h"
#include "calendarcolor.h"
#include "../../panel/common/common.h"
#include <QtDBus/QDBusInterface>
#include <QtDBus/QDBusReply>
#include <unistd.h>
#include<QDebug>
#include <QJsonParseError>
#include <QJsonObject>
#include <QProcess>
#include <QGesture>
#include <KWindowEffects>
#include <KWindowSystem>
#include <ukuistylehelper/ukuistylehelper.h>
#define PANEL_CONTROL_IN_CALENDAR "org.ukui.control-center.panel.plugins"
#define LUNAR_KEY                 "calendar"
#define FIRST_DAY_KEY "firstday"

#define TRANSPARENCY_SETTING "org.ukui.control-center.personalise"
#define TRANSPARENCY_KEY "transparency"

#define ORG_UKUI_STYLE            "org.ukui.style"
#define SYSTEM_FONT_SIZE "systemFontSize"
#define SYSTEM_FONT      "systemFont"
#define STYLE_NAME                "styleName"
#define STYLE_NAME_KEY_DARK       "ukui-dark"
#define STYLE_NAME_KEY_DEFAULT    "ukui-default"
#define STYLE_NAME_KEY_BLACK       "ukui-black"
#define STYLE_NAME_KEY_LIGHT       "ukui-light"
#define STYLE_NAME_KEY_WHITE       "ukui-white"
#define ICON_COLOR_LOGHT      255
#define ICON_COLOR_DRAK       0

#define KYSDK_DATESERVER "com.kylin.kysdk.DateServer"
#define KYSDK_DATEPATH "/com/kylin/kysdk/Date"
#define KYSDK_DATEINTERFACE "com.kylin.kysdk.DateInterface"

QDate LunarCalendarWidget::s_clickDate = QDate();
LunarCalendarWidget::LunarCalendarWidget(QWidget *parent) : QWidget(parent)
{
    setObjectName("LunarCalendarWidget");
    installEventFilter(this);
    setMouseTracking(true);
    analysisWorktimeJs();

    btnYear = new QPushButton;
    btnMonth = new QPushButton;
    btnToday = new QPushButton;
    btnClick = false;

    calendarStyle = CalendarStyle_Red;
    date = QDate::currentDate();

    widgetTime = new QWidget;
    timeShow = new QVBoxLayout(widgetTime);

    datelabel =new QLabel(this);
    timelabel = new QLabel(this);
    lunarlabel = new QLabel(this);

    widgetTime->setObjectName("widgetTime");
    timeShow->setContentsMargins(16, 16, 16, 0);

    const QByteArray calendar_id(PANEL_CONTROL_IN_CALENDAR);
    if(QGSettings::isSchemaInstalled(calendar_id)){
        calendar_gsettings = new QGSettings(calendar_id);
    }
    initWidget();

    if(calendar_gsettings!=nullptr){
        //农历切换监听与日期显示格式
        connect(calendar_gsettings, &QGSettings::changed, this, [=] (const QString &key){
            if(key == LUNAR_KEY){
                m_showLunar = getShowLunar();
                setShowLunar(m_showLunar);
                controlDownLine();
                _timeUpdate();
             }
            else if(key == "date") {
                if(calendar_gsettings->get("date").toString() == "cn"){
                    dateShowMode = "yyyy/MM/dd  dddd";
                } else {
                    dateShowMode = "yyyy-MM-dd  dddd";
                }
            } else if (key == FIRST_DAY_KEY) {
                setWeekNameFormat(calendar_gsettings->get(FIRST_DAY_KEY).toString() == "sunday");
            }
        });
        if(calendar_gsettings->get("date").toString() == "cn"){
            dateShowMode = "yyyy/MM/dd  dddd";
        } else {
            dateShowMode = "yyyy-MM-dd  dddd";
        }
        m_showLunar = getShowLunar();
        setShowLunar(m_showLunar);
        setWeekNameFormat(calendar_gsettings->get(FIRST_DAY_KEY).toString() == "sunday");
        //监听12/24小时制
        connect(calendar_gsettings, &QGSettings::changed, this, [=] (const QString &keys){
                timemodel = calendar_gsettings->get("hoursystem").toString();
                _timeUpdate();
        });
        timemodel = calendar_gsettings->get("hoursystem").toString();

    } else {
        //无设置默认公历
        lunarstate = true;
    }
    //判断图形字体是否存在,不存在则加入
    QFontDatabase fontDb;
    if (!fontDb.families().contains("FontAwesome")) {
        int fontId = fontDb.addApplicationFont(":/image/fontawesome-webfont.ttf");
        QStringList fontName = fontDb.applicationFontFamilies(fontId);
        if (fontName.count() == 0) {
            qDebug() << "load fontawesome-webfont.ttf error";
        }
    }

    if (fontDb.families().contains("FontAwesome")) {
        iconFont = QFont("FontAwesome");
#if (QT_VERSION >= QT_VERSION_CHECK(4,8,0))
        iconFont.setHintingPreference(QFont::PreferNoHinting);
#endif
    }
    //切换主题
    const QByteArray style_id(ORG_UKUI_STYLE);
    QStringList stylelist;
    stylelist<<STYLE_NAME_KEY_DARK<<STYLE_NAME_KEY_BLACK;
    if(QGSettings::isSchemaInstalled(style_id)) {
        style_settings = new QGSettings(style_id);
        dark_style=stylelist.contains(style_settings->get(STYLE_NAME).toString());
        setColor(dark_style);
        m_fontName = style_settings->get(SYSTEM_FONT).toString();
        qDebug() << m_fontName;
        m_font.setFamily(m_fontName);
    }
    cboxYearandMonthLabel->setFont(m_font);
    connect(style_settings, &QGSettings::changed, this, [=] (const QString &key){
        if(key==STYLE_NAME){
            dark_style=stylelist.contains(style_settings->get(STYLE_NAME).toString());
            _timeUpdate();
            setColor(dark_style);
        }else if(key == SYSTEM_FONT){
            m_fontName = style_settings->get(SYSTEM_FONT).toString();
            qDebug() << m_fontName;
            m_font.setFamily(m_fontName);
        }else{
            qDebug()<<"key!=STYLE_NAME";
        }
    });



    timer = new QTimer();
    connect(timer,SIGNAL(timeout()),this,SLOT(timerUpdate()));
    timer->start(1000);

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

    setLocaleCalendar();//设置某区域下日历的显示
    initTransparency();
    setWindowOpacity(1);
    setAttribute(Qt::WA_TranslucentBackground,true);//设置窗口背景透明
    setProperty("useSystemStyleBlur", true);   //设置毛玻璃效果
    setProperty("useStyleWindowManager",false);

    KWindowEffects::enableBlurBehind(winId(),true);
    KWindowSystem::setState(winId(),NET::SkipPager|NET::SkipTaskbar|NET::SkipSwitcher);
    kdk::UkuiStyleHelper::self()->removeHeader(this);

    _timeUpdate();
}



void LunarCalendarWidget::getFontInfo(QString &fontName, int &fontSize)
{
    qDebug() << __FILE__ <<__FUNCTION__;
    fontName = m_fontName;
    fontSize = m_fontSize;
}
LunarCalendarWidget::~LunarCalendarWidget()
{
}

/*
 * @brief 设置日历的背景及文字颜色
 * 参数：
 * weekColor 周六及周日文字颜色
*/

void LunarCalendarWidget::setColor(bool mdark_style)
{
    const QByteArray calendar_id(PANEL_CONTROL_IN_CALENDAR);
    if(mdark_style){
        weekTextColor = QColor(0, 0, 0);
        weekBgColor = QColor(180, 180, 180);
        if(QGSettings::isSchemaInstalled(calendar_id)){
            m_showLunar = calendar_gsettings->get(LUNAR_KEY).toString() == "lunar";
        }
        bgImage = ":/image/bg_calendar.png";
        selectType = SelectType_Rect;
    }else{
        weekTextColor = QColor(255, 255, 255);
        weekBgColor = QColor(0, 0, 0);
        if(QGSettings::isSchemaInstalled(calendar_id)){
            m_showLunar = calendar_gsettings->get(LUNAR_KEY).toString() == "lunar";
        }
        bgImage = ":/image/bg_calendar.png";
        selectType = SelectType_Rect;
    }
    initStyle();
}

void LunarCalendarWidget::controlDownLine()
{
    QString lang;
    QString locale;
    getLocale(lang, locale);
    if((!lang.contains("zh",Qt::CaseInsensitive)) ||
       (!locale.contains("zh",Qt::CaseInsensitive))) {
        if(lineDown!=nullptr) {
            lineDown->hide();
        }
    }
    if(calendar_gsettings->get("calendar").toString() == "solarlunar") {
        if(lineDown!=nullptr) {
            lineDown->hide();
        }
    }
}

void LunarCalendarWidget::_timeUpdate() {
    QDateTime time = QDateTime::currentDateTime();
    QLocale locale = (QLocale::system().name() == "zh_CN" ? (QLocale::Chinese) : (QLocale::English));
    QString _time;
    if(timemodel == "12") {
        if(locale.language() == QLocale::English){
            _time = time.toString("hh:mm:ss A");
            //_time = locale.toString(time,"hh:mm:ss A");
        } else {
            _time = time.toString("A hh:mm:ss");
            //_time = locale.toString(time,"A hh:mm:ss");
        }
    } else {
        //_time = locale.toString(time,"hh:mm:ss");
        _time = time.toString("hh:mm:ss");
    }

    QFont font(m_fontName);
    datelabel->setText(_time);
    font.setPointSize(22);
    datelabel->setFont(font);
    QString strHoliday;
    QString strSolarTerms;
    QString strLunarFestival;
    QString strLunarYear;
    QString strLunarMonth;
    QString strLunarDay;

    LunarCalendarInfo::Instance()->getLunarCalendarInfo(locale.toString(time,"yyyy").toInt(),
                                                        locale.toString(time,"MM").toInt(),
                                                        locale.toString(time,"dd").toInt(),
                                                        strHoliday,
                                                        strSolarTerms,
                                                        strLunarFestival,
                                                        strLunarYear,
                                                        strLunarMonth,
                                                        strLunarDay);

    //QString _date = locale.toString(time,dateShowMode);
    QString _date = time.toString(dateShowMode);
    if (lunarstate) {
        _date = _date + " "+strLunarMonth + strLunarDay;
    }
    timelabel->setText(_date);
    font.setPointSize(12);
    timelabel->setFont(font);
    QFont font1(m_font);
    font1.setPixelSize(22);
    QFont font2(m_font);
    font2.setPixelSize(12);
    QFontMetrics fm(font1);
    QFontMetrics fm2(font2);
    int h = fm.boundingRect(datelabel->text()).height();
    int h2=fm2.boundingRect(timelabel->text()).height();
    datelabel->setAlignment(Qt::AlignCenter);
    timelabel->setAlignment(Qt::AlignCenter);
    datelabel->setFixedHeight(h+5);
    timelabel->setFixedHeight(h2+5);
    datelabel->setContentsMargins(0,0,0,0);
    timelabel->setContentsMargins(0,0,0,0);

}

void LunarCalendarWidget::timerUpdate()
{
    _timeUpdate();
}

void LunarCalendarWidget::initWidget()
{
    setObjectName("lunarCalendarWidget");

    //顶部widget
    m_widgetTop = new QWidget;
    m_widgetTop->setObjectName("widgetTop");
    m_widgetTop->setMinimumHeight(35);

    //上个月的按钮
    btnPrevYear = new kdk::KBorderlessButton;
    btnPrevYear->setObjectName("btnPrevYear");
    btnPrevYear->setFixedWidth(36);
    btnPrevYear->setFixedHeight(36);
    btnPrevYear->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Expanding);
    //btnPrevYear->setProperty("useIconHighlightEffect", 0x2);
    btnPrevYear->setIcon(QIcon::fromTheme("ukui-start-symbolic"));


    //下个月按钮
    btnNextYear = new kdk::KBorderlessButton;
    btnNextYear->setObjectName("btnNextYear");
    btnNextYear->setFixedWidth(36);
    btnNextYear->setFixedHeight(36);
    //btnNextYear->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Expanding);
    btnNextYear->setProperty("useIconHighlightEffect", 0x2);
    btnNextYear->setIcon(QIcon::fromTheme("ukui-end-symbolic"));

    m_font.setFamily(m_fontName);
    m_font.setPointSize(12);
    QFont smallfont = m_font;
    if(QLocale::system().name() != "zh_CN"){
        smallfont.setPointSize(8);
    }
    //转到年显示
    btnYear->setObjectName("btnYear");
    btnYear->setFocusPolicy(Qt::NoFocus);
    btnYear->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Expanding);
    btnYear->setFont(smallfont);
    btnYear->setText(tr("Year"));
    btnYear->setToolTip(tr("Year"));
    btnYear->setFixedSize(64,36);

    //btnYear->setStyle(new CustomStyle_pushbutton("ukui-default"));
    connect(btnYear,&QPushButton::clicked,this,&LunarCalendarWidget::yearWidgetChange);

    //转到月显示
    btnMonth->setObjectName("btnMonth");
    btnMonth->setFocusPolicy(Qt::NoFocus);
    btnMonth->setFont(smallfont);
    btnMonth->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Expanding);
    btnMonth->setText(tr("Month"));
    btnMonth->setToolTip(tr("Month"));
    btnMonth->setFixedSize(64,36);
    //btnMonth->setStyle(new CustomStyle_pushbutton("ukui-default"));
    connect(btnMonth,&QPushButton::clicked,this,&LunarCalendarWidget::monthWidgetChange);

    //转到今天
    btnToday->setObjectName("btnToday");
    btnToday->setFocusPolicy(Qt::NoFocus);
    btnToday->setFont(smallfont);
    //btnToday->setFixedWidth(40);
    //btnToday->setStyle(new CustomStyle_pushbutton("ukui-default"));
    btnToday->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Expanding);
    btnToday->setText(tr("Today"));
    btnToday->setToolTip(tr("Today"));
    btnToday->setFixedSize(64,36);

    btnYear->setProperty("needTranslucent",true);
    btnMonth->setProperty("needTranslucent",true);
    btnToday->setProperty("needTranslucent",true);
    btnYear->setProperty("useButtonPalette", true);
    btnMonth->setProperty("useButtonPalette", true);
    btnToday->setProperty("useButtonPalette", true);
    //年份与月份下拉框 暂不用此
    cboxYearandMonth = new QComboBox;
    cboxYearandMonthLabel = new QLabel();
    cboxYearandMonthLabel->setFixedWidth(80);
    cboxYearandMonthLabel->setFont(m_font);

    //顶部横向布局
    QHBoxLayout *layoutTop = new QHBoxLayout(m_widgetTop);
    layoutTop->setContentsMargins(0, 0, 0, 9);
    layoutTop->addSpacing(8);
    layoutTop->addWidget(btnPrevYear);
    layoutTop->addWidget(cboxYearandMonthLabel);
    layoutTop->addWidget(btnNextYear);
    layoutTop->addStretch();
    layoutTop->addWidget(btnYear);
    layoutTop->addWidget(btnMonth);
    layoutTop->addWidget(btnToday);
    layoutTop->addSpacing(8);

    //时间
    widgetTime->setMinimumHeight(50);
    timeShow->setSpacing(4);
    timeShow->addStretch();
    timeShow->addWidget(datelabel);//, Qt::AlignHCenter);
//    timeShow->addSpacing(4);
    timeShow->addWidget(timelabel);//,Qt::AlignHCenter);
    timeShow->addStretch();
//    datelabel->setStyleSheet("background-color:red");
//    timelabel->setStyleSheet("background-color:green");
    //星期widget
    widgetWeek = new QWidget;
    widgetWeek->setObjectName("widgetWeek");
    widgetWeek->setMinimumHeight(30);
    widgetWeek->installEventFilter(this);

    //星期布局
    QHBoxLayout *layoutWeek = new QHBoxLayout(widgetWeek);
    layoutWeek->setMargin(0);
    layoutWeek->setSpacing(0);

    for (int i = 0; i < 7; i++) {
        QLabel *lab = new QLabel;
        lab->setObjectName(QString("WeekLabel_%1").arg(i));
        QFont font(m_font);
        font.setPixelSize(14);
        lab->setFont(font);
        lab->setAlignment(Qt::AlignCenter);
        layoutWeek->addWidget(lab);
        labWeeks.append(lab);
    }

    //日期标签widget
    m_widgetDayBody = new QWidget;
    m_widgetDayBody->setObjectName("widgetDayBody");
    m_widgetDayBody->setAttribute(Qt::WA_TransparentForMouseEvents,true);
    //日期标签布局
    QGridLayout *layoutBodyDay = new QGridLayout(m_widgetDayBody);
    layoutBodyDay->setMargin(1);
    layoutBodyDay->setHorizontalSpacing(0);
    layoutBodyDay->setVerticalSpacing(0);

    //逐个添加日标签
    for (int i = 0; i < 42; i++) {
        LunarCalendarItem *lab = new LunarCalendarItem(m_fontName);
        lab->setObjectName(QString("DayLabel_%1").arg(i));
        lab->installEventFilter(this);
        lab->worktime = worktime;
        connect(lab, SIGNAL(clicked(QDate, LunarCalendarItem::DayType)), this, SLOT(labClicked(QDate, LunarCalendarItem::DayType)));
        layoutBodyDay->addWidget(lab, i / 7, i % 7);
        dayItems.append(lab);
    }

    //年份标签widget
    widgetYearBody = new QWidget;
    widgetYearBody->setObjectName("widgetYearBody");
    widgetYearBody->setAttribute(Qt::WA_TransparentForMouseEvents,true);
    //年份标签布局
    QGridLayout *layoutBodyYear = new QGridLayout(widgetYearBody);
    layoutBodyYear->setMargin(1);
    layoutBodyYear->setHorizontalSpacing(0);
    layoutBodyYear->setVerticalSpacing(0);

    //逐个添加年标签
    for (int i = 0; i < 12; i++) {
        LunarCalendarYearItem *labYear = new LunarCalendarYearItem(m_fontName);
        labYear->setObjectName(QString("YEARLabel_%1").arg(i));
        labYear->installEventFilter(this);
        connect(labYear, SIGNAL(yearMessage(QDate, LunarCalendarYearItem::DayType)), this, SLOT(updateYearClicked(QDate, LunarCalendarYearItem::DayType)));
        layoutBodyYear->addWidget(labYear, i / 3, i % 3);
        yearItems.append(labYear);
    }
    widgetYearBody->hide();

    //月份标签widget
    widgetmonthBody = new QWidget;
    widgetmonthBody->setObjectName("widgetmonthBody");
    widgetmonthBody->setAttribute(Qt::WA_TransparentForMouseEvents,true);
    //月份标签布局
    QGridLayout *layoutBodyMonth = new QGridLayout(widgetmonthBody);
    layoutBodyMonth->setMargin(1);
    layoutBodyMonth->setHorizontalSpacing(0);
    layoutBodyMonth->setVerticalSpacing(0);

    //逐个添加月标签
    for (int i = 0; i < 12; i++) {
        LunarCalendarMonthItem *labMonth = new LunarCalendarMonthItem(m_fontName);
        labMonth->setObjectName(QString("MONTHLabel_%1").arg(i));
        labMonth->installEventFilter(this);
        connect(labMonth, SIGNAL(monthMessage(QDate, LunarCalendarMonthItem::DayType)), this, SLOT(updateMonthClicked(QDate, LunarCalendarMonthItem::DayType)));
        layoutBodyMonth->addWidget(labMonth, i / 3, i % 3);
        monthItems.append(labMonth);
    }
    widgetmonthBody->hide();

    QFont font(m_fontName);
    font.setPointSize(12);
    labWidget = new QWidget();
    labWidget->installEventFilter(this);
    labBottom = new QLabel();
    labBottom->installEventFilter(this);
    yijichooseLabel = new QLabel();
    yijichooseLabel->setText("宜忌");
    yijichooseLabel->setFont(font);
    yijichooseLabel->installEventFilter(this);

    labBottom->setFont(font);
    labBottom->setAlignment(Qt::AlignLeft|Qt::AlignVCenter);
    yijichoose = new QCheckBox();
    yijichoose->installEventFilter(this);

    labLayout = new QHBoxLayout();
    labLayout->addWidget(labBottom);
    labLayout->addStretch();
    labLayout->addWidget(yijichooseLabel);
    labLayout->addWidget(yijichoose);
    labWidget->setLayout(labLayout);

    yijiLayout = new QVBoxLayout;
    yijiWidget = new QWidget;

    yiLabel = new QLabel();
    jiLabel = new QLabel();
    yiLabel->setFont(font);
    jiLabel->setFont(font);

    yijiLayout->addWidget(yiLabel);
    yijiLayout->addWidget(jiLabel);
    yijiWidget->setLayout(yijiLayout);
    yiLabel->setVisible(false);
    jiLabel->setVisible(false);

    connect(yijichoose,&QRadioButton::clicked,this,&LunarCalendarWidget::customButtonsClicked);
    //默认打开黄历菜单
    yijichoose->setChecked(true);
    yijistate = true;
    Q_EMIT yijichoose->clicked(true);
    //主布局
    lineUp = new PartLineWidget();
    lineDown = new PartLineWidget();

    lineUp->setFixedSize(440, 1);
    lineDown->setFixedSize(440, 1);
    QVBoxLayout *verLayoutCalendar = new QVBoxLayout(this);
    verLayoutCalendar->setMargin(0);
    verLayoutCalendar->setSpacing(0);
    verLayoutCalendar->addWidget(widgetTime);
    verLayoutCalendar->addItem(new QSpacerItem(8,8));
    verLayoutCalendar->addWidget(lineUp);
    verLayoutCalendar->addItem(new QSpacerItem(8,8));
    verLayoutCalendar->addWidget(m_widgetTop);
    verLayoutCalendar->addWidget(widgetWeek);
    verLayoutCalendar->addWidget(m_widgetDayBody, 1);
    verLayoutCalendar->addWidget(widgetYearBody, 1);
    verLayoutCalendar->addWidget(widgetmonthBody, 1);
    verLayoutCalendar->addItem(new QSpacerItem(8,8));
    verLayoutCalendar->addWidget(lineDown);
    controlDownLine();
    verLayoutCalendar->addItem(new QSpacerItem(8,8));
    verLayoutCalendar->addWidget(labWidget);
    verLayoutCalendar->addWidget(yijiWidget);
    widgetWeek->setContentsMargins(16,0,16,0);
    m_widgetDayBody->setContentsMargins(16,0,16,0);
    widgetYearBody->setContentsMargins(16,0,16,0);
    widgetmonthBody->setContentsMargins(16,0,16,0);
    labWidget->setContentsMargins(16,0,16,0);
    yijiWidget->setContentsMargins(16,0,16,16);
    //绑定按钮和下拉框信号
    connect(btnPrevYear, &kdk::KBorderlessButton::clicked, this, [=]() {
        switch (m_currentType) {
        case 0:
            showPreviousMonth(true);
            break;
        case 2:
            changeYear(false);
            break;
        case 1:
        default:
            break;
        }
    });
    connect(btnNextYear, &kdk::KBorderlessButton::clicked, this, [=](){
        switch (m_currentType) {
        case 0:
            showNextMonth(true);
            break;
        case 2:
            changeYear(true);
            break;
        case 1:
        default:
            break;
        }
    });
    connect(btnToday, SIGNAL(clicked(bool)), this, SLOT(showToday()));
//    connect(cboxYearandMonth, SIGNAL(currentIndexChanged(QString)), this, SLOT(yearChanged(QString)));
//    connect(cboxMonth, SIGNAL(currentIndexChanged(QString)), this, SLOT(monthChanged(QString)));
    yijichoose->setProperty("needTranslucent",true);
}

//设置日历的地区
void LunarCalendarWidget::setLocaleCalendar()
{
#if 0
    QStringList res = getLocale();
    qDebug()<<"设置区域:"<<res.at(0);
    int isCN = res.at(0) == "zh_CN.UTF-8" ? 1 : 0;
#else
    QString language;
    QString locale;
    QStringList res = getLocale(language,locale);
    qDebug() << language << locale;
    qDebug()<<"设置区域:"<<res.at(0);
    //int isCN = res.at(0) == "zh_CN.UTF-8" ? 1 : 0;
    bool isCN = language.contains("zh_CN");
#endif
    if (FirstdayisSun){
        labWeeks.at(0)->setText(tr("Sun"));
        labWeeks.at(1)->setText(tr("Mon"));
        labWeeks.at(2)->setText(tr("Tue"));
        labWeeks.at(3)->setText(tr("Wed"));
        labWeeks.at(4)->setText(tr("Thur"));
        labWeeks.at(5)->setText(tr("Fri"));
        labWeeks.at(6)->setText(tr("Sat"));
    }else {
        labWeeks.at(0)->setText(tr("Mon"));
        labWeeks.at(1)->setText(tr("Tue"));
        labWeeks.at(2)->setText(tr("Wed"));
        labWeeks.at(3)->setText(tr("Thur"));
        labWeeks.at(4)->setText(tr("Fri"));
        labWeeks.at(5)->setText(tr("Sat"));
        labWeeks.at(6)->setText(tr("Sun"));
    }
}

//获取指定地区的编号代码
QStringList LunarCalendarWidget::getLocale(QString &language, QString &locale)
{
    //判断区域(美国/中国)
    QString objpath;
    unsigned int uid = getuid();
    objpath = objpath +"/org/freedesktop/Accounts/User"+QString::number(uid);
    QString formats;
    QString lang;
    QStringList result;

    QDBusInterface localeInterface("org.freedesktop.Accounts",
                             objpath,
                             "org.freedesktop.DBus.Properties",
                             QDBusConnection::systemBus(),this);
    QDBusReply<QMap<QString, QVariant>> reply = localeInterface.call("GetAll","org.freedesktop.Accounts.User");
    if (reply.isValid()){
        QMap<QString, QVariant> propertyMap;
        propertyMap = reply.value();
        if (propertyMap.keys().contains("FormatsLocale")) {
            formats = propertyMap.find("FormatsLocale").value().toString();
            locale = formats;
        }
        if(lang.isEmpty() && propertyMap.keys().contains("Language")) {
            lang = propertyMap.find("Language").value().toString();
            language = lang;
        }
    } else {
        qDebug() << "reply failed";
    }
    result.append(formats);
    result.append(lang);
    return result;

}

void LunarCalendarWidget::initStyle()
{
    //设置样式
//    QStringList qss;

//    //自定义日控件颜色
//    QString strSelectType;
//    if (selectType == SelectType_Rect) {
//        strSelectType = "SelectType_Rect";
//    } else if (selectType == SelectType_Circle) {
//        strSelectType = "SelectType_Circle";
//    } else if (selectType == SelectType_Triangle) {
//        strSelectType = "SelectType_Triangle";
//    } else if (selectType == SelectType_Image) {
//        strSelectType = "SelectType_Image";
    //}

    //计划去掉qss,保留农历切换的设置
    //qss.append(QString("LunarCalendarItem{qproperty-showLunar:%1;}").arg(m_showLunar));

    // this->setStyleSheet(qss.join(""));
}

void LunarCalendarWidget::analysisWorktimeJs()
{
    /*解析json文件*/
    QFile file("/usr/share/ukui-panel/plugin-calendar/html/jiejiari.json");
    file.open(QIODevice::ReadOnly | QIODevice::Text);
    QString value = file.readAll();
    file.close();

    QJsonParseError parseJsonErr;
    QJsonDocument document = QJsonDocument::fromJson(value.toUtf8(),&parseJsonErr);
    if(!(parseJsonErr.error == QJsonParseError::NoError))
    {
        qDebug()<<tr("解析json文件错误！");
        return;
    }
    QJsonObject jsonObject = document.object();
    QStringList args = jsonObject.keys();

    for (int i=0;i<args.count();i++) {
        if(jsonObject.contains(args.at(i)))
        {
            QJsonValue jsonValueList = jsonObject.value(args.at(i));
            QJsonObject item = jsonValueList.toObject();
            QStringList arg2 = item.keys();
            for (int j=0;j<arg2.count();j++) {
                worktimeinside.insert(arg2.at(j),item[arg2.at(j)].toString());
            }
        }
        worktime.insert(args.at(i),worktimeinside);
        worktimeinside.clear();
    }
}

void LunarCalendarWidget::yearWidgetChange()
{
    if (widgetYearBody->isHidden()){
        widgetYearBody->show();
        widgetWeek->hide();
        m_widgetDayBody->hide();
        widgetmonthBody->hide();
        changeMode(2);
        m_savedYear = date.year();
        qDebug () << m_savedYear;
    }
    else{
        widgetYearBody->hide();
        widgetWeek->show();
        m_widgetDayBody->show();
        widgetmonthBody->hide();
        date.setDate(m_savedYear,date.month(),date.day());
        changeMode(0);
        initDate();
    }

}

void LunarCalendarWidget::monthWidgetChange()
{
    if(widgetmonthBody->isHidden()){
        widgetYearBody->hide();
        widgetWeek->hide();
        m_widgetDayBody->hide();
        widgetmonthBody->show();
        changeMode(1);
    }
    else{
        widgetYearBody->hide();
        widgetWeek->show();
        m_widgetDayBody->show();
        widgetmonthBody->hide();
        changeMode(0);
    }
}
void LunarCalendarWidget::changeMode(int mode)
{
    m_currentType = mode;
    if(mode == 1 || mode == 2) {
        btnNextYear->setEnabled(false);
        btnPrevYear->setEnabled(false);
    } else {
        btnNextYear->setEnabled(true);
        btnPrevYear->setEnabled(true);
    }
}

//初始化日期面板
void LunarCalendarWidget::initDate()
{
    int year = date.year();
    int month = date.month();
    int day = date.day();
    if(oneRun) {
        downLabelHandle(date);
        yijihandle(date);
        oneRun = false;
    }
    //设置为今天,设置变量防止重复触发
    btnClick = true;
    //cboxYearandMonth->setCurrentIndex(cboxYearandMonth->findText(QString("%1.%2").arg(year).arg(month)));
    btnClick = false;

    cboxYearandMonthLabel->setAlignment(Qt::AlignCenter);
    if(m_currentType != 2){
        cboxYearandMonthLabel->setText(QString("%1.%2").arg(year).arg(month));
    } else {
        cboxYearandMonthLabel->setText(QString("%1.%2").arg(m_savedYear).arg(month));
    }

    //首先判断当前月的第一天是星期几
    int week = LunarCalendarInfo::Instance()->getFirstDayOfWeek(year, month, FirstdayisSun);
    //当前月天数
    int countDay = LunarCalendarInfo::Instance()->getMonthDays(year, month);
    //上月天数
    int countDayPre = LunarCalendarInfo::Instance()->getMonthDays(1 == month ? year - 1 : year, 1 == month ? 12 : month - 1);

    //如果上月天数上月刚好一周则另外处理
    int startPre, endPre, startNext, endNext, index, tempYear, tempMonth, tempDay;
    if (0 == week) {
        startPre = 0;
        endPre = 7;
        startNext = 0;
        endNext = 42 - (countDay + 7);
    } else {
        startPre = 0;
        endPre = week;
        startNext = week + countDay;
        endNext = 42;
    }

    //纠正1月份前面部分偏差,1月份前面部分是上一年12月份
    tempYear = year;
    tempMonth = month - 1;
    if (tempMonth < 1) {
        tempYear--;
        tempMonth = 12;
    }

    //显示上月天数
    for (int i = startPre; i < endPre; i++) {
        index = i;
        tempDay = countDayPre - endPre + i + 1;

        QDate date(tempYear, tempMonth, tempDay);
        QString lunar = LunarCalendarInfo::Instance()->getLunarDay(tempYear, tempMonth, tempDay);
        dayItems.at(index)->setDate(date, lunar, LunarCalendarItem::DayType_MonthPre);
        dayItems.at(index)->setFont(m_fontName);
    }

    //纠正12月份后面部分偏差,12月份后面部分是下一年1月份
    tempYear = year;
    tempMonth = month + 1;
    if (tempMonth > 12) {
        tempYear++;
        tempMonth = 1;
    }

    //显示下月天数
    for (int i = startNext; i < endNext; i++) {
        index = 42 - endNext + i;
        tempDay = i - startNext + 1;

        QDate date(tempYear, tempMonth, tempDay);
        QString lunar = LunarCalendarInfo::Instance()->getLunarDay(tempYear, tempMonth, tempDay);
        dayItems.at(index)->setDate(date, lunar, LunarCalendarItem::DayType_MonthNext);
    }

    //重新置为当前年月
    tempYear = year;
    tempMonth = month;
    QFont font(m_fontName);

    //显示当前月
    for (int i = week; i < (countDay + week); i++) {
        index = (0 == week ? (i + 7) : i);
        tempDay = i - week + 1;

        QDate date(tempYear, tempMonth, tempDay);
        QString lunar = LunarCalendarInfo::Instance()->getLunarDay(tempYear, tempMonth, tempDay);
        dayItems.at(index)->setDate(date, lunar, LunarCalendarItem::DayType_MonthCurrent);
    }

    for (int i=0;i<12;i++){
        monthItems.at(i)->setDate(QDate(date.year(),i+1,1));
        yearItems.at(i)->setDate(date.addYears(i));
        yearItems.at(i)->setFont(font);
        monthItems.at(i)->setFont(font);
    }
    auto it = dayItems.begin();
    for(;it!=dayItems.end();it++){
        (*it)->setFont(font);
    }

    auto itw = labWeeks.begin();
    QFont f(m_fontName);
    f.setPixelSize(14);
    for(;itw!=labWeeks.end();itw++){
       (*itw)->setFont(f);
    }

    labBottom->setFont(m_font);
    labBottom->repaint();

    yijichooseLabel->setFont(m_font);
    yijichooseLabel->repaint();

    yiLabel->setFont(m_font);
    jiLabel->setFont(m_font);
    yijiWidget->repaint();
    QFont smallfont = m_font;
    if(QLocale::system().name() != "zh_CN"){
        smallfont.setPointSize(8);
    }
    btnYear->setFont(smallfont);
    btnYear->repaint();
    btnToday->setFont(smallfont);
    btnToday->repaint();
    btnMonth->setFont(smallfont);
    btnMonth->repaint();
    m_widgetTop->repaint();
    cboxYearandMonthLabel->setFont(m_font);
    cboxYearandMonthLabel->repaint();
}

void LunarCalendarWidget::customButtonsClicked(int x)
{
    if (x) {
        yiLabel->setVisible(true);
        jiLabel->setVisible(true);
        yijistate = true;
        Q_EMIT yijiChangeUp();
    } else {
        yiLabel->setVisible(false);
        jiLabel->setVisible(false);
        Q_EMIT yijiChangeDown();
        yijistate = false;
    }
}

QString LunarCalendarWidget::getSettings()
{
    QString arg = "配置文件";
    return  arg;

}

void LunarCalendarWidget::setSettings(QString arg)
{

}

void LunarCalendarWidget::downLabelHandle(const QDate &date)
{

    QString strHoliday;
    QString strSolarTerms;
    QString strLunarFestival;
    QString strLunarYear;
    QString strLunarMonth;
    QString strLunarDay;

    LunarCalendarInfo::Instance()->getLunarCalendarInfo(date.year(),
                                                        date.month(),
                                                        date.day(),
                                                        strHoliday,
                                                        strSolarTerms,
                                                        strLunarFestival,
                                                        strLunarYear,
                                                        strLunarMonth,
                                                        strLunarDay);

    QString labBottomarg = strLunarYear + "  " + strLunarMonth + strLunarDay;
    labBottom->setText(labBottomarg);

}

void LunarCalendarWidget::yijihandle(const QDate &date)
{
    /*解析json文件*/
    QFile file(QString("/usr/share/ukui-panel/plugin-calendar/html/hlnew/hl%1.json").arg(date.year()));
    file.open(QIODevice::ReadOnly | QIODevice::Text);
    QString value = file.readAll();
    file.close();

    QJsonParseError parseJsonErr;
    QJsonDocument document = QJsonDocument::fromJson(value.toUtf8(),&parseJsonErr);
    if(!(parseJsonErr.error == QJsonParseError::NoError))
    {
        qDebug()<<tr("解析json文件错误！");
        yiLabel->setText("宜：");
        jiLabel->setText("忌：");
        return;
    }
    QJsonObject jsonObject = document.object();

    if(jsonObject.contains(QString("d%1").arg(date.toString("MMdd"))))
    {
        QJsonValue jsonValueList = jsonObject.value(QString("d%1").arg(date.toString("MMdd")));
        QJsonObject item = jsonValueList.toObject();
        QString yiString;
        QString jiString;
        if (item["y"].toString() == "." || item["y"].isNull()){
            yiString = "宜：";
        }else {
            yiString = "宜：" + item["y"].toString();
        }
        if (item["j"].toString() == "." || item["j"].isNull()){
            jiString = "忌：";
        }else {
            jiString = "忌：" + item["j"].toString();
        }

        yiLabel->setText(yiString);
        jiLabel->setText(jiString);
    }
}

void LunarCalendarWidget::yearChanged(const QString &arg1)
{
    //如果是单击按钮切换的日期变动则不需要触发
    if (btnClick) {
        return;
    }
    int nIndex = arg1.indexOf(".");
    if(-1 == nIndex){
        return;
    }
    int year = arg1.mid(0,nIndex).toInt();
    int month = arg1.mid(nIndex + 1).toInt();
    int day = date.day();
    dateChanged(year, month, day);
}

void LunarCalendarWidget::monthChanged(const QString &arg1)
{
    //如果是单击按钮切换的日期变动则不需要触发
    if (btnClick) {
        return;
    }

    int year = date.year();
    int month = arg1.mid(0, arg1.length()).toInt();
    int day = date.day();
    dateChanged(year, month, day);
}

void LunarCalendarWidget::labClicked(const QDate &date, const LunarCalendarItem::DayType &dayType)
{
    this->date = date;
    s_clickDate = date;
    qDebug() << s_clickDate;
    if (LunarCalendarItem::DayType_MonthPre == dayType){
        showPreviousMonth(false);
    }
    else if (LunarCalendarItem::DayType_MonthNext == dayType) {
        showNextMonth(false);
    }
    else{
        dayChanged(this->date,s_clickDate);
    }
}

void LunarCalendarWidget::updateYearClicked(const QDate &date, const LunarCalendarYearItem::DayType &dayType)
{
    //通过传来的日期，设置当前年月份
    this->date = date;
    widgetYearBody->hide();
    widgetWeek->show();
    m_widgetDayBody->show();
    widgetmonthBody->hide();
    s_clickDate = date;
    changeDate(date);
    dayChanged(date,QDate());
    changeMode(0);
}

void LunarCalendarWidget::updateMonthClicked(const QDate &date, const LunarCalendarMonthItem::DayType &dayType)
{
    //通过传来的日期，设置当前年月份
    this->date = date;
    widgetYearBody->hide();
    widgetWeek->show();
    m_widgetDayBody->show();
    widgetmonthBody->hide();
//    qDebug()<<date;
    s_clickDate = date;
    changeDate(date);
    dayChanged(date,QDate());
    changeMode(0);
}

void LunarCalendarWidget::changeDate(const QDate &date)
{
    int year = date.year();
    int month = date.month();
    int day = date.day();
    if(oneRun) {
        downLabelHandle(date);
        yijihandle(date);
        oneRun = false;
    }

    //设置为今天,设置变量防止重复触发
    btnClick = true;
    //cboxYearandMonth->setCurrentIndex(cboxYearandMonth->findText(QString("%1.%2").arg(year).arg(month)));
    btnClick = false;

    cboxYearandMonthLabel->setText(QString("%1.%2").arg(year).arg(month));

    //首先判断当前月的第一天是星期几
    int week = LunarCalendarInfo::Instance()->getFirstDayOfWeek(year, month, FirstdayisSun);
    //当前月天数
    int countDay = LunarCalendarInfo::Instance()->getMonthDays(year, month);
    //上月天数
    int countDayPre = LunarCalendarInfo::Instance()->getMonthDays(1 == month ? year - 1 : year, 1 == month ? 12 : month - 1);

    //如果上月天数上月刚好一周则另外处理
    int startPre, endPre, startNext, endNext, index, tempYear, tempMonth, tempDay;
    if (0 == week) {
        startPre = 0;
        endPre = 7;
        startNext = 0;
        endNext = 42 - (countDay + 7);
    } else {
        startPre = 0;
        endPre = week;
        startNext = week + countDay;
        endNext = 42;
    }

    //纠正1月份前面部分偏差,1月份前面部分是上一年12月份
    tempYear = year;
    tempMonth = month - 1;
    if (tempMonth < 1) {
        tempYear--;
        tempMonth = 12;
    }

    //显示上月天数
    for (int i = startPre; i < endPre; i++) {
        index = i;
        tempDay = countDayPre - endPre + i + 1;

        QDate date(tempYear, tempMonth, tempDay);
        QString lunar = LunarCalendarInfo::Instance()->getLunarDay(tempYear, tempMonth, tempDay);
        dayItems.at(index)->setDate(date, lunar, LunarCalendarItem::DayType_MonthPre);
    }

    //纠正12月份后面部分偏差,12月份后面部分是下一年1月份
    tempYear = year;
    tempMonth = month + 1;
    if (tempMonth > 12) {
        tempYear++;
        tempMonth = 1;
    }

    //显示下月天数
    for (int i = startNext; i < endNext; i++) {
        index = 42 - endNext + i;
        tempDay = i - startNext + 1;

        QDate date(tempYear, tempMonth, tempDay);
        QString lunar = LunarCalendarInfo::Instance()->getLunarDay(tempYear, tempMonth, tempDay);
        dayItems.at(index)->setDate(date, lunar, LunarCalendarItem::DayType_MonthNext);
    }

    //重新置为当前年月
    tempYear = year;
    tempMonth = month;

    //显示当前月
    for (int i = week; i < (countDay + week); i++) {
        index = (0 == week ? (i + 7) : i);
        tempDay = i - week + 1;

        QDate date(tempYear, tempMonth, tempDay);
        QString lunar = LunarCalendarInfo::Instance()->getLunarDay(tempYear, tempMonth, tempDay);
        dayItems.at(index)->setDate(date, lunar, LunarCalendarItem::DayType_MonthCurrent);
    }

    for (int i=0;i<12;i++){
        yearItems.at(i)->setDate(s_clickDate.addYears(i));
        monthItems.at(i)->setDate(QDate(s_clickDate.year(),i+1,1));
    }
}

void LunarCalendarWidget::dayChanged(const QDate &date,const QDate &m_date)
{
    //计算星期几,当前天对应标签索引=日期+星期几-1
    int year = date.year();
    int month = date.month();
    int day = date.day();
    int week = LunarCalendarInfo::Instance()->getFirstDayOfWeek(year, month, FirstdayisSun);
    //选中当前日期,其他日期恢复,这里还有优化空间,比方说类似单选框机制
    for (int i = 0; i < 42; i++) {
        //当月第一天是星期天要另外计算
        int index = day + week - 1;
        if (week == 0) {
            index = day + 6;
        }
         dayItems.at(i)->setSelect(false);
        if(dayItems.at(i)->getDate() == m_date) {
           dayItems.at(i)->setSelect(i == index);
        }
        if (i == index) {
            downLabelHandle(dayItems.at(i)->getDate());
            yijihandle(dayItems.at(i)->getDate());
        }

    }

    //发送日期单击信号
    Q_EMIT clicked(date);
    //发送日期更新信号
    Q_EMIT selectionChanged();
}

void LunarCalendarWidget::dateChanged(int year, int month, int day)
{
    //如果原有天大于28则设置为1,防止出错
    if(year <= 1970 || year >=2099){
        return ;
    }
    date.setDate(year, month, day > 28 ? 1 : day);
    initDate();
}

bool LunarCalendarWidget::getShowLunar()
{
    //语言是简体或繁体中文且区域是中国且GSetting的值时，
    //这个时候才显示农历和黄历信息
    QString lang,format;
    getLocale(lang,format);
    //qInfo() << lang << format << (calendar_gsettings->get("calendar").toString() == "lunar") ;
    if((lang.contains("zh_CN")||lang.contains("zh_HK")) &&
            (calendar_gsettings->get("calendar").toString() == "lunar")){
        m_showLunar = true;
    }else {
        m_showLunar = false;
    }
    return m_showLunar;
}

void LunarCalendarWidget::setShowLunar(bool showLunar)
{
    qDebug() << showLunar;
    bool realShow = showLunar & yijistate;
    //日界面需要重绘
    for(auto i = 0 ;i < dayItems.size();i++) {
        dayItems.at(i)->setShowLunar(showLunar);
    }
    //日期字符串要重新写
    lunarstate = realShow;
    //黄历信息不能再显示了
    yiLabel->setVisible(realShow);
    jiLabel->setVisible(realShow);
    //yijistate = realShow;
    labWidget->setVisible(showLunar);
    yijiWidget->setVisible(showLunar);
    yijichoose->setChecked(yijistate);
    //重新布局当前窗口
    Q_EMIT almanacChanged(realShow);
}



LunarCalendarWidget::CalendarStyle LunarCalendarWidget::getCalendarStyle() const
{
    return this->calendarStyle;
}

QDate LunarCalendarWidget::getDate() const
{
    return this->date;
}

QColor LunarCalendarWidget::getWeekTextColor() const
{
    return this->weekTextColor;
}

QColor LunarCalendarWidget::getWeekBgColor() const
{
    return this->weekBgColor;
}

QString LunarCalendarWidget::getBgImage() const
{
    return this->bgImage;
}

LunarCalendarWidget::SelectType LunarCalendarWidget::getSelectType() const
{
    return this->selectType;
}


QColor LunarCalendarWidget::getBorderColor() const
{
    return this->borderColor;
}
QColor LunarCalendarWidget::getWeekColor() const
{
    return this->weekColor;
}

QColor LunarCalendarWidget::getSuperColor() const
{
    return this->superColor;
}

QColor LunarCalendarWidget::getLunarColor() const
{
    return this->lunarColor;
}
QColor LunarCalendarWidget::getCurrentTextColor() const
{
    return this->currentTextColor;
}

QColor LunarCalendarWidget::getOtherTextColor() const
{
    return this->otherTextColor;
}
QColor LunarCalendarWidget::getSelectTextColor() const
{
    return this->selectTextColor;
}

QColor LunarCalendarWidget::getHoverTextColor() const
{
    return this->hoverTextColor;
}

QColor LunarCalendarWidget::getCurrentLunarColor() const
{
    return this->currentLunarColor;
}

QColor LunarCalendarWidget::getOtherLunarColor() const
{
    return this->otherLunarColor;
}

QColor LunarCalendarWidget::getSelectLunarColor() const
{
    return this->selectLunarColor;
}

QColor LunarCalendarWidget::getHoverLunarColor() const
{
    return this->hoverLunarColor;
}

QColor LunarCalendarWidget::getCurrentBgColor() const
{
    return this->currentBgColor;
}

QColor LunarCalendarWidget::getOtherBgColor() const
{
    return this->otherBgColor;
}

QColor LunarCalendarWidget::getSelectBgColor() const
{
    return this->selectBgColor;
}

QColor LunarCalendarWidget::getHoverBgColor() const
{
    return this->hoverBgColor;
}

QSize LunarCalendarWidget::sizeHint() const
{
    return QSize(600, 500);
}

QSize LunarCalendarWidget::minimumSizeHint() const
{
    return QSize(200, 150);
}

//显示上一年
void LunarCalendarWidget::showPreviousYear()
{
    int year = date.year();
    int month = date.month();
    int day = date.day();
    if (year <= 1901) {
        return;
    }

    year--;
    dateChanged(year, month, day);
}

//显示下一年
void LunarCalendarWidget::showNextYear()
{
    int year = date.year();
    int month = date.month();
    int day = date.day();
    if (year >= 2099) {
        return;
    }

    year++;
    dateChanged(year, month, day);
}

//显示上月日期
void LunarCalendarWidget::showPreviousMonth(bool date_clicked)
{
    int year = date.year();
    int month = date.month();
    int day = date.day();
    if (year <= 1901 && month == 1) {
        return;
    }

    //extra:
    if (date_clicked) month--;
    if (month < 1) {
               month = 12;
               year--;
    }
    dateChanged(year, month, day);
}

//显示下月日期
void LunarCalendarWidget::showNextMonth(bool date_clicked)
{
    int year = date.year();
    int month = date.month();
    int day = date.day();
    if (year >= 2099 ) {
        return;
    }

    //extra
    if (date_clicked)month++;
    if (month > 12) {
               month = 1;
               year++;
    }

    dateChanged(year, month, day);
    //dayChanged(this->date,clickDate);
}

//转到今天
void LunarCalendarWidget::showToday()
{
    widgetYearBody->hide();
    widgetmonthBody->hide();
    m_widgetDayBody->show();
    widgetWeek->show();
    date = QDate::currentDate();
    changeMode(0);
    initDate();
    s_clickDate = date;
    dayChanged(this->date,QDate());
}

void LunarCalendarWidget::setCalendarStyle(const LunarCalendarWidget::CalendarStyle &calendarStyle)
{
    if (this->calendarStyle != calendarStyle) {
        this->calendarStyle = calendarStyle;
    }
}

void LunarCalendarWidget::setWeekNameFormat(bool FirstDayisSun)
{
    FirstdayisSun = FirstDayisSun;
    setLocaleCalendar();//在设置是从某星期作为起点时,再判断某区域下日历的显示
    initDate();
}

void LunarCalendarWidget::setDate(const QDate &date)
{
    if (this->date != date) {
        this->date = date;
        initDate();
    }
}

void LunarCalendarWidget::setWeekTextColor(const QColor &weekTextColor)
{
    if (this->weekTextColor != weekTextColor) {
        this->weekTextColor = weekTextColor;
        initStyle();
    }
}

void LunarCalendarWidget::setWeekBgColor(const QColor &weekBgColor)
{
    if (this->weekBgColor != weekBgColor) {
        this->weekBgColor = weekBgColor;
        initStyle();
    }
}

void LunarCalendarWidget::setBgImage(const QString &bgImage)
{
    if (this->bgImage != bgImage) {
        this->bgImage = bgImage;
        initStyle();
    }
}

void LunarCalendarWidget::setSelectType(const LunarCalendarWidget::SelectType &selectType)
{
    if (this->selectType != selectType) {
        this->selectType = selectType;
        initStyle();
    }
}

void LunarCalendarWidget::setBorderColor(const QColor &borderColor)
{
    if (this->borderColor != borderColor) {
        this->borderColor = borderColor;
        initStyle();
    }
}

void LunarCalendarWidget::setWeekColor(const QColor &weekColor)
{
    if (this->weekColor != weekColor) {
        this->weekColor = weekColor;
        initStyle();
    }
}

void LunarCalendarWidget::setSuperColor(const QColor &superColor)
{
    if (this->superColor != superColor) {
        this->superColor = superColor;
        initStyle();
    }
}

void LunarCalendarWidget::setLunarColor(const QColor &lunarColor)
{
    if (this->lunarColor != lunarColor) {
        this->lunarColor = lunarColor;
        initStyle();
    }
}

void LunarCalendarWidget::setCurrentTextColor(const QColor &currentTextColor)
{
    if (this->currentTextColor != currentTextColor) {
        this->currentTextColor = currentTextColor;
        initStyle();
    }
}

void LunarCalendarWidget::setOtherTextColor(const QColor &otherTextColor)
{
    if (this->otherTextColor != otherTextColor) {
        this->otherTextColor = otherTextColor;
        initStyle();
    }
}

void LunarCalendarWidget::setSelectTextColor(const QColor &selectTextColor)
{
    if (this->selectTextColor != selectTextColor) {
        this->selectTextColor = selectTextColor;
        initStyle();
    }
}

void LunarCalendarWidget::setHoverTextColor(const QColor &hoverTextColor)
{
    if (this->hoverTextColor != hoverTextColor) {
        this->hoverTextColor = hoverTextColor;
        initStyle();
    }
}

void LunarCalendarWidget::setCurrentLunarColor(const QColor &currentLunarColor)
{
    if (this->currentLunarColor != currentLunarColor) {
        this->currentLunarColor = currentLunarColor;
        initStyle();
    }
}

void LunarCalendarWidget::setOtherLunarColor(const QColor &otherLunarColor)
{
    if (this->otherLunarColor != otherLunarColor) {
        this->otherLunarColor = otherLunarColor;
        initStyle();
    }
}

void LunarCalendarWidget::setSelectLunarColor(const QColor &selectLunarColor)
{
    if (this->selectLunarColor != selectLunarColor) {
        this->selectLunarColor = selectLunarColor;
        initStyle();
    }
}

void LunarCalendarWidget::setHoverLunarColor(const QColor &hoverLunarColor)
{
    if (this->hoverLunarColor != hoverLunarColor) {
        this->hoverLunarColor = hoverLunarColor;
        initStyle();
    }
}

void LunarCalendarWidget::setCurrentBgColor(const QColor &currentBgColor)
{
    if (this->currentBgColor != currentBgColor) {
        this->currentBgColor = currentBgColor;
        initStyle();
    }
}

void LunarCalendarWidget::setOtherBgColor(const QColor &otherBgColor)
{
    if (this->otherBgColor != otherBgColor) {
        this->otherBgColor = otherBgColor;
        initStyle();
    }
}

void LunarCalendarWidget::setSelectBgColor(const QColor &selectBgColor)
{
    if (this->selectBgColor != selectBgColor) {
        this->selectBgColor = selectBgColor;
        initStyle();
    }
}

void LunarCalendarWidget::setHoverBgColor(const QColor &hoverBgColor)
{
    if (this->hoverBgColor != hoverBgColor) {
        this->hoverBgColor = hoverBgColor;
        initStyle();
    }
}
void LunarCalendarWidget::changeMonth(bool forward)
{
    int year = date.year();
    int month = date.month();
    int day = date.day();
    if (year <= 1901 && month == 1) {
        return;
    }
    if(forward){
        month +=3;
        if(month > 12) {
            year += 1;
            month -=12;
        }
    }else{
        month -=3;
        if(month<=0){
            year -=1;
            month +=12;
        }
    }

    dateChanged(year, month, day);
}
void LunarCalendarWidget::changeYear(bool forward)
{
    int year = date.year();
    int month = date.month();
    int day = date.day();
    if (year <= 1901 || year >= 2099) {
        return;
    }

    if(forward)
        year +=3;
    else
        year -=3;

    dateChanged(year, month, day);
}
void LunarCalendarWidget::wheelEvent(QWheelEvent *event) {
    switch (m_currentType) {
    case 0:
        if (event->delta() > 100) {
            showPreviousMonth();
        } else if (event->delta() < -100) {
            showNextMonth();
        }
        break;

    case 2:
        if (event->delta() > 100) {
            //向前三年
            changeYear(false);
        } else if (event->delta() < -100){
            //向后三年
            changeYear(true);
        }
        break;
    default:

    case 1:
        break;
    }
    event->accept();
//    return QWidget::wheelEvent(event);

}

bool  LunarCalendarWidget::eventFilter(QObject *watched, QEvent *event)
{
    if(event->type() == QEvent::MouseButtonPress){
        qDebug() << event->type()<< watched->objectName();
        QMouseEvent *mouse = static_cast<QMouseEvent*>(event);
        if(mouse!=nullptr) {
            if(watched == this){
                if(mouse->source() == Qt::MouseEventSynthesizedByQt){
                    m_start_y = mouse->pos().y();
                }
                if(m_currentType == 0){
                    QPoint pt = m_widgetDayBody->mapFromGlobal(QCursor::pos());
                    for(auto w : dayItems){
                        if(w->geometry().contains(pt))
                            m_clickedWidget = w;

                    }
                }else if(m_currentType == 2){
                    QPoint pt = widgetYearBody->mapFromGlobal(QCursor::pos());
                    for(auto w : yearItems){
                        if(w->geometry().contains(pt))
                            m_clickedWidget = w;

                    }
                }else if(m_currentType == 1){
                    QPoint pt = widgetmonthBody->mapFromGlobal(QCursor::pos());
                    for(auto w: monthItems){
                        if(w->geometry().contains(pt))
                            m_clickedWidget = w;
                    }
                }
                return false;
            }
        }
    }else if(event->type()==QEvent::MouseButtonRelease){
        qDebug() << event->type() << watched->objectName();
        //return -1;
        QMouseEvent *mouse = static_cast<QMouseEvent*>(event);
        if(mouse!=nullptr) {
            if(watched == this){
                if(mouse->source() == Qt::MouseEventSynthesizedByQt){
                    //触摸的释放
                    if(m_start_y == -1)
                        return false;

                    if( mouse->pos().y() - m_start_y > 100){
                        switch(m_currentType){
                        case 0:
                            showNextMonth();
                            break;
                        case 2:
                            changeYear(true);
                            break;
                        }
                         return false;
                    }else if(mouse->pos().y() - m_start_y < -100){
                         switch(m_currentType){
                         case 0:
                             showPreviousMonth();
                             break;
                         case 2:
                             changeYear(false);
                             break;
                         }
                         return false;
                    }
                }
                //鼠标抬起
                if(m_clickedWidget==nullptr){
                    return false;
                }
                if(m_clickedWidget->geometry().contains(m_widgetDayBody->mapFromGlobal(QCursor::pos()))){
                    qDebug() << "选中";
                    LunarCalendarItem *item = qobject_cast<LunarCalendarItem*>(m_clickedWidget);
                    if(dayItems.contains(item))
                        item->onSelected();

                    LunarCalendarYearItem *yItem = qobject_cast<LunarCalendarYearItem*>(m_clickedWidget);
                    if(yearItems.contains(yItem))
                        yItem->onSelected();

                     LunarCalendarMonthItem *mItem = qobject_cast<LunarCalendarMonthItem*>(m_clickedWidget);
                     if(monthItems.contains(mItem))
                         mItem->onSelected();

                }
                return false;
            }
        }
    }
    else if (event->type()==QEvent::MouseMove){
        QMouseEvent *mouse = static_cast<QMouseEvent*>(event);
        if(mouse!=nullptr) {
            if(mouse->source()==Qt::MouseEventSynthesizedByQt){
                return -1;
            }
        }
        if(m_currentType == 0){
            for(auto w:dayItems){
                if(w->geometry().contains(m_widgetDayBody->mapFromGlobal(QCursor::pos()))){
                    w->onEnter();
                } else {
                    w->onLeave();
                }
            }
        } else if(m_currentType == 2){
            for(auto w:yearItems){
                if(w->geometry().contains(widgetYearBody->mapFromGlobal(QCursor::pos()))){
                    w->onEnter();
                } else {
                    w->onLeave();
                }
            }
        } else if(m_currentType == 1){
            for(auto w:monthItems){
                if(w->geometry().contains(widgetmonthBody->mapFromGlobal(QCursor::pos()))){
                    w->onEnter();
                }else{
                    w->onLeave();
                }
            }
        }
        return false;
    } else if(event->type()==QEvent::Enter){
        LunarCalendarItem *item = qobject_cast<LunarCalendarItem*>(watched);
        if(dayItems.contains(item) == true){
            item->onEnter();
        }
        LunarCalendarYearItem *yItem = qobject_cast<LunarCalendarYearItem*>(watched);
        if(yearItems.contains(yItem)){
            yItem->onEnter();
        }
    }else if(event->type()==QEvent::Leave){
        for(auto day : dayItems)
            day->onLeave();
        for (auto month :monthItems)
            month->onLeave();
        for(auto year:yearItems)
            year->onLeave();

    } else if(event->type()==QEvent::WindowDeactivate){
        this->hide();
        return false;
    }

    return false;
}
void LunarCalendarWidget::showCalendar(bool needShowToday)
{
    KWindowSystem::setState(winId(),NET::SkipPager|NET::SkipTaskbar|NET::SkipSwitcher);
    show();
    if(needShowToday) {
        showToday();
    }
}
void LunarCalendarWidget::initTransparency()
{
    const QByteArray tranparency(TRANSPARENCY_SETTING);
    if (QGSettings::isSchemaInstalled(tranparency)){
        m_transparencySetting = new QGSettings(tranparency);
        m_trans = m_transparencySetting->get(TRANSPARENCY_KEY).toDouble()*255;
        update();
        connect(m_transparencySetting,&QGSettings::changed,this,[=](const QString &key) {
            if(key == TRANSPARENCY_KEY) {
                m_trans = m_transparencySetting->get(TRANSPARENCY_KEY).toDouble()*255;
                update();
            }
        });
    } else {
        m_trans = 0.75;
        update();
    }
}
void LunarCalendarWidget::paintEvent(QPaintEvent*e)
{
    QStyleOption opt;
    opt.init(this);
    QPainter p(this);
    QColor color = palette().color(QPalette::Base);
    color.setAlpha(m_trans);
    QBrush brush = QBrush(color);
    p.setBrush(brush);
    p.setRenderHints(QPainter::Antialiasing|QPainter::SmoothPixmapTransform);
    p.setPen(Qt::NoPen);
    p.drawRoundedRect(opt.rect,6,6);
    return QWidget::paintEvent(e);
}

PartLineWidget::PartLineWidget(QWidget *parent) : QWidget(parent)
{

}

void PartLineWidget::paintEvent(QPaintEvent *event)
{
    QPainter p(this);

    QRect rect = this->rect();

    p.setRenderHint(QPainter::Antialiasing);  // 反锯齿;
    QColor color=qApp->palette().color(QPalette::BrightText);
//    if(color.red() == 255 && color.green() == 255 && color.blue() == 255){
//        color.setRgb(1,1,1,255);
//    } else if (color.red() == 31 && color.green() == 32 && color.blue() == 34) {
//        color.setRgb(255,255,255,255);
//    }
    //color.setAlphaF(0.08);
    p.setBrush(color);
    p.setOpacity(0.08);
    p.setPen(Qt::NoPen);
    p.drawRoundedRect(rect,0,0);

    QWidget::paintEvent(event);
}

statelabel::statelabel() : QLabel()
{


}

//鼠标点击事件
void statelabel::mousePressEvent(QMouseEvent *event)
{
    if (event->buttons() == Qt::LeftButton){
        Q_EMIT labelclick();

    }
    return;
}
//快捷键
void LunarCalendarWidget::keyPressEvent(QKeyEvent *ev)
{
    if(ev->key()==Qt::Key_Escape) {
        this->hide();
    }
    QWidget::keyPressEvent(ev);
}

