from PySide2.QtWidgets import QApplication,QMessageBox,QLineEdit,QTableWidgetItem
from PySide2.QtWidgets import QFileDialog
from PySide2.QtUiTools import QUiLoader
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib
import sys
import os

class Login():#登录界面窗口
      
    def __init__(self):
        self.ui = QUiLoader().load('login.ui')
        self.ui.Btn_Login.clicked.connect(self.open_main)
        self.worrycount=0#错误计数
        self.df=pd.read_excel('社区信息表 .xlsx',dtype=object)
        self.pw=self.df[['电话','密码']]

    def open_main(self):#登录
        ID=self.ui.Login_User_Input.text()
        PassWord=self.ui.Login_Pa_Input.text()
        if ID in self.pw.values:
          if ID=='admin' and PassWord==self.pw[self.pw['电话']==ID].iloc[0,1]:
             self.w2= windowgly()#管理员登录
             self.w2.ui.show()
             self.ui.close()
          elif PassWord==self.pw[self.pw['电话']==ID].iloc[0,1]:
             row=list(self.df[self.df['电话']==ID].index)
             self.w2= windowjm(ID,row[0])#居民登录
             self.w2.ui.myself.insertRow(0) 
             self.w2.ui.myself.setItem(0,0, QTableWidgetItem(self.df.loc[row[0],'姓名']))
             self.w2.ui.myself.setItem(0,1, QTableWidgetItem(self.df.loc[row[0],'单元']))
             self.w2.ui.myself.setItem(0,2, QTableWidgetItem(self.df.loc[row[0],'楼栋']))
             self.w2.ui.myself.setItem(0,3, QTableWidgetItem(str(self.df.loc[row[0],'房间'])))
             self.w2.ui.show()
             self.ui.close()
             QMessageBox.information(self.ui,'公告',self.df.loc[0,'单元'])
            # 11714584364
          else:
             #密码错误重试判断
             if self.worrycount<3: 
                self.worrycount+=1
                self.ui.Login_Pa_Input.clear()
                self.ui.wgt.setText('密码错误,您还有{}次重试机会'.format(3-self.worrycount))
                print('>>>密码错误\n>>>您还有{}次重试机会'.format(3-self.worrycount))
                #重复的登录判断
                #self.open_main()
             else:
                    print('>>>密码错误次数过多\n>>>请联系系统管理员\n>>>终端关闭')
                    a=self.df[(self.df['电话']==ID)].index
                    self.df.loc[a,'0还是1']=1
                    self.df.to_excel('社区信息表 .xlsx',index=None)
                    QMessageBox.warning(self.ui,'密码错误次数过多','请联系系统管理员,终端关闭')
                    self.ui.close()
        else:
             print('>>>系统中没有此账号\n>>>请联系管理员')
             self.ui.wgt.setText('系统中没有此账号,请联系管理员')

class windowgly():#管理员窗口
    def __init__(self):
        self.ui= QUiLoader().load('windowgly.ui')
        self.row=0
        self.Things=pd.read_excel('社区物资表 .xlsx',dtype=object)
        self.df=pd.read_excel('社区信息表 .xlsx',dtype=object)
        self.xsj=pd.read_excel('打卡表.xlsx',dtype=object)
        self.ui.Wang_GTgg.append(self.df.loc[0,'单元'])
        self.ui.changekey.clicked.connect(self.changekey)
        self.ui.Zhou_SJ1.clicked.connect(self.show_frozenusers)
        self.ui.rechangekey.clicked.connect(self.rechangekey)
        self.ui.newgg.clicked.connect(self.newgg)
        self.ui.lookthings.clicked.connect(self.lookthings)
        self.ui.changethings.clicked.connect(self.changethings)
        self.ui.things.cellChanged.connect(self.newthings)
        self.ui.Yang_XT1.clicked.connect(self.lookyang)
        self.ui.Yang_XT2.clicked.connect(self.lookmj)
        self.ui.Tu.clicked.connect(self.bar_show)
        self.ui.daka1.clicked.connect(self.daka)
        self.ui.nodaka1.clicked.connect(self.nodaka)
        self.ui.in_information.clicked.connect(self.in_information)
        self.ui.out_information.clicked.connect(self.out_information)
        self.ui.changeuser.clicked.connect(self.changeuser)
        self.ui.close1.clicked.connect(self.close)

    def changekey(self):#修改管理员密码
        Newkey1=self.ui.newkey1.text()
        Newkey2=self.ui.newkey2.text()
        if(Newkey1!=Newkey2):
            QMessageBox.warning(self.ui,'两次输入不一致','请重新输入')
        else:
            self.df.loc[0,'密码']=Newkey1
            self.df.to_excel('社区信息表 .xlsx',index=None)
            QMessageBox.information(self.ui,'修改成功','请重新登录')
            self.w2=Login()
            self.w2.ui.show()
            self.ui.close()

    def show_frozenusers(self):#查看冻结账号
        for i in range(0,len(self.df)):
            if self.df.loc[i,'0还是1']==1:
                print('第%d个'%self.row)
                self.ui.frozenu_sers.insertRow(self.row) 
                self.ui.frozenu_sers.setItem(self.row,0, QTableWidgetItem(self.df.loc[i,'姓名']))
                self.ui.frozenu_sers.setItem(self.row,1, QTableWidgetItem(self.df.loc[i,'电话']))
                self.row+=1 
        self.ui.rechangekey.setEnabled(True)
        self.ui.Zhou_SJ1.setEnabled(False)

    def rechangekey(self):#重置冻结账号密码
        for i in range(0,len(self.df)):
            if self.df.loc[i,'0还是1']==1:
                self.df.loc[i,'0还是1']=0
                self.df.loc[i,'密码']='123456'
                self.ui.frozenu_sers.removeRow(0)
        self.df.to_excel('社区信息表 .xlsx',index=None)
        QMessageBox.information(self.ui,'重置成功','请继续下一步操作')
        self.row=0
        self.ui.Zhou_SJ1.setEnabled(True)
        self.ui.rechangekey.setEnabled(False)

    def newgg(self):#发布新的公告
        text=self.ui.Wang_GTnew.toPlainText()
        self.ui.Wang_GTgg.clear()
        self.ui.Wang_GTgg.append(text)
        QMessageBox.information(self.ui,'修改成功','请继续下一步操作')
        self.df.loc[0,'单元']=text
        self.df.to_excel('社区信息表 .xlsx',index=None)

    def lookthings(self):#查看物资情况
        for i in range(0,len(self.Things)):
            self.ui.things.insertRow(self.row) 
            self.ui.things.setItem(self.row,0, QTableWidgetItem(self.Things.loc[i,'大类']))
            self.ui.things.setItem(self.row,1, QTableWidgetItem(self.Things.loc[i,'类型']))
            self.ui.things.setItem(self.row,2, QTableWidgetItem(self.Things.loc[i,'具体']))
            self.ui.things.setItem(self.row,3, QTableWidgetItem(str(self.Things.loc[i,'数量'])))
            self.ui.things.setItem(self.row,4, QTableWidgetItem(self.Things.loc[i,'单位']))
            self.row+=1
        self.row=0
        self.ui.lookthings.setEnabled(False)

    def newthings(self,x,y):#修改物资情况
        newthings=self.ui.things.item(x,y).text()
        self.Things.iloc[x,y]=newthings

    def changethings(self):#确认修改物资情况
        self.Things.to_excel('社区物资表 .xlsx',index=None)
        QMessageBox.information(self.ui,'修改成功','请继续下一步操作')
        self.ui.lookthings.setEnabled(True)

    def lookyang(self):#查看阳性名单
        for i in list(self.df[self.df['核酸']=='阳'].index):
                self.ui.Yangtable.insertRow(self.row) 
                yxt=self.df.loc[i,'单元']+self.df.loc[i,'楼栋']+str(self.df.loc[i,'房间'])
                self.ui.Yangtable.setItem(self.row,0, QTableWidgetItem(self.df.loc[i,'姓名']))
                self.ui.Yangtable.setItem(self.row,1, QTableWidgetItem(yxt))
                self.ui.Yangtable.setItem(self.row,2, QTableWidgetItem(self.df.loc[i,'电话']))
                self.row+=1
        self.row=0
        print(1)
        self.ui.Yang_XT1.setEnabled(False)

    def lookmj(self):#查看密接人员
        yxt=self.df[['姓名','单元','楼栋','房间','核酸','电话']]
        str_value_list=[]
        for row_index,row in yxt.iterrows():   
            str1=str(row['单元'])
            str2=str(row['楼栋'])
            str3=str(row['房间'])
            str_value=str1[0]+str2[0]+str3
            str_value_list.append(str_value)   
        yxt['编码']=str_value_list    
        yxt=yxt.set_index('编码')       
        yx=yxt[yxt['核酸']=='阳'] 
        list1=[i for i in yx.index]
        yx=yx.set_index('姓名')
        for i in list1:
            for row_index,row in yxt.iterrows(): 
                if row_index[0:2]==i[0:2]:
                      self.ui.mjtable.insertRow(self.row) 
                      yxtt=row['单元']+row['楼栋']+str(row['房间'])
                      self.ui.mjtable.setItem(self.row,0, QTableWidgetItem(row['姓名']))
                      self.ui.mjtable.setItem(self.row,1, QTableWidgetItem(yxtt))
                      self.ui.mjtable.setItem(self.row,2, QTableWidgetItem(row['电话']))
                      self.row+=1
        self.row=0
        self.ui.Yang_XT2.setEnabled(False)

    def bar_show(self):#查看统计图
        yx=self.df[self.df['核酸']=='阳']
        list1=[i for i in yx.index]
        yx=yx.set_index('姓名')
        list2=[]
        for i in list1:
            for row_index,row in self.df.iterrows(): 
                if str(row_index)[0:2]==str(i)[0:2]:
                    list2.append(row)
        df_mj=pd.DataFrame(list2)
        matplotlib.rcParams['font.family']='simHei'
        matplotlib.rcParams['axes.unicode_minus'] =False
        dy_list=self.df['单元'].unique()
        y1=[]
        y2=[]
        for i in dy_list:
            y1.append(len(yx[yx['单元']==i]))
        for i in dy_list:
            y2.append(len(df_mj[df_mj['单元']==i]))       
        x = range((len(dy_list)))  
        p1=plt.bar(x, y1, width=0.2,color='red',label='阳性')
        p2=plt.bar([i + 0.2 for i in x], y2, width=0.2, color='orange',label='密接')
        plt.xticks([i + 0.1 for i in x], dy_list)
        plt.bar_label(p1,label_type='edge')
        plt.bar_label(p2,label_type='edge')
        plt.ylabel('人数')
        plt.xlabel('单元')
        plt.title('小区阳性及密接统计')
        plt.legend()
        plt.show() 

    def daka(self):#查看打卡情况
        for i in range(0,len(self.xsj)):
            self.ui.daka2.insertRow(self.row) 
            self.ui.daka2.setItem(self.row,0, QTableWidgetItem(self.xsj.loc[i,'姓名']))
            self.ui.daka2.setItem(self.row,1, QTableWidgetItem(self.xsj.loc[i,'打卡情况']))
            self.ui.daka2.setItem(self.row,2, QTableWidgetItem(self.xsj.loc[i,'今日所在地']))
            self.ui.daka2.setItem(self.row,3, QTableWidgetItem(self.xsj.loc[i,'健康码状态']))
            self.ui.daka2.setItem(self.row,4, QTableWidgetItem(self.xsj.loc[i,'是否核酸']))
            self.ui.daka2.setItem(self.row,5, QTableWidgetItem(self.xsj.loc[i,'是否隔离']))
            self.row+=1
        self.row=0

    def nodaka(self):#查看未打卡名单
        for i in range(0,len(self.xsj)):
            if(self.xsj.loc[i,'打卡情况']=='无'):
                self.ui.nodaka2.insertRow(self.row) 
                self.ui.nodaka2.setItem(self.row,0, QTableWidgetItem(self.xsj.loc[i,'姓名']))
                self.row+=1
        self.row=0

    def in_information(self):#导入居民信息
        filePath, _  = QFileDialog.getOpenFileName(
                    self.ui,"选择你导入的文件", r"d:", "类型 (*.xlsx *.xls )")
        in1=pd.read_excel(filePath,dtype=object)
        #in1即为想要导入的文件，将它拼接上去再写入即可
        print(in1)
        print(filePath)
        QMessageBox.information(self.ui,'','导入成功')

    def out_information(self):#导出居民信息
        filePath, _  = QFileDialog.getSaveFileName(
                    self.ui,"导出居民信息",r"d:","类型 (*.xlsx)" )
        print(filePath)
        self.df.to_excel(filePath)
        QMessageBox.information(self.ui,'','导出成功')

    def changeuser(self):#切换账号
        choice = QMessageBox.question(
        self.ui,
        '确认',
        '确定要切换账号吗？')
        if choice == QMessageBox.Yes:
             self.w2= Login()
             self.w2.ui.show()
             self.ui.close()
        if choice == QMessageBox.No:
            print('你选择了no')
         
    def close(self):#退出
        choice = QMessageBox.question(
        self.ui,
        '确认',
        '真的要离开吗qaq？')
        if choice == QMessageBox.Yes:
             self.ui.close()
        if choice == QMessageBox.No:
            print('你选择了no')

class windowjm():#居民端窗口
    def __init__(self,ID,index):
        self.ui= QUiLoader().load('windowjm.ui')
        self.id=ID
        self.index=index
        self.row=0
        self.Things=pd.read_excel('社区物资表 .xlsx',dtype=object)
        self.df=pd.read_excel('社区信息表 .xlsx',dtype=object)
        self.xsj=pd.read_excel('打卡表.xlsx',dtype=object)
        self.applything=pd.read_excel('物资申请表.xlsx',dtype=object)
        self.ui.changekey.clicked.connect(self.changekey)
        self.ui.lookthings.clicked.connect(self.lookthings)
        self.ui.addthings.clicked.connect(self.addthings)
        self.ui.myself.cellChanged.connect(self.newmyself)
        self.ui.changemyself.clicked.connect(self.changemyself)
        self.ui.checkYXT.clicked.connect(self.checkYXT)
        self.ui.delete2.clicked.connect(self.delete)   
        self.ui.sign.clicked.connect(self.sign)
        self.ui.lookhistory.clicked.connect(self.history)
        self.ui.changeuser.clicked.connect(self.changeuser)
        self.ui.close1.clicked.connect(self.close)
        self.ui.Wang_GTgg.append(self.df.loc[0,'单元'])
        self.ui.province.setText('湖南')
        self.ui.city.setText('长沙')
        self.ui.area.setText('岳麓')

    def changekey(self):#修改密码
        Newkey1=self.ui.newkey1.text()
        Newkey2=self.ui.newkey2.text()
        row=self.index
        if(Newkey1!=Newkey2):
            QMessageBox.warning(self.ui,'两次输入不一致','请重新输入')
        else:
            self.df.loc[row,'密码']=Newkey1
            self.df.to_excel('社区信息表 .xlsx',index=None)
            QMessageBox.information(self.ui,'修改成功','请重新登录')
            self.w2=Login()
            self.w2.ui.show()
            self.ui.close()

    def lookthings(self):#查看物资情况
        for i in range(0,len(self.Things)):
            self.ui.things.insertRow(self.row) 
            self.ui.things.setItem(self.row,0, QTableWidgetItem(self.Things.loc[i,'大类']))
            self.ui.things.setItem(self.row,1, QTableWidgetItem(self.Things.loc[i,'类型']))
            self.ui.things.setItem(self.row,2, QTableWidgetItem(self.Things.loc[i,'具体']))
            self.ui.things.setItem(self.row,3, QTableWidgetItem(str(self.Things.loc[i,'数量'])))
            self.ui.things.setItem(self.row,4, QTableWidgetItem(self.Things.loc[i,'单位']))
            self.row+=1
        self.row=0
        print('lalal')
        #self.ui.lookthings.setEnabled(False)

    def addthings(self):#增加申领物资
        self.ui.thingsadd.insertRow(self.row)
        self.row+=1
        print(self.row)

    def delete(self):#删除申领物资
        row=self.ui.deleterow.text()
        row=int(row)-1
        self.ui.thingsadd.removeRow(row)
        self.row-=1
        print(row)

    def checkYXT(self):#确认申领取物资ID(电话号码/账号)，df(社区物资表)，df1(物资申请表)，yxt(社区信息表)
        yxt_dict={}; ID=self.id; df=self.Things
        df1=self.applything; yxt=self.df
        row=self.ui.thingsadd.rowCount()
        for x in range(row):
            key=self.ui.thingsadd.item(x,0).text()
            value=self.ui.thingsadd.item(x,1).text()
            yxt_dict[key]=value
        print(yxt_dict)
        list1=[]
        dict2={}
        for key,value in yxt_dict.items():
            for row_index, row in df.iterrows():
                if row['具体']==key:
                    dict1=dict(row)
                    df.loc[row_index,'数量']=int(df.loc[row_index,'数量'])-int(value)
                    dict1['数量']=value
                    dict1['电话']=ID
                    list1.append(dict1)
                    break        
        df2=pd.DataFrame(list1)
        df=df.set_index('大类')
        df.to_excel('社区物资表 .xlsx') 
        df1=df1.append(df2,ignore_index=True)
        for row_index,row in yxt.iterrows():
            dict2[row['姓名']]=row['电话']
        for i in df1.index:
            for key,value in dict2.items():
                 if value==str(df1.loc[i,'电话']):
                      df1.loc[i,'姓名']=key
        df1=df1.set_index('姓名')
        df1.to_excel('物资申请表.xlsx')
        yxt_dict.clear()
        print(yxt_dict)
        QMessageBox.about(self.ui,'申请成功','请等待管理员审核')

    def history(self):#df1(物资申请表)
        ID=self.id; df1=self.applything
        for row_index ,row in df1.iterrows():
            if row['电话']==ID:
                self.ui.thingshistory.insertRow(self.row) 
                self.ui.thingshistory.setItem(self.row,0, QTableWidgetItem(row['具体']))
                self.ui.thingshistory.setItem(self.row,1, QTableWidgetItem(str(row['数量'])))
                self.row+=1
                print(row['具体'],row['数量']) #
        self.row=0

    def newmyself(self,x,y):#读取修改的个人信息
        newmyself=self.ui.myself.item(x,y).text()
        if(y==0):
            self.df.loc[self.index,'姓名']=newmyself
        elif(y==1):
            self.df.loc[self.index,'单元']=newmyself
        elif(y==2):
            self.df.loc[self.index,'楼栋']=newmyself
        else:
            self.df.loc[self.index,'房间']=int(newmyself)
        print(newmyself)

    def changemyself(self):#确认修改个人信息
        self.df.to_excel('社区信息表 .xlsx',index=None)
        QMessageBox.information(self.ui,'修改成功','请继续下一步操作')

    def sign(self):#打卡
        adress=self.ui.province.text()+'省'+self.ui.city.text()+'市'+self.ui.area.text()+'区'
        adress=adress+self.ui.detail.text()
        jkm=self.ui.jkm.checkedButton().text()
        hs=self.ui.hs.checkedButton().text()
        gl=self.ui.geli.checkedButton().text()
        self.xsj.loc[self.index-1,'打卡情况']='Yes'
        self.xsj.loc[self.index-1,'今日所在地']=adress
        self.xsj.loc[self.index-1,'健康码状态']=jkm
        self.xsj.loc[self.index-1,'是否核酸']=hs
        self.xsj.loc[self.index-1,'是否隔离']=gl
        print(adress,jkm,hs,gl)
        self.xsj.to_excel('打卡表.xlsx',index=None)
        QMessageBox.about(self.ui,'','您已完成今日打卡')

    def changeuser(self):#切换账号
        choice = QMessageBox.question(
        self.ui,
        '确认',
        '确定要切换账号吗？')
        if choice == QMessageBox.Yes:
             self.w2= Login()
             self.w2.ui.show()
             self.ui.close()
        if choice == QMessageBox.No:
            print('你选择了no')
         
    def close(self):#退出
        choice = QMessageBox.question(
        self.ui,
        '确认',
        '真的要离开吗qaq？')
        if choice == QMessageBox.Yes:
             self.ui.close()
        if choice == QMessageBox.No:
            print('你选择了no')

if __name__ == '__main__':
    app = QApplication.instance()
    if app is None: 
        app = QApplication(sys.argv)
    zp = Login()
    zp.ui.show()
    sys.exit(app.exec_())
