import traceback
from PyQt6.QtWidgets import QFileDialog
from openpyxl import Workbook
from Functions.QtFunctions.LogerinTxt import app_logger
import datetime
from Functions.apiFunction import api_fc


def saveRisktable(self):
    try:
        fileName, _ = QFileDialog.getSaveFileName(None, "选取文件夹", "/风险数据库.xlsx" ,"xlsx(*.xlsx)")
        if fileName:
            ip = "http://" + str(self.ipinfo) + "/static/saveRisktable"
            # res = requests.get(url=ip, timeout=30).json()["返回值"]
            res = api_fc.request_get('/static/saveRisktable')["返回值"]
            wb = Workbook()
            wb.create_sheet(title="风险数据库.xlsx", index=0)
            ws = wb.active
            ws.title = '风险数据库'
            ws = wb['风险数据库']
            for row in range(1, len(res ) +1):
                for cloumn in range(1, 8):
                    ws.cell(row, cloumn).number_format = '@'
            ws.cell(1, 1).value = "风险编号"
            ws.cell(1, 2).value = "状态"
            ws.cell(1, 3).value = "提示内容"
            ws.cell(1, 4).value = "触发条件1"
            ws.cell(1, 5).value = "触发条件2"
            ws.cell(1, 6).value = "触发条件3"
            ws.cell(1, 7).value = "触发条件4"
            ws.cell(1, 8).value = "触发条件5"
            if len(res) != 0:
                ii =1
                for i in res:
                    for j in range(0, 8):
                        # print(ii,j)
                        ws.cell(int(ii) + 1, j+ 1).value = i[j]
                    ii += 1
            wb.save(fileName)
    except Exception:
        print(traceback.format_exc())


def saveAllflight(self):
    try:
        index = {"序号": "0", "类型": "9", "航班号": "4", "机型": "2", "发动机": "3", "机号": "1", "计达": "5", "预达": "6", "计飞": "7",
                 "机位": "8"}
        index2 = {1: "序号", 2: "类型", 3: "航班号", 4: "机型", 5: "发动机", 6: "机号", 7: "计达", 8: "预达", 9: "计飞", 10: "机位"}
        fileName, _ = QFileDialog.getSaveFileName(None, "选取文件夹", "/%s全天航班导出（未含保障结束）.xlsx" % self.selectedtime,
                                                  "xlsx(*.xlsx)")
        # print(fileName)
        if fileName:
            # ip = "http://" + str(self.ipinfo) + "/static/" + "tableWidgetDispaly22/" + "%s" % self.selectedtime
            # res = requests.get(url=ip, timeout=30).json()
            res = api_fc.request_post('/static/tableWidgetDispaly22',selectedtime= "%s" % self.selectedtime)['data']
            # print(res)
            wb = Workbook()
            wb.create_sheet(title="%s全天航班导出（未含保障结束）.xlsx" % self.selectedtime, index=0)
            ws = wb.active
            ws.title = '航班数据'
            ws = wb['航班数据']
            for row in range(1, 400):
                for cloumn in range(1, 10):
                    ws.cell(row, cloumn).number_format = '@'
            ws.cell(1, 1).value = "序号"
            ws.cell(1, 2).value = "类型"
            ws.cell(1, 3).value = "航班号"
            ws.cell(1, 4).value = "机型"
            ws.cell(1, 5).value = "发动机"
            ws.cell(1, 6).value = "机号"
            ws.cell(1, 7).value = "计达"
            ws.cell(1, 8).value = "预达"
            ws.cell(1, 9).value = "计飞"
            ws.cell(1, 10).value = "机位"
            if len(res) != 0:
                for i in res.keys():
                    if res[i]["109"] != "4":
                        for j in range(1, 11):
                            if j == 2 and "3U" in res[i]["4"] and "CSC" in res[i]["4"]:
                                ws.cell(int(i) + 2, j).value = "外" + str(res[i][index[index2[j]]])
                            elif j == 7 or j == 8:
                                text = str(res[i][index[index2[j]]]).replace(":", "") if str(
                                    res[i][index[index2[j]]]) != "" else ""
                                ws.cell(int(i) + 2, j).value = text
                            elif j == 9:
                                text = str(str(res[i][index[index2[j]]]).split("]")[1]).replace(":", "") if "]" in str(
                                    res[i][index[index2[j]]]) else ""
                                ws.cell(int(i) + 2, j).value = text
                            else:
                                ws.cell(int(i) + 2, j).value = res[i][index[index2[j]]]
            wb.save(fileName)
        self.show_message2("提示", "%s全天航班导出成功！文件已保存至%s" % (self.selectedtime, fileName))
    except Exception:
        self.show_message2("警告", "导出失败，确认%s是否被打开或联系管理员！！！" % fileName)
        app_logger.error(traceback.format_exc())


def saveAllflight2(self):
    try:
        time2 = datetime.datetime.strptime(self.selectedtime, "%Y%m%d")
        time1 = str((time2 - datetime.timedelta(days=1)).strftime("%Y%m%d"))
        index = {"序号": "1", "类型": "19", "航班号": "9", "机型": "5", "发动机": "7", "机号": "3", "计达": "11", "预达": "13",
                 "计飞": "15", "机位": "8", "放行": "21", "工1": "23", "工2": "25", "工3": "27", "工4": "29", "备注": "61",
                 "班组长": "31"}
        index2 = {1: "序号", 2: "类型", 3: "航班号", 4: "机型", 5: "发动机", 6: "机号", 7: "计达", 8: "预达", 9: "计飞", 10: "机位", 11: "放行",
                  12: "工1", 13: "工2", 14: "工3", 15: "工4", 16: "备注", 17: "班组长"}
        fileName, _ = QFileDialog.getSaveFileName(None, "选取文件夹",
                                                  "/%s航班安排备份导出.xlsx" % (str(time1) + "-" + str(self.selectedtime)[-2:]),
                                                  "xlsx(*.xlsx)")
        # print(fileName)
        wb = Workbook()
        if fileName:
            for selectedtime in [self.selectedtime, time1]:
                # ip = "http://" + str(self.ipinfo) + "/static/" + "tableWidgetDispaly11/" + "%s" % selectedtime
                # res = requests.get(url=ip, timeout=30).json()
                res = api_fc.request_post('/static/tableWidgetDispaly11',selectedtime="%s" % selectedtime)['data']
                # print(res)
                wb.create_sheet(title="%s" % selectedtime, index=0)
                ws = wb.active
                ws.title = "%s" % selectedtime
                ws = wb["%s" % selectedtime]
                for row in range(1, 400):
                    for cloumn in range(1, 18):
                        ws.cell(row, cloumn).number_format = '@'
                ws.cell(1, 1).value = "序号"
                ws.cell(1, 2).value = "类型"
                ws.cell(1, 3).value = "航班号"
                ws.cell(1, 4).value = "机型"
                ws.cell(1, 5).value = "发动机"
                ws.cell(1, 6).value = "机号"
                ws.cell(1, 7).value = "计达"
                ws.cell(1, 8).value = "预达"
                ws.cell(1, 9).value = "计飞"
                ws.cell(1, 10).value = "机位"
                ws.cell(1, 11).value = "放行"
                ws.cell(1, 12).value = "工1"
                ws.cell(1, 13).value = "工2"
                ws.cell(1, 14).value = "工3"
                ws.cell(1, 15).value = "工4"
                ws.cell(1, 16).value = "备注"
                ws.cell(1, 17).value = "班组长"

                if len(res) != 0:
                    for i in res.keys():
                        for j in range(1, 18):
                            if j == 2:
                                if "3U" not in res[i]["4"] and "CSC" not in res[i]["4"]:
                                    ws.cell(int(i) + 2, j).value = "外" + str(res[i][index[index2[j]]])
                                else:
                                    ws.cell(int(i) + 2, j).value = res[i][index[index2[j]]]
                            elif j == 7 or j == 8:
                                text = str(res[i][index[index2[j]]]).replace(":", "") if str(
                                    res[i][index[index2[j]]]) != "" else ""
                                ws.cell(int(i) + 2, j).value = text
                            elif j == 9:
                                text = str(str(res[i][index[index2[j]]]).split("]")[1]).replace(":", "") if "]" in str(
                                    res[i][index[index2[j]]]) else ""
                                ws.cell(int(i) + 2, j).value = text
                            else:
                                ws.cell(int(i) + 2, j).value = res[i][index[index2[j]]]
        wb.save(fileName)
        self.show_message2("提示", "%s全天航班导出成功！文件已保存至%s" % (self.selectedtime, fileName))
    except Exception:
        self.show_message2("警告", "导出失败，确认%s是否被打开或联系管理员！！！" % fileName)
        app_logger.error(traceback.format_exc())


def saveAllflight3(self):
    try:
        time2 = datetime.datetime.strptime(self.selectedtime, "%Y%m%d")
        time1 = str((time2 - datetime.timedelta(days=1)).strftime("%Y%m%d"))
        index = {"序号": "0", "类型": "9", "航班号": "4", "机型": "2", "发动机": "3", "机号": "1", "计达": "5", "预达": "6", "计飞": "7",
                 "机位": "8", "工作单": "10", "飞单": "11", "客舱单": "12", "临工单": "13", "AMRO记录": "14", "备注": "32", "电签": "15"}
        index2 = {1: "序号", 2: "类型", 3: "航班号", 4: "机型", 5: "发动机", 6: "机号", 7: "计达", 8: "预达", 9: "计飞", 10: "机位",
                  11: "工作单", 12: "飞单", 13: "客舱单", 14: "临工单", 15: "AMRO记录", 16: "备注", 17: "电签"}
        fileName, _ = QFileDialog.getSaveFileName(None, "选取文件夹",
                                                  "/%s维修记录备份导出.xlsx" % (str(time1) + "-" + str(self.selectedtime)[-2:]),
                                                  "xlsx(*.xlsx)")
        # print(fileName)
        wb = Workbook()
        if fileName:
            for selectedtime in [self.selectedtime, time1]:
                # ip = "http://" + str(self.ipinfo) + "/static/" + "tableWidgetDispaly22/" + "%s" % selectedtime
                # res = requests.get(url=ip, timeout=30).json()
                res = api_fc.request_post('/static/tableWidgetDispaly22', selectedtime="%s" % self.selectedtime)['data']
                # print(res)
                wb.create_sheet(title="%s" % selectedtime, index=0)
                ws = wb.active
                ws.title = "%s" % selectedtime
                ws = wb["%s" % selectedtime]
                for row in range(1, 400):
                    for cloumn in range(1, 18):
                        ws.cell(row, cloumn).number_format = '@'
                ws.cell(1, 1).value = "序号"
                ws.cell(1, 2).value = "类型"
                ws.cell(1, 3).value = "航班号"
                ws.cell(1, 4).value = "机型"
                ws.cell(1, 5).value = "发动机"
                ws.cell(1, 6).value = "机号"
                ws.cell(1, 7).value = "计达"
                ws.cell(1, 8).value = "预达"
                ws.cell(1, 9).value = "计飞"
                ws.cell(1, 10).value = "机位"
                ws.cell(1, 11).value = "工作单"
                ws.cell(1, 12).value = "飞单"
                ws.cell(1, 13).value = "客舱单"
                ws.cell(1, 14).value = "临工单"
                ws.cell(1, 15).value = "AMRO记录"
                ws.cell(1, 16).value = "备注"
                ws.cell(1, 17).value = "电签"

                if len(res) != 0:
                    for i in res.keys():
                        for j in range(1, 18):
                            if j == 2:
                                if "3U" not in res[i]["4"] and "CSC" not in res[i]["4"]:
                                    ws.cell(int(i) + 2, j).value = "外" + str(res[i][index[index2[j]]])
                                else:
                                    ws.cell(int(i) + 2, j).value = res[i][index[index2[j]]]
                            elif j == 6:
                                text = "B-" + str(res[i][index[index2[j]]])
                                ws.cell(int(i) + 2, j).value = text
                            elif j == 7 or j == 8:
                                text = str(res[i][index[index2[j]]]).replace(":", "") if str(
                                    res[i][index[index2[j]]]) != "" else ""
                                ws.cell(int(i) + 2, j).value = text
                            elif j == 9:
                                text = str(str(res[i][index[index2[j]]]).split("]")[1]).replace(":", "") if "]" in str(
                                    res[i][index[index2[j]]]) else ""
                                ws.cell(int(i) + 2, j).value = text
                            else:
                                ws.cell(int(i) + 2, j).value = res[i][index[index2[j]]]
        wb.save(fileName)
        self.show_message2("提示", "%s全天航班导出成功！文件已保存至%s" % (self.selectedtime, fileName))
    except Exception:
        self.show_message2("警告", "导出失败，确认%s是否被打开或联系管理员！！！" % fileName)
        app_logger.error(traceback.format_exc())


def saveDealflight(self):
    try:
        index = {"序号": "0", "类型": "9", "航班号": "4", "机型": "2", "发动机": "3", "机号": "1", "计达": "5", "预达": "6", "计飞": "7",
                 "机位": "8"}
        index2 = {1: "序号", 2: "类型", 3: "航班号", 4: "机型", 5: "发动机", 6: "机号", 7: "计达", 8: "预达", 9: "计飞", 10: "机位"}
        fileName, _ = QFileDialog.getSaveFileName(None, "选取文件夹", "/%s交班航班导出.xlsx" % self.selectedtime, "xlsx(*.xlsx)")
        # print(fileName)
        if fileName:
            # ip = "http://" + str(self.ipinfo) + "/static/" + "tableWidgetDispaly22/" + "%s" % self.selectedtime
            # res = requests.get(url=ip, timeout=30).json()
            res = api_fc.request_post('/static/tableWidgetDispaly22',selectedtime= "%s" % self.selectedtime)['data']
            # print(res)
            wb = Workbook()
            wb.create_sheet(title="%s交班航班导出.xlsx" % self.selectedtime, index=0)
            ws = wb.active
            ws.title = '航班数据'
            ws = wb['航班数据']
            for row in range(1, 400):
                for cloumn in range(1, 10):
                    ws.cell(row, cloumn).number_format = '@'
            ws.cell(1, 1).value = "序号"
            ws.cell(1, 2).value = "类型"
            ws.cell(1, 3).value = "航班号"
            ws.cell(1, 4).value = "机型"
            ws.cell(1, 5).value = "发动机"
            ws.cell(1, 6).value = "机号"
            ws.cell(1, 7).value = "计达"
            ws.cell(1, 8).value = "预达"
            ws.cell(1, 9).value = "计飞"
            ws.cell(1, 10).value = "机位"
            if len(res) != 0:
                for i in res.keys():
                    if res[i]["109"] == "1" or res[i]["109"] == "3":
                        for j in range(1, 11):
                            if j == 2:
                                if "3U" not in res[i]["4"] and "CSC" not in res[i]["4"]:
                                    ws.cell(int(i) + 2, j).value = "外" + str(res[i][index[index2[j]]])
                                else:
                                    ws.cell(int(i) + 2, j).value = res[i][index[index2[j]]]
                            elif j == 7 or j == 8:
                                text = str(res[i][index[index2[j]]]).replace(":", "") if str(
                                    res[i][index[index2[j]]]) != "" else ""
                                ws.cell(int(i) + 2, j).value = text
                            elif j == 9:
                                text = str(str(res[i][index[index2[j]]]).split("]")[1]).replace(":", "") if "]" in str(
                                    res[i][index[index2[j]]]) else ""
                                ws.cell(int(i) + 2, j).value = text
                            else:
                                ws.cell(int(i) + 2, j).value = res[i][index[index2[j]]]
            wb.save(fileName)
        self.show_message2("提示", "%s交班航班导出成功！文件已保存至%s" % (self.selectedtime, fileName))
    except Exception:
        self.show_message2("警告", "导出失败，确认%s是否被打开或联系管理员！！！" % fileName)
        app_logger.error(traceback.format_exc())

def saveCase(self):
    try:
        fileName, _ = QFileDialog.getSaveFileName(None, "选取文件夹", "/停场航班导入模板.xlsx", "xlsx(*.xlsx)")
        if fileName:
            wb = Workbook()
            wb.create_sheet(title="停场航班导入模板", index=0)
            ws = wb.active
            ws.title = '航班数据'
            ws = wb['航班数据']
            for row in range(1, 50):
                for cloumn in range(1, 7):
                    ws.cell(row, cloumn).number_format = '@'
            ws.cell(1, 1).value = "序号"
            ws.cell(1, 2).value = "日期"
            ws.cell(1, 3).value = "机号"
            ws.cell(1, 4).value = "机位"
            ws.cell(1, 5).value = "机型"
            ws.cell(1, 6).value = "发动机"
            ws.cell(1, 7).value = "录入数据请从第三行开始录入，切勿覆盖第一二行数据！！！"
            ws.cell(2, 1).value = "1"
            ws.cell(2, 2).value = "2024/03/21"
            ws.cell(2, 3).value = "1663"
            ws.cell(2, 4).value = "722"
            ws.cell(2, 5).value = "A321"
            ws.cell(2, 6).value = "V2500"
            ws.cell(2, 7).value = "录入数据请从第三行开始录入，切勿覆盖第一二行数据！！！"
            wb.save(fileName)
            self.show_message2("提示", "导出成功！文件已保存至%s" % fileName)
    except Exception:
        self.show_message2("警告", "导出失败，确认%s是否被打开或联系管理员！！！")
        app_logger.error(traceback.format_exc())