import datetime

from PyQt6 import QtCore
from PyQt6.QtCore import Qt
from PyQt6.QtWidgets import QWidget , QMessageBox , QTableWidgetItem

from UI.checkCalllist import Ui_checkCalllist
from .LogerinTxt import app_logger
from Functions.apiFunction import api_fc


class checkCalllist(Ui_checkCalllist, QWidget):
    checkCalllist_signal = QtCore.pyqtSignal(str)

    def __init__(self, parent=None):
        super().__init__(parent)
        try:
            self.setupUi(self)
            self.ipinfo = None
            self.selectedtime = None
            self.pushButton.clicked.connect(self.btn)
            # self.show()
        except Exception as e:
            app_logger.log_error(e)

    def start(self):
        try:
            selectedtime_time = str(self.selectedtime) + " 00:00:00"
            now = datetime.datetime.strptime(selectedtime_time, "%Y%m%d %H:%M:%S")
            tom = (now + datetime.timedelta(days=1)).strftime("%Y-%m-%d %H:%M:%S")
            yesterday = (now - datetime.timedelta(days=1)).strftime("%Y-%m-%d %H:%M:%S")
            self.label_5.setText("%s/%s" % (str(yesterday)[0:10], str(tom)[0:10]))
            # ip = "http://" + str(self.ipinfo) + "/static/checkCalllist" + "/" + str(self.selectedtime)
            try:
                # res = requests.get(url=ip, timeout=30).json()
                res = api_fc.request_post('/static/checkCalllist', time=str(self.selectedtime))["data"]
                # print(res)
            except Exception as e:
                # print('登录服务器失败')
                QMessageBox.warning(self, "提示", "服务器连接超时，请联系管理员检查服务器！")
                app_logger.log_error(e)

            self.peopleLabel = ["序号", "电话", "工号", "姓名", "航班号", "拨号次数", "创建时间", "接通时间"]
            self.tableWidgetFlight.setColumnCount(len(self.peopleLabel))
            self.tableWidgetFlight.verticalHeader().setVisible(False)
            self.tableWidgetFlight.setHorizontalHeaderLabels(self.peopleLabel)
            col = len(self.peopleLabel)
            diplaylist = res
            self.tableWidgetFlight.setRowCount(len(diplaylist.keys()))
            for row in diplaylist.keys():
                for colNum in range(0, col):
                    if colNum == 0:
                        self.tableWidgetFlight.setItem(int(row), colNum, QTableWidgetItem(str(row)))
                        self.tableWidgetFlight.item(int(row), colNum).setTextAlignment(Qt.AlignmentFlag.AlignCenter)
                    else:
                        self.tableWidgetFlight.setItem(int(row), colNum,QTableWidgetItem(diplaylist[row][self.peopleLabel[colNum]]))
                        self.tableWidgetFlight.item(int(row), colNum).setTextAlignment(Qt.AlignmentFlag.AlignCenter)
            self.tableWidgetFlight.resizeColumnsToContents()
            # self.show()
        except Exception as e:
            app_logger.log_error(e)
    def btn(self):
        try:
            # ip = "http://" + str(self.ipinfo) + "/static/checkCalllist" + "/" + str(self.selectedtime)
            # self.res = requests.get(url=ip, timeout=30).json()
            self.res = api_fc.request_post('/static/checkCalllist', time=str(self.selectedtime))["data"]
        except Exception as e:
            # print('登录服务器失败')
            QMessageBox.warning(self, "提示", "服务器连接超时，请联系管理员检查服务器！")
            app_logger.log_error(e)
            self.res = {}
        col = len(self.peopleLabel)
        diplaylist = self.res
        self.tableWidgetFlight.setRowCount(len(diplaylist))
        rownum = 0
        for row in diplaylist:
            for colNum in range(0, col):
                if colNum == 0:
                    self.tableWidgetFlight.setItem(int(row), colNum, QTableWidgetItem(str(row)))
                    self.tableWidgetFlight.item(int(row), colNum).setTextAlignment(Qt.AlignmentFlag.AlignCenter)
                else:
                    self.tableWidgetFlight.setItem(int(row), colNum,QTableWidgetItem(diplaylist[row][self.peopleLabel[colNum]]))
                    self.tableWidgetFlight.item(int(row), colNum).setTextAlignment(Qt.AlignmentFlag.AlignCenter)
        self.tableWidgetFlight.resizeColumnsToContents()

    def closeEvent(self, event):
        try:
            reply = QMessageBox.question(self, '确认', '你确定要退出程序吗？')
            reply = str(reply)
            if reply == "StandardButton.Yes":
                self.checkCalllist_signal.emit(reply)
                event.ignore()
            else:
                event.ignore()
        except Exception as e:
            app_logger.log_error(e)
