class EditTodayScheduleCellDialog(QDialog):
    def __init__(self, scheduleId):
        super(EditTodayScheduleCellDialog, self).__init__()
        self.init()
        self.loading(scheduleId)

    def init(self):
        self.initUI()
        self.initSQL()
        self.initOther()
        self.initInteraction()

    def initUI(self):
        self.ui = Ui_EditTodayScheduleCellDialog()
        self.ui.setupUi(self)

    def initSQL(self):
        self.SQLHelper = SQLHelper()

    def initOther(self):
        self.moveFlag = False

    def initInteraction(self):
        self.ui.cancel.clicked.connect(self.cancelClicked)
        self.ui.dialogNavClose.clicked.connect(self.dialogNavCloseClicked)
        self.ui.comfirm.clicked.connect(self.comfirmClicked)

    def loading(self, scheduleId):
        self.loadingShift()
        self.loadingRoom()
        self.loadingStaff()
        self.loadingSchedule(scheduleId)

    def loadingShift(self):
        shifts = self.SQLHelper.getAllShift()
        result = []

        for shift in shifts:
            result.append([shift[1], shift[0]])

        self.ui.loadingShift(result)

    def loadingRoom(self):
        rooms = self.SQLHelper.getAllRoom()
        result = []

        for room in rooms:
            result.append([room[1], room[0]])

        self.ui.loadingRoom(result)

    def loadingStaff(self):
        staffs = self.SQLHelper.getAllStaff()
        result = []

        for staff in staffs:
            result.append([f'{staff[0]:03d}', staff[2], staff[0]])

        self.ui.loadingStaff(result)

    def loadingSchedule(self, scheduleId: int):
        self.scheduleId = scheduleId
        if not scheduleId is None:

            schedule = self.SQLHelper.getScheduleDetailById(scheduleId)[0]

            self.ui.shiftSelection.setCurrentText(schedule[5])
            self.ui.roomSelection.setCurrentText(schedule[7])
            self.ui.staffSelection.setCurrentText(
                f'{schedule[1]:03d} {schedule[2]}')

    def cancelClicked(self):
        self.SQLHelper.close()
        self.reject()

    def dialogNavCloseClicked(self):
        self.SQLHelper.close()
        self.reject()

    def comfirmClicked(self):

        shiftId = self.ui.shiftSelection.currentData(Qt.UserRole)
        roomId = self.ui.roomSelection.currentData(Qt.UserRole)
        staffId = self.ui.staffSelection.currentData(Qt.UserRole)
        date = datetime.now().strftime("%Y-%m-%d")

        if self.scheduleId is None:
            dialog = MessageDialog("提示訊息", "請確認是否新增該筆排班資料")
            if dialog.exec():
                self.SQLHelper.newSchedule(date, staffId, shiftId, roomId)
                self.accept()
        else:
            dialog = MessageDialog("提示訊息", "請確認是否修改該筆排班資料")
            if dialog.exec():
                self.SQLHelper.updateScheduleById(staffId, shiftId, roomId,
                                                  self.scheduleId)
                self.accept()

    def mousePressEvent(self, event):
        if event.button() == Qt.LeftButton:
            self.moveFlag = True
            self.movePosition = event.globalPos() - self.pos()
            self.setCursor(QCursor(Qt.OpenHandCursor))
            event.accept()

    def mouseMoveEvent(self, event):
        if Qt.LeftButton and self.moveFlag:
            self.move(event.globalPos() - self.movePosition)
            event.accept()

    def mouseReleaseEvent(self, event):
        self.moveFlag = False
        self.setCursor(Qt.ArrowCursor)
class ShiftHelper:
    def __init__(self):
        self.initSQL()

    def initSQL(self):
        self.SQLHelper = SQLHelper()

    def getShiftByTime(self, time):

        time = datetime.strptime(time, "%H:%M:%S")

        shifts = self.SQLHelper.getAllShift()

        for shift in shifts:
            start = datetime.strptime(f"{shift[2]}", "%H:%M:%S")
            end = datetime.strptime(f"{shift[3]}", "%H:%M:%S")
            if start > end:
                end += timedelta(days=1)
            if start <= time <= end:
                return shift

    def getShiftStatus(self, shiftId, date, checkIn, checkOut):

        now = datetime.now()

        try:
            checkIn = datetime.strptime(checkIn, "%Y-%m-%d %H:%M:%S")
        except:
            checkIn = None
        try:
            checkOut = datetime.strptime(checkOut, "%Y-%m-%d %H:%M:%S")
        except:
            checkOut = None

        shift = self.SQLHelper.getShiftById(shiftId)

        shouldCheckIn = datetime.strptime(f'{date} {shift[0][2]}',
                                          "%Y-%m-%d %H:%M:%S")
        shouldCheckOut = datetime.strptime(f'{date} {shift[0][3]}',
                                           "%Y-%m-%d %H:%M:%S")

        if shouldCheckIn > shouldCheckOut:
            shouldCheckOut += timedelta(days=1)

        if now < shouldCheckIn:
            if not checkIn is None and not checkOut is None:
                return "早退"
            elif not checkIn is None:
                return "執行中"
            else:
                return "未執行"
        elif shouldCheckIn <= now < shouldCheckOut:
            if checkIn is None:
                return "已遲到未執行"
            elif checkIn >= shouldCheckIn and checkOut is None:
                return "已遲到執行中"
            elif checkOut is None:
                return "執行中"
            elif checkIn >= shouldCheckIn and checkOut < shouldCheckOut:
                return "遲到早退"
            elif checkIn >= shouldCheckIn and checkOut >= shouldCheckOut:
                return "遲到"
            elif checkIn < shouldCheckIn and checkOut < shouldCheckOut:
                return "早退"
        else:
            if checkIn is None and checkOut is None:
                return "曠班"
            elif checkOut is None:
                return "未簽退"
            elif checkIn >= shouldCheckIn and checkOut < shouldCheckOut:
                return "遲到早退"
            elif checkIn >= shouldCheckIn:
                return "遲到"
            elif checkOut < shouldCheckOut:
                return "早退"
            elif checkIn < shouldCheckIn and checkOut >= shouldCheckOut:
                return "準時"
class EditArrangementCellDialog(QDialog):
    def __init__(self, arrangementId):
        super(EditArrangementCellDialog, self).__init__()
        self.init()
        self.loading(arrangementId)

    def init(self):
        self.initUI()
        self.initSQL()
        self.initOther()
        self.initInteraction()

    def initUI(self):
        self.ui = Ui_EditArrangementCellDialog()
        self.ui.setupUi(self)

    def initSQL(self):
        self.SQLHelper = SQLHelper()

    def initOther(self):
        self.moveFlag = False

    def initInteraction(self):
        self.ui.cancel.clicked.connect(self.cancelClicked)
        self.ui.dialogNavClose.clicked.connect(self.dialogNavCloseClicked)
        self.ui.comfirm.clicked.connect(self.comfirmClicked)

    def loading(self, arrangementId):
        self.loadingWeek()
        self.loadingShift()
        self.loadingRoom()
        self.loadingPeriod()
        self.loadingStaff()
        self.loadingArrangement(arrangementId)

    def loadingWeek(self):
        result = [["星期一", 0], ["星期二", 1], ["星期三", 2], ["星期四", 3], ["星期五", 4],
                  ["星期六", 5], ["星期日", 6]]
        self.ui.loadingWeek(result)

    def loadingShift(self):
        shifts = self.SQLHelper.getAllShift()
        result = []

        for shift in shifts:
            result.append([shift[1], shift[0]])

        self.ui.loadingShift(result)

    def loadingRoom(self):
        rooms = self.SQLHelper.getAllRoom()
        result = []

        for room in rooms:
            result.append([room[1], room[0]])

        self.ui.loadingRoom(result)

    def loadingPeriod(self):
        periods = self.SQLHelper.getPeriodNotVacation()
        result = []

        for period in periods:
            result.append([period[1], period[0]])

        self.ui.loadingPeriod(result)

    def loadingStaff(self):
        staffs = self.SQLHelper.getAllStaff()
        result = []

        for staff in staffs:
            result.append([f'{staff[0]:03d}', staff[2], staff[0]])

        self.ui.loadingStaff(result)

    def loadingArrangement(self, arrangementId):
        self.arrangementId = arrangementId
        if not arrangementId is None:
            arrangement = self.SQLHelper.getArrangementDetailById(
                arrangementId)[0]

            weekTrans = {
                0: "星期一",
                1: "星期二",
                2: "星期三",
                3: "星期四",
                4: "星期五",
                5: "星期六",
                6: "星期日"
            }

            self.ui.weekSelection.setCurrentText(weekTrans[arrangement[3]])
            self.ui.shiftSelection.setCurrentText(arrangement[5])
            self.ui.roomSelection.setCurrentText(arrangement[7])
            self.ui.periodSelection.setCurrentText(arrangement[9])
            self.ui.staffSelection.setCurrentText(
                f'{arrangement[1]:03d} {arrangement[2]}')

    def cancelClicked(self):
        self.SQLHelper.close()
        self.reject()

    def dialogNavCloseClicked(self):
        self.SQLHelper.close()
        self.reject()

    def comfirmClicked(self):

        week = self.ui.weekSelection.currentData(Qt.UserRole)
        shiftId = self.ui.shiftSelection.currentData(Qt.UserRole)
        roomId = self.ui.roomSelection.currentData(Qt.UserRole)
        periodId = self.ui.periodSelection.currentData(Qt.UserRole)
        staffId = self.ui.staffSelection.currentData(Qt.UserRole)

        if self.arrangementId is None:
            dialog = MessageDialog("提示訊息", "請確認是否新增該筆排班資料")
            if dialog.exec():
                self.SQLHelper.newArrangement(staffId, week, shiftId, roomId,
                                              periodId)
                self.accept()
        else:
            dialog = MessageDialog("提示訊息", "請確認是否修改該筆排班資料")
            if dialog.exec():
                self.SQLHelper.updateArrangementById(self.arrangementId,
                                                     staffId, week, shiftId,
                                                     roomId, periodId)
                self.accept()

    def mousePressEvent(self, event):
        if event.button() == Qt.LeftButton:
            self.moveFlag = True
            self.movePosition = event.globalPos() - self.pos()
            self.setCursor(QCursor(Qt.OpenHandCursor))
            event.accept()

    def mouseMoveEvent(self, event):
        if Qt.LeftButton and self.moveFlag:
            self.move(event.globalPos() - self.movePosition)
            event.accept()

    def mouseReleaseEvent(self, event):
        self.moveFlag = False
        self.setCursor(Qt.ArrowCursor)
class EditShiftDialog(QDialog):
    def __init__(self):
        super(EditShiftDialog, self).__init__()
        self.init()
        self.loading()

    def init(self):
        self.initUI()
        self.initSQL()
        self.initOther()
        self.initInteraction()

    def initUI(self):
        self.ui = Ui_EditShiftDialog()
        self.ui.setupUi(self)

    def initSQL(self):
        self.SQLHelper = SQLHelper()

    def initOther(self):
        self.moveFlag = False

    def initInteraction(self):
        self.ui.cancel.clicked.connect(self.cancelClicked)
        self.ui.dialogNavClose.clicked.connect(self.dialogNavCloseClicked)
        self.ui.delete.clicked.connect(self.deleteClicked)
        self.ui.edit.clicked.connect(self.editClicked)
        self.ui.add.clicked.connect(self.addClicked)

    def loading(self):
        self.loadingVacation()

    def loadingVacation(self):
        shifts = self.SQLHelper.getAllShift()

        result = []
        for shift in shifts:
            tmp_shift = []
            tmp_shift.append(shift[0])
            tmp_shift.append(shift[1])
            tmp_shift.append(shift[2])
            tmp_shift.append(shift[3])
            tmp_shift.append(str(shift[4]))
            tmp_shift.append(str(shift[5]))
            result.append(tmp_shift)

        self.ui.loadingList(result)

    def cancelClicked(self):
        self.SQLHelper.close()
        self.reject()

    def dialogNavCloseClicked(self):
        self.SQLHelper.close()
        self.reject()

    def deleteClicked(self):
        if len(self.ui.listArea.selectedItems()) == 0:
            dialog = MessageDialog("錯誤訊息", "請先選擇項目後再進行相關操作")
            dialog.exec()
        else:
            dialog = MessageDialog("提示訊息", "請確認是否刪除該項班別資料及其關聯的所有班表資訊")
            if dialog.exec():
                shiftId = self.ui.listArea.selectedItems()[0].data(
                    0, Qt.UserRole)
                self.SQLHelper.delShiftById(shiftId)
                self.loadingVacation()

    def editClicked(self):
        if len(self.ui.listArea.selectedItems()) == 0:
            dialog = MessageDialog("錯誤訊息", "請先選擇項目後再進行相關操作")
            dialog.exec()
        else:
            shiftId = self.ui.listArea.selectedItems()[0].data(0, Qt.UserRole)
            dialog = EditShiftCellDialog(shiftId)
            if dialog.exec():
                self.loadingVacation()

    def addClicked(self):
        dialog = EditShiftCellDialog(None)
        if dialog.exec():
            self.loadingVacation()

    def mousePressEvent(self, event):
        if event.button() == Qt.LeftButton:
            self.moveFlag = True
            self.movePosition = event.globalPos() - self.pos()
            self.setCursor(QCursor(Qt.OpenHandCursor))
            event.accept()

    def mouseMoveEvent(self, event):
        if Qt.LeftButton and self.moveFlag:
            self.move(event.globalPos() - self.movePosition)
            event.accept()

    def mouseReleaseEvent(self, event):
        self.moveFlag = False
        self.setCursor(Qt.ArrowCursor)