#include "leadscheme.h"
#include <QDebug>
#include <QJsonObject>
#include <QJsonValue>
#include <QButtonGroup>
#include "operatorjson.h"
#include <QApplication>
#include <QScrollArea>
#include <QDir>
#include <QFileInfoList>
#include <QFileInfo>
#include "logger.h"
LeadScheme::LeadScheme(QWidget * parent ):QWidget (parent)
{
    init();
    initconnect();
    initLay();

}
LeadScheme::~LeadScheme()
{


}

void LeadScheme::init()
{
    QSize sizetemp(60,60);
    m_btnOK.setFixedSize(sizetemp);
    m_btndelete.setFixedSize(sizetemp);
    m_btnNew.setFixedSize(sizetemp);
     // m_btnNew.setText("新建");
     // m_btndelete.setText("删除");
     // m_btnCancel.setText("取消");
     // m_btnOK.setText("修改");
      m_btnOK.setStyleSheet("QPushButton{border-image:url(:/image/EGG_icon_Modify.png);}"
                             "QPushButton:hover{border-image:url(:/image/EGG_icon_Modify_hover.png);}"
                             "QPushButton:pressed{border-image:url(:/image/EGG_icon_Modify_checked.png);}"
                             );
      m_btndelete.setStyleSheet("QPushButton{border-image:url(:/image/EGG_icond_DeleteSh.png);}"
                             "QPushButton:hover{border-image:url(:/image/EGG_icon_DeleteSh_hover.png);}"
                             "QPushButton:pressed{border-image:url(:/image/EGG_icon_DeleteSh_checked.png);}"
                             );
      m_btnNew.setStyleSheet("QPushButton{border-image:url(:/image/EGG_icon_newShec.png);}"
                             "QPushButton:hover{border-image:url(:/image/EGG_icon_newShec_hover.png);}"
                             "QPushButton:pressed{border-image:url(:/image/EGG_icon_newShec_checked.png);}"
                             );

}
bool LeadScheme::initconnect()
{
    bool bCon = true;
    bCon = connect(&m_btnOK,SIGNAL(clicked(bool)),this,SLOT(slotSave()));
    if(!bCon)
     {
                logError()<<"connect failed"<<endl;
                return bCon;

    }
    bCon = connect(&m_btnNew,SIGNAL(clicked(bool)),this,SLOT(slotNew()));
    if(!bCon)
     {
                logError()<<"connect failed"<<endl;
                return bCon;

    }
    bCon = connect(&m_btndelete,SIGNAL(clicked(bool)),this,SLOT(slotDelete()));
    if(!bCon)
     {
                logError()<<"connect failed"<<endl;
                return bCon;

    }
     return bCon;
}

void LeadScheme::initLay()
{
#if 0
    QLabel * labScheme = new QLabel;
    labScheme->setText("导联方案");
    QVBoxLayout * vlayScheme = new QVBoxLayout;
    vlayScheme->addWidget(labScheme);
    vlayScheme->addWidget(&m_LeadSchemes);

    QLabel * labNum = new QLabel;
    labNum->setText("导联");
    QVBoxLayout * vlayNum = new QVBoxLayout;
    vlayNum->addWidget(labNum );
    vlayNum->addWidget(&m_listNum);


    QLabel * labPoints = new QLabel;
    labPoints->setText("测点");
    QVBoxLayout * vlayPoints = new QVBoxLayout;
    vlayPoints->addWidget(labPoints);
    vlayPoints->addWidget(&m_listPoints);


    QLabel * labExPoints = new QLabel;
    labExPoints->setText("参考点");
    QVBoxLayout * vlayExPoints = new QVBoxLayout;
    vlayExPoints->addWidget(labExPoints );
    vlayExPoints->addWidget(&m_listExPoints );


    QHBoxLayout * hlayWPoints =  new QHBoxLayout;
    QWidget     * wPoints = new QWidget;
    wPoints->setLayout(hlayWPoints);
    hlayWPoints->addLayout(vlayNum );
    hlayWPoints->addLayout(vlayPoints);
    hlayWPoints->addLayout(vlayExPoints);

    QLabel * labScheme = new QLabel;
    labScheme->setText("导联方案");
    QVBoxLayout * vlayScheme = new QVBoxLayout;
    vlayScheme->addWidget(labScheme,1,Qt::AlignHCenter);
    vlayScheme->addWidget(&m_LeadSchemes,1);
    vlayScheme->addStretch();


#else

    QLabel * labScheme = new QLabel;
    labScheme->setText("导联方案");
    labScheme->setObjectName("labScheme");

    QLabel * labNum = new QLabel;
    labNum->setText("导联");
   labNum->setObjectName("labSchemeNum");
     QLabel * labPoints = new QLabel;
    labPoints->setText("测点");
    labPoints->setObjectName("labSchemePoints");
    QLabel * labExPoints = new QLabel;
    labExPoints->setText("参考点");
    labExPoints->setObjectName("labSchemePointsparam");
    //start
    QWidget     * wPoints = new QWidget;

    QGridLayout * gridlayOut =  new QGridLayout;
    QVBoxLayout  * vlayPoints = new QVBoxLayout;
    vlayPoints->addLayout(gridlayOut);
   // vlayPoints->addStretch();
    wPoints->setLayout(vlayPoints);
    QStringList strList1,strList2,strList3;
    strList1<<"0"<<"1"<<"2"<<"3"<<"4"<<"5"<<"6"<<"7"<<"8"<<"9"<<"10"<<"11"<<
                            "12"<<"13"<<"14"<<"15";
   strList2<<"F1"<<"F2"<<"F3"<<"F4"<<"C3"<<"C4"<<"P3"<<"P4"<<"O1"<<"O2"<<"F7"<<"F8"<<
                                "T3"<<"T4"<<"T5"<<"T6";
   strList3<<"A1"<<"A2"<<"A1"<<"A1"<<"A2"<<"A1"<<"A2"<<"A1"<<"A2"<<"A1"<<"A2"<<"A1"<<
                                "A1"<<"A2"<<"A1"<<"A2";
    pButtonGroup0 = new QButtonGroup(this);

    QButtonGroup *pButtonGroup1 = new QButtonGroup(this);
    // 设置互斥
    pButtonGroup1->setExclusive(true);
    QButtonGroup *pButtonGroup2= new QButtonGroup(this);
    // 设置互斥
    pButtonGroup2->setExclusive(true);
    QButtonGroup *pButtonGroup3 = new QButtonGroup(this);
    // 设置互斥
    pButtonGroup3->setExclusive(true);
    int colmn = 0;

#if 0
    QStringList  Sches;
    Sches<<"8通道"<<"16通道"<<"64通道";
    gridlayOut->addWidget(labScheme,0,colmn++,Qt::AlignHCenter);
    for (int i= 0 ; i<Sches.size();i++)
    {
        QPushButton * btn  =  new QPushButton(Sches.at(i));
        //btn->setMinimumHeight(minHeight);
        btn->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
        pButtonGroup0->addButton(btn);
        gridlayOut->addWidget( btn,i+1,0);
        btn->setCheckable(true);
    }
#else
    QStringList  Sches;
    Sches<<"8通道"<<"16通道"<<"64通道";
    //遍历加载当前已经存在的方案
    QDir dir(QApplication::applicationDirPath()+"/Scheme/");
    QStringList fileList;
    QFileInfoList fileInfoList = dir.entryInfoList(QDir::Files | QDir::NoDotAndDotDot | QDir::Dirs);
    foreach (auto fileInfo, fileInfoList)
    {
           if(fileInfo.isFile())
           {

                if(!Sches.contains(fileInfo.baseName()) && fileInfo.baseName().compare("0")!=0)
                {
                    Sches.append(fileInfo.baseName());
                }
           }
       }
    gridlayOut->addWidget(labScheme,0,colmn++,Qt::AlignHCenter);
    QScrollArea * scroll = new QScrollArea;
    scroll->setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding));
    scroll->setWidgetResizable(true);
    scroll->setAlignment(Qt::AlignRight);
    QWidget * wShech = new QWidget;

    gridlayOut->addWidget(scroll,1,colmn-1,12,1);
   // QGridLayout * gridShech  =  new QGridLayout;
    m_vlayHH = new QVBoxLayout;
    wShech->setLayout(m_vlayHH);
    for (int i= 0 ; i<Sches.size();i++)
    {
        QPushButton * btn  =  new QPushButton(Sches.at(i));
        connect(btn,SIGNAL(clicked(bool)),this,SLOT(slotUpdateCurScheme()));
        btn->setMaximumHeight(60);
        btn->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
        pButtonGroup0->addButton(btn);
        //gridShech->addWidget( btn,i+1,0);
        m_vlayHH->addWidget(btn);
        btn->setCheckable(true);
        m_listBtnsSchemes.append(btn);
        btn->setObjectName("btnShem");
#if 1
      btn->setStyleSheet("QPushButton{ background: rgb(255, 255, 255); color: #666666;font-family: Source Han Sans; font-size: 30px;font-weight: normal; border-radius: 4px; border:0px ; } \
                             QPushButton:hover{color: black;background: rgb(255, 255, 255);color: #666666;font-family: Source Han Sans; font-size: 30px;font-weight: normal; border-radius: 4px; }\
                             QPushButton:pressed{color: black; background: rgb(255, 255, 255);color: #666666;font-family: Source Han Sans; font-size: 30px;font-weight: normal; border-radius: 4px;}\
                             QPushButton:checked{ color: white;background:  #0D9DDB;border-radius: 8px; }");
#endif

    }
    m_vlayHH->addStretch();

    scroll->setWidget(wShech);

    QHBoxLayout * hbtn  = new QHBoxLayout;
    hbtn->addStretch();
    hbtn->addWidget(&m_btnNew);
    hbtn->addWidget(&m_btndelete);
    //hbtn->addWidget(&m_btnCancel);
    hbtn->addWidget(&m_btnOK);
    hbtn->addStretch();
    gridlayOut->addLayout(hbtn,14,colmn-1,1,1);
    QLabel * desLab = new QLabel;
    desLab->setObjectName("labDesShec");
    desLab->setText("1 选择重构方式0-9\n(注意：0方式不能重构\n2 左键点击重构选择测参点\n3左键点击部位要选择的点)");
     gridlayOut->addWidget(desLab,15,colmn-1,3,1);

#endif

    gridlayOut->addWidget(labNum,0,colmn++,Qt::AlignHCenter);
    int minHeight = 45;
    for (int i = 0 ;i<strList1.size();i++)
    {
          QPushButton * btn  =  new QPushButton(strList1.at(i));
          //btn->setMinimumHeight(minHeight);
          btn->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
          pButtonGroup1->addButton(btn);
          gridlayOut->addWidget( btn,i+1,1);
          btn->setCheckable(true);
           btn->setObjectName("btnShem1");
#if 1
      btn->setStyleSheet("QPushButton{ background: rgb(255, 255, 255); color: #666666;font-family: Source Han Sans; font-size: 30px;font-weight: normal; border-radius: 4px; border:0px ; } \
                             QPushButton:hover{color: black;background: rgb(255, 255, 255);color: #666666;font-family: Source Han Sans; font-size: 30px;font-weight: normal; border-radius: 4px; }\
                             QPushButton:pressed{color: black; background: rgb(255, 255, 255);color: #666666;font-family: Source Han Sans; font-size: 30px;font-weight: normal; border-radius: 4px;}\
                             QPushButton:checked{ color: white;background:  #0D9DDB;border-radius: 8px; }");
#endif

    }
    gridlayOut->addWidget( labPoints,0,colmn++,Qt::AlignHCenter);
    for (int i = 0 ;i<strList2.size();i++)
    {
          QPushButton * btn  =  new QPushButton(strList2.at(i));
           //btn->setMinimumHeight(minHeight);
           btn->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
          pButtonGroup2->addButton(btn);

          gridlayOut->addWidget( btn,i+1,2);
           btn->setCheckable(true);
            btn->setObjectName("btnShem1");
#if 1
      btn->setStyleSheet("QPushButton{ background: rgb(255, 255, 255); color: #666666;font-family: Source Han Sans; font-size: 30px;font-weight: normal; border-radius: 4px; border:0px ; } \
                             QPushButton:hover{color: black;background: rgb(255, 255, 255);color: #666666;font-family: Source Han Sans; font-size: 30px;font-weight: normal; border-radius: 4px; }\
                             QPushButton:pressed{color: black; background: rgb(255, 255, 255);color: #666666;font-family: Source Han Sans; font-size: 30px;font-weight: normal; border-radius: 4px;}\
                             QPushButton:checked{ color: white;background:  #0D9DDB;border-radius: 8px; }");
#endif

    }
    gridlayOut->addWidget( labExPoints,0,colmn++,Qt::AlignHCenter);
    for (int i = 0 ;i<strList3.size();i++)
    {
          QPushButton * btn  =  new QPushButton(strList3.at(i));
          //btn->setMinimumHeight(minHeight);
          btn->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
          pButtonGroup3->addButton(btn);

          gridlayOut->addWidget( btn,i+1,3);
           btn->setCheckable(true);
            btn->setObjectName("btnShem1");
#if 1
      btn->setStyleSheet("QPushButton{ background: rgb(255, 255, 255); color: #666666;font-family: Source Han Sans; font-size: 30px;font-weight: normal; border-radius: 4px; border:0px ; } \
                             QPushButton:hover{color: black;background: rgb(255, 255, 255);color: #666666;font-family: Source Han Sans; font-size: 30px;font-weight: normal; border-radius: 4px; }\
                             QPushButton:pressed{color: black; background: rgb(255, 255, 255);color: #666666;font-family: Source Han Sans; font-size: 30px;font-weight: normal; border-radius: 4px;}\
                             QPushButton:checked{ color: white;background:  #0D9DDB;border-radius: 8px; }");
#endif
    }
//end

#endif
    QWidget * wClickedPints = new QWidget;
    wClickedPints->setStyleSheet("border-image:url(:/image/img_lead.png);}");

    QVBoxLayout * vlaypointsTemp = new QVBoxLayout;
    m_editShecName.setFixedWidth(180);
    m_editShecName.setPlaceholderText("输入方案名称");
    vlaypointsTemp->addWidget(&m_editShecName);
    vlaypointsTemp->addWidget(wClickedPints);
    QWidget * ww  =new QWidget;
    ww->setLayout(vlaypointsTemp);
   // wClickedPints->setFixedWidth(500);
    //wClickedPints->show();
    QHBoxLayout  * hlayAll = new QHBoxLayout;
   // hlayAll->addLayout(vlayScheme,1);
    hlayAll->addWidget(wPoints,3);
    hlayAll->addWidget(ww,3);


    QList<QColor> colors;
    colors.append(QColor(100, 184, 255));
    colors.append(QColor(255, 107, 107));
    colors.append(QColor(24, 189, 155));
    colors.append(QColor(1, 174, 103));
    colors.append(QColor(52, 73, 94));

    int x = 5;
    int y = 5;
    int radius = 50;

    QStringList  listNames;
    listNames<<"Fp1"<<"Fp2"
            <<"F7"<<"F3"<<"Fz"<<"F4"<<"F8"
             <<"A1"<<"T3"<<"C3"<<"Cz"<<"C4"<<"T4"<<"A2"
            <<"T5"<<"P3" <<"Pz"<<"P4" <<"T6"
            <<"O1"<<"O2";

    QJsonObject json;
    OperatorJson Ojson;
    Ojson.readJson(QApplication::applicationDirPath()+"/Scheme/0.json",json);



    qDebug()<<"hahaha"<<json<<endl;
    for(int i  = 0 ; i< listNames.size();i++)
    {
        MoveButton * btn  =  new MoveButton(wClickedPints);
        btn->setParent(wClickedPints);
        int x =json[listNames.at(i)].toObject()["x"].toInt();
        int  y = json[listNames.at(i)].toObject()["y"].toInt();

        btn->setGeometry(x,y, radius, radius);
        //x = x + radius;
        btn->setText(listNames.at(i));
        btn->setCanMove(true);
        btn->setShowOverlay(true);
        btn->setBgColor(QColor(1, 174, 103));
        m_listMoveBtns.append(btn);
    }


    QWidget  * Wall =  new QWidget;
    Wall->setLayout(hlayAll);
    Wall->setStyleSheet("QWidget \
      {\
          background-color:white;\
           border-radius:10px;\
       }");

    QVBoxLayout * vlayAll = new QVBoxLayout;
    vlayAll->addWidget(Wall);
    //vlayAll->addLayout(hbtn);
    setLayout(vlayAll);

   // setStyleSheet("QLabel{font-family: 思源黑体;font-size: 26px;font-weight: 500;color: #054578;}");
}
void LeadScheme::reLay()
{
    QLayoutItem *child;
    while ((child = m_vlayHH->takeAt(0)) != 0)
    {
        //删除Stretch(弹簧)等布局
        if (child->spacerItem())
        {
            m_vlayHH->removeItem(child);
            continue;
        }
        //删除布局
        //删除布局
        QWidget * w = child->widget();
        m_vlayHH->removeWidget(child->widget());
        child->widget()->setParent(0);
        if (w)
        {
            w->deleteLater();
        }
    }

}
void   LeadScheme::slotUpdateCurScheme()
{
    //1获取方案名称
    QPushButton *btn = static_cast<QPushButton*>(  sender());
    if(btn)
    {
        m_CurScheme = btn->text();
    }
    //2检查对应的方案名称是否存在
    //（2.1）存在就加载原来的
    QString  sFileName = QApplication::applicationDirPath()+"/Scheme/"+m_CurScheme+".json";
    if(QFile::exists(sFileName))
    {
        int radius = 50;
        QJsonObject json;
        OperatorJson Ojson;
        Ojson.readJson(sFileName,json);

        for(int i  = 0 ; i< json.keys().size();i++)
        {
            for(int j =0 ;j < m_listMoveBtns.size();j++)
            {
                if(m_listMoveBtns.at(j)->getText().compare(json.keys().at(i)) ==0)
                {
                  MoveButton * btn =   m_listMoveBtns.at(j);
                 int x =json[json.keys().at(i)].toObject()["x"].toInt();
                 int  y = json[json.keys().at(i)].toObject()["y"].toInt();

                  btn->setGeometry(x,y, radius, radius);
                }

            }

        }

    }
    else // (2.2)不存在就加载模版
    {
        int radius = 50;
        QJsonObject json;
        OperatorJson Ojson;
       Ojson.readJson(QApplication::applicationDirPath()+"/Scheme/0.json",json);
        for(int i  = 0 ; i< json.keys().size();i++)
        {
            for(int j =0 ;j < m_listMoveBtns.size();j++)
            {
                if(m_listMoveBtns.at(j)->getText().compare(json.keys().at(i)) ==0)
                {
                  MoveButton * btn =   m_listMoveBtns.at(j);
                 int x =json[json.keys().at(i)].toObject()["x"].toInt();
                 int  y = json[json.keys().at(i)].toObject()["y"].toInt();

                  btn->setGeometry(x,y, radius, radius);
                }

            }

        }
    }

    //保存最新的位置
    QJsonObject jsonSave;

    for(int i  = 0;i< m_listMoveBtns.size();i++ )
    {
            auto btn =  m_listMoveBtns.at(i);
            QString text = btn->getText();
            int x = btn->x();
            int y = btn->y();
            QJsonObject perJson;
            perJson.insert("x",x);
            perJson.insert("y",y);
            jsonSave.insert(text,perJson);
            qDebug()<<QString("名称:%1\tx:%2\ty:%3").arg(text).arg(x).arg(y)<<endl;
      }
      OperatorJson json;

      json.savaJson(jsonSave,QApplication::applicationDirPath()+"/Scheme/"+m_CurScheme+".json");


}
void  LeadScheme::slotSave()
{
      QJsonObject jsonSave;

      for(int i  = 0;i< m_listMoveBtns.size();i++ )
      {
              auto btn =  m_listMoveBtns.at(i);
              QString text = btn->getText();
              int x = btn->x();
              int y = btn->y();
              QJsonObject perJson;
              perJson.insert("x",x);
              perJson.insert("y",y);
              jsonSave.insert(text,perJson);
              qDebug()<<QString("名称:%1\tx:%2\ty:%3").arg(text).arg(x).arg(y)<<endl;
        }

        OperatorJson json;

        json.savaJson(jsonSave,QApplication::applicationDirPath()+"/Scheme/"+m_CurScheme+".json");

  }
  void  LeadScheme::slotNew()
  {
      //1 新建方案名称不为空 且不重复
      QString schemeName =  m_editShecName.text();
      if(schemeName.isEmpty())
      {
          logError()<<"Shech Name is empty!"<<endl;
          return ;
      }
      //2 判断名称是否有重复
         QStringList listNames;
      schemeName = schemeName.trimmed();
      for(int i = 0 ; i< m_listBtnsSchemes.size();i++)
      {
          QString name = m_listBtnsSchemes.at(i)->text();
          if(name.compare(schemeName)== 0)
          {
              logError()<<"Shech Name is repeated!"<<endl;
              return ;
          }
        listNames.append(name);
      }
      listNames.append(schemeName);
      //3 获取当前所有方案名称
      m_listBtnsSchemes.clear();
      reLay();
      //4 重新布局
      for (int i= 0 ; i<listNames.size();i++)
      {
          QPushButton * btn  =  new QPushButton(listNames.at(i));
          connect(btn,SIGNAL(clicked(bool)),this,SLOT(slotUpdateCurScheme()));
          btn->setMaximumHeight(60);
          btn->setObjectName("btnShem");
          btn->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
          pButtonGroup0->addButton(btn);
          //gridShech->addWidget( btn,i+1,0);
          m_vlayHH->addWidget(btn);
          btn->setCheckable(true);
          m_listBtnsSchemes.append(btn);
      }
      m_vlayHH->addStretch();
  }
  void  LeadScheme::slotDelete()
  {
      //1 获取当前列表，从当前列表中获取出被选中的要删除的
      QString sDeleName;
      QStringList listNames;
      for(int i = 0 ; i< m_listBtnsSchemes.size();i++)
      {
          if(m_listBtnsSchemes.at(i)->isChecked())
          {
              //logError()<<"delete:"<<m_listBtnsSchemes.at(i)->text()<<endl;
              sDeleName=m_listBtnsSchemes.at(i)->text();
              continue;
          }
          listNames.append(m_listBtnsSchemes.at(i)->text());
      }
      //2 重新布局
      m_listBtnsSchemes.clear();
       reLay();
       //3
       for (int i= 0 ; i<listNames.size();i++)
       {
           QPushButton * btn  =  new QPushButton(listNames.at(i));
           connect(btn,SIGNAL(clicked(bool)),this,SLOT(slotUpdateCurScheme()));
           btn->setMaximumHeight(40);
           btn->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
           pButtonGroup0->addButton(btn);
           //gridShech->addWidget( btn,i+1,0);
           m_vlayHH->addWidget(btn);
           btn->setCheckable(true);
           m_listBtnsSchemes.append(btn);
       }
       m_vlayHH->addStretch();
       //4 删除对应的位置文件

       QFile::remove( QApplication::applicationDirPath()+"/Scheme/"+sDeleName+".json");
  }
