<template>
  <div class="header-button-bar" style="position: relative">
    <el-tabs v-model="activeTab" type="border-card" @tab-click="handleTabClick">
      <!-- 特殊按钮 tab 退出 打开 保存 -->
      <el-tab-pane v-for="btn in fakeTabs" :key="btn.name" :name="btn.name">
        <template #label>
          <span @click.stop>
            <el-tooltip :content="btn.label" placement="top" effect="light">
              <el-button
                :type="btn.type"
                :size="btn.size || 'small'"
                @click="btn.onClick"
                class="icon-only-button"
              >
                <img :src="btn.icon" alt="icon" class="button-icon" />
              </el-button>
            </el-tooltip>
          </span>
        </template>
        <template #default></template>
      </el-tab-pane>
      <!-- 普通标签页 -->
      <el-tab-pane v-for="tab in tabs" :key="tab.name" :name="tab.name">
        <template #label>
          <span class="tab-label">
            <img :src="tab.icon" alt="icon" class="tab-icon" />
            {{ tab.label }}
          </span>
        </template>
        <div class="button-group">
          <el-tooltip
            v-for="button in tab.buttons"
            :key="button.action"
            :content="button.label"
            placement="top"
            effect="light"
          >
            <el-button
              type=""
              @click="emitButtonClick(button.action)"
              class="icon-text-button"
            >
              <img :src="button.icon" alt="icon" class="button-icon" />
              {{ button.label }}
            </el-button>
          </el-tooltip>
        </div>
      </el-tab-pane>
      <!-- 特殊按钮 tab 帮助 -->
      <el-tab-pane v-for="btn in fakeTabs2" :key="btn.name" :name="btn.name">
        <template #label>
          <span @click.stop>
            <el-tooltip :content="btn.label" placement="top" effect="light">
              <el-button
                :type="btn.type"
                :size="btn.size || 'small'"
                @click="btn.onClick"
                class="icon-only-button"
              >
                <img :src="btn.icon" alt="icon" class="button-icon" />
              </el-button>
            </el-tooltip>
          </span>
        </template>
        <template #default></template>
      </el-tab-pane>
      <el-tab-pane name="user" key="userButton">
        <template #label>
          <span @click.stop style="margin-top: 5px">
            <el-avatar :src="user" :size="22" />
            <el-dropdown style="margin-top: 4px">
              <div class="user-dropdown-trigger">
                <span class="nickname">{{ nickName }}</span>
                <el-icon class="el-icon--right"><arrow-down /></el-icon>
              </div>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="handleProfile">
                    <el-icon><User /></el-icon>
                    <span>{{ $t("index.userinfo") }}</span>
                  </el-dropdown-item>
                  <el-dropdown-item @click="handleChangePassword">
                    <el-icon><Key /></el-icon>
                    <span>{{ $t("index.changePassword") }}</span>
                  </el-dropdown-item>
                  <el-dropdown-item
                    divided
                    @click="handleLogout"
                    style="color: #f56c6c"
                  >
                    <el-icon><SwitchButton /></el-icon>
                    <span>{{ $t("index.logout") }}</span>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </span>
        </template>
        <template #default></template>
      </el-tab-pane>
    </el-tabs>
  </div>

  <el-dialog
    v-model="dialog.userinfoDialog"
    align-center
    :append-to-body="true"
    width="600"
    class="dialog_class"
    draggable
  >
    <template #header="{ titleId, titleClass }">
      <div class="my-header">
        <h4 :id="titleId" :class="titleClass">{{ $t("dialog.userinfo") }}</h4>
      </div>
    </template>

    <el-card class="userinfo-card" shadow="never">
      <template #header>
        <div class="userinfo-header">
          <el-avatar :src="user" :size="30" style="margin-right: 10px" />
          <h4 class="userinfo-nickname">
            {{ userStore.userInfo.nickName || "User" }}
          </h4>
        </div>
      </template>
      <el-form :label-width="labelWidth" label-position="left">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item :label="$t('dialog.username')">
              {{ userStore.userInfo.userName }}
            </el-form-item>
            <el-form-item :label="$t('dialog.mobileNo')">
              {{ userStore.userInfo.mobileNo }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('dialog.nickname')">
              {{ userStore.userInfo.nickName || "User" }}
            </el-form-item>
            <el-form-item :label="$t('dialog.email')">
              {{ userStore.userInfo.email }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item :label="$t('dialog.regTime')">
          {{ userStore.userInfo.regTime }}
        </el-form-item>
      </el-form>
    </el-card>

    <template #footer>
      <span class="userinfo-footer lastbtn">
        <el-button @click="dialog.userinfoDialog = false">{{
          $t("dialog.cancel")
        }}</el-button>
        <el-button @click="dialog.userinfoDialog = false">
          {{ $t("dialog.ok") }}
        </el-button>
      </span>
    </template>
  </el-dialog>

  <el-dialog
    v-model="dialog.changePassword"
    align-center
    :append-to-body="true"
    width="500"
    class="dialog_class"
    draggable
  >
    <template #header="{ titleId, titleClass }">
      <div class="my-header">
        <h4 :id="titleId" :class="titleClass">
          {{ $t("dialog.changePassword") }}
        </h4>
      </div>
    </template>

    <el-card class="userinfo-card" shadow="never">
      <el-form :label-width="labelWidth1">
        <el-form-item :label="`${$t('dialog.oldPassword')}：`">
          <el-input
            v-model="pwd.oldPassword"
            type="password"
            show-password
            :placeholder="$t('dialog.inputOldPassword')"
          />
        </el-form-item>
        <el-form-item :label="`${$t('dialog.newPassword')}：`">
          <el-input
            v-model="pwd.newPassword"
            type="password"
            show-password
            :placeholder="$t('dialog.inputNewPassword')"
          />
        </el-form-item>
        <el-form-item :label="`${$t('dialog.confirmNewPassword')}：`">
          <el-input
            v-model="pwd.confirmNewPassword"
            type="password"
            show-password
            :placeholder="$t('dialog.inputConfirmNewPassword')"
          />
        </el-form-item>
      </el-form>
    </el-card>

    <template #footer>
      <span class="lastbtn">
        <el-button @click="dialog.changePassword = false">{{
          $t("dialog.cancel")
        }}</el-button>
        <el-button @click="ChangePassword">
          {{ $t("dialog.ok") }}
        </el-button>
      </span>
    </template>
  </el-dialog>

<ProjectListDialog
      v-model:visible="dialog.projectListDialog"
      identify="openProject"
      @confirm="handleProjectConfirm"
      @flow-imported="handleFlowImported"
    />
</template>

<script setup>
import { ref, computed } from "vue"
import { request } from "@/utils/request"
import { useRouter } from "vue-router"
import { useI18n } from "vue-i18n"
import { useUserStore } from "@/store/user"
import { removeToken, removeUserId } from "@/utils/token"
import { ElMessageBox, ElMessage } from "element-plus"
import { ArrowDown, User, Key, SwitchButton } from "@element-plus/icons-vue"
import { useProjectStore } from "@/store/project"
import ProjectListDialog from "@/components/dialog/ProjectListDialog.vue";
import exitIcon from "@/assets/icons/exit.png"
const userStore = useUserStore()
const router = useRouter()
const { t } = useI18n()
const nickName = computed(() => userStore.userInfo.nickName || "User")
// 退出
import openIcon from "@/assets/icons/open.png" // 打开文件
import saveFileIcon from "@/assets/icons/save.png" // 保存文件
import saveProjectIcon from "@/assets/icons/saveProject.png" // 保存项目
import editIcon from "@/assets/icons/edit.png" // 编辑
import importProIcon from "@/assets/icons/importPro.png" // 导入
import tutorialIcon from "@/assets/icons/tutorial.png" // 配置
import copyIcon from "@/assets/icons/copy.png" // 复制
import cutIcon from "@/assets/icons/cut.png" // 剪切
import pasteIcon from "@/assets/icons/paste.png" // 粘贴
import importProjectIcon from "@/assets/icons/importProject.png" // 导入项目
import importExportIcon from "@/assets/icons/import.png" // 导入导出
import importFMUIcon from "@/assets/icons/importfmu.png" // 导入FMU
import importCADIcon from "@/assets/icons/importCAD.png" // 导入CAD
import exportXMLIcon from "@/assets/icons/exportXML.png" // 导出XML
import exportFMUIcon from "@/assets/icons/exportFMU.png" // 导出FMU
import unitManagementIcon from "@/assets/icons/unit.png" // 单位管理
import perferenceIcon from "@/assets/icons/perference.png" // 偏好设置
import systemSettingsIcon from "@/assets/icons/system.png" // 系统设置
import toolIcon from "@/assets/icons/tool.png" // 工具
import undoIcon from "@/assets/icons/withDrawing.png" // 撤销
import redoIcon from "@/assets/icons/redo.png" // 重做
import configIcon from "@/assets/icons/tutorial.png" // 配置
import navigationIcon from "@/assets/icons/navigation.png" // 导航
import parameterAssistantIcon from "@/assets/icons/parameterAssistant.png" // 参数助手
import helpIcon from "@/assets/icons/help.png" // 帮助
import user from "@/assets/img/user.png" // 用户头像
const emit = defineEmits(["button-click"])
const showSecondContent = ref(false)
const projectStore = useProjectStore()

onMounted(() => {
  getprojectlist()
})

const fakeTabs = [
  {
    name: "exit",
    label: t("buttons.exit"),
    type: "",
    icon: exitIcon,
    onClick: () => {
      handleExit()
    }
  },
  {
    name: "open",
    label: t("buttons.open"),
    type: "",
    icon: openIcon,
    onClick: () => {
      dialog.value.projectListDialog = true;
    }
  },
  {
    name: "save",
    label: t("buttons.save"),
    type: "",
    icon: saveProjectIcon,
    onClick: () => {
      handleSaveProject()
    }
  }
]

const fakeTabs2 = [
  {
    name: "help",
    label: t("tabs.help"),
    type: "",
    icon: helpIcon,
    onClick: () => {
      console.log("点击了 帮助")
    }
  }
]

const tabs = [
  {
    name: "edit",
    label: t("tabs.edit"),
    icon: editIcon,
    buttons: [
      { action: "cut", label: t("buttons.cut"), icon: cutIcon },
      { action: "copy", label: t("buttons.copy"), icon: copyIcon },
      { action: "paste", label: t("buttons.paste"), icon: pasteIcon },
      { action: "undo", label: t("buttons.undo"), icon: undoIcon },
      { action: "redo", label: t("buttons.redo"), icon: redoIcon }
    ]
  },
  {
    name: "import-export",
    label: t("tabs.importExport"),
    icon: importExportIcon,
    buttons: [
      {
        action: "importProject",
        label: t("buttons.importProject"),
        icon: importProjectIcon
      },
      {
        action: "importFMU",
        label: t("buttons.importFMU"),
        icon: importFMUIcon
      },
      {
        action: "importCAD",
        label: t("buttons.importCAD"),
        icon: importCADIcon
      },
      {
        action: "exportXML",
        label: t("buttons.exportXML"),
        icon: exportXMLIcon
      },
      {
        action: "exportFMU",
        label: t("buttons.exportFMU"),
        icon: exportFMUIcon
      }
    ]
  },
  {
    name: "config",
    label: t("tabs.config"),
    icon: configIcon,
    buttons: [
      {
        action: "unitManagement",
        label: t("buttons.unitManagement"),
        icon: unitManagementIcon
      },
      {
        action: "preference",
        label: t("buttons.preference"),
        icon: perferenceIcon
      }
    ]
  },
  {
    name: "tools",
    label: t("tabs.tools"),
    icon: toolIcon,
    buttons: [
      { action: "wizard", label: t("buttons.wizard"), icon: navigationIcon },
      {
        action: "parameterAssisant",
        label: t("buttons.parameterAssistant"),
        icon: parameterAssistantIcon
      }
    ]
  }
]

const activeTab = ref(tabs[0].name)

// 弹窗开关
let dialog = ref({
  userinfoDialog: false,
  changePassword: false,
  projectListDialog: false
})

// 分页
let gd = ref({
  total: 1,
  currentPage4: 1,
  pageSize4: 5,
  searchtag: ""
})

let projectlists = ref([])
let selectedRows = ref([])

let pwd = ref({
  oldPassword: "",
  newPassword: "",
  confirmNewPassword: ""
})

const handleProfile = () => {
  dialog.value.userinfoDialog = true
}

const handleChangePassword = () => {
  dialog.value.changePassword = true
  pwd.value.oldPassword = ""
  pwd.value.newPassword = ""
  pwd.value.confirmNewPassword = ""
}

const handleLogout = () => {
  userStore.clearUserInfo()
  removeToken()
  removeUserId()
  ElMessage.success(t("message.logoutSuccess"))
  router.push("/login")
}

const emitButtonClick = (action) => {
  emit("button-click", action)
}

const handleTabClick = (tab) => {
  console.log("Tab switched to:", tab.name)
}
// 退出项目
const handleExit = () => {
  router.push("/project")
}

// 打开项目
const handleOpenProject = () => {
  dialog.value.projectListDialog = true
  getprojectlist()
}

// 保存项目
const handleSaveProject = () => {
  emit("button-click", "save");
}

// 获取项目列表
const getprojectlist = () => {
  const params = {
    transCode: "ES0001",
    count: gd.value.pageSize4,
    page: gd.value.currentPage4,
    searchtag: gd.value.searchtag
  }
  request(params)
    .then((res) => {
      gd.value.total = res.total
      projectlists.value = res.rows.map((item) => ({
        ...item,
        updateTime: item.updateTime.split(" +")[0]
      }))
    })
    .catch((err) => {
      console.error(err)
      ElMessage.error(err.returnMsg)
    })
}

// 处理行点击事件
const handleRowClick = (row) => {
  const index = selectedRows.value.findIndex((item) => item.pid === row.pid)
  if (index === -1) {
    selectedRows.value = [row] // 单选模式，只保留一个选中项
    // selectedRows.value.push(row); // 如果是多选模式，使用 push
  } else {
    selectedRows.value.splice(index, 1) // 如果已选中，则取消选中
  }
}

// 为行添加类名
const tableRowClassName = ({ row }) => {
  return selectedRows.value.some((item) => item.pid === row.pid)
    ? "selected-row"
    : ""
}

// 处理分页变化
const handleSizeChange = (newSize) => {
  gd.value.pageSize4 = newSize
  gd.value.currentPage4 = 1
  getprojectlist()
}

// 获取项目
const handleCurrentChange2 = (val) => {
  getprojectlist()
}

// 确认选中行
const confirmSelected = () => {
  if (selectedRows.value.length !== 1) {
    ElMessage.warning("请选择一个项目！")
    return
  }

  const selected = selectedRows.value[0]

  const project = {
    projectId: selected.pid,
    projectName: selected.name || `Project ${projectStore.projects.length + 1}`,
    keywords: selected.keywords || "",
    remark: selected.remark || "",
    flow: selected.flow ? selected.flow : { nodes: [], edges: [] }
  }

  // 如果项目已存在，更新信息；否则添加新项目
  if (projectStore.projects.some((p) => p.projectId === selected.pid)) {
    projectStore.updateProjectInfo(selected.pid, project)
  } else {
    projectStore.addProject(project)
  }

  // 设置激活项目
  projectStore.setActiveProject(selected.pid)

  // 跳转到首页
  router.push({ path: "/home" })
  dialog.value.projectListDialog = false
}

// 处理项目选择确认
const handleProjectConfirm = (project) => {
  router.push({ path: "/home" });
  dialog.value.projectListDialog = false;
};

const handleFlowImported = (newFlow) => {
  // 这里可以调用 VueFlow 的刷新方法
  // 或者直接重新加载当前项目
  // 例如：重新调用 flowInit() 或其他刷新方法
  console.log('Flow imported, need to refresh VueFlow', newFlow);
  
  // 如果你有访问 vueflow.vue 组件的方法，可以调用它的刷新方法
  // 例如：vueFlowRef.value.flowInit();
}
</script>

<style scoped>
.header-button-bar {
  position: relative; /* 作为绝对定位的参照 */
  display: flex;
  align-items: center;
  width: 100%;
  background: #ffffff;
  margin: -1px 0 -3px -1px;
}

:deep(.el-tabs) {
  width: 100%;
}

:deep(.el-tabs__nav-wrap) {
  width: 100%;
  position: relative; /* 备用定位参照 */
}

:deep(.el-tabs__nav) {
  display: flex;
  gap: 4px;
  width: calc(100% - 100px); /* 为 #tab-user 预留空间 */
}

:deep(#tab-user) {
  position: absolute;
  right: -70px; /* 紧贴右边缘 */
  top: 50%; /* 垂直居中 */
  transform: translateY(-50%); /* 调整垂直位置 */
  padding: 0;
  display: flex;
  align-items: center;
  background-color: #edf2fa;
  border: none;
}

.custom-tab-nav {
  display: flex;
  align-items: center;
  gap: 8px;
}

.left-buttons {
  display: flex;
  gap: 8px;
}

.tab-like-button {
  padding: 8px 16px;
  font-size: 14px;
  border: none;
  background: #fff;
  transition: all 0.3s;
}

.tab-like-button:hover {
  background-color: #f0f0f0;
  color: #075679;
}

.tabs-nav {
  flex: 1;
}

.button-group {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  padding: 6px;
  border: 1px solid #d0cdcd;
  border-radius: 5px;
}

.button-group .el-button {
  min-width: 60px;
  padding: 4px 8px;
  font-size: 14px;
  border: none;
  transition: all 0.3s;
}

.button-group .el-button:hover {
  background-color: #f0f0f0;
  color: #075679;
}

:deep(.el-tabs__header) {
  margin: 0;
  border-bottom: 1px solid #e4e7ed;
  background-color: #edf2fa;
}

:deep(.el-tabs__content) {
  padding: 0;
  background: #ffffff;
}

.icon-only-button {
  padding: 0;
  min-width: 32px;
  height: 39px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #edf2fa;
  border: none;
}

:deep(.el-tabs--border-card > .el-tabs__header .el-tabs__item.is-active) {
  border-top: none;
}

.icon-text-button {
  display: flex;
  align-items: center;
  gap: 4px;
}

.button-icon {
  width: 16px;
  height: 16px;
}

.tab-label {
  display: flex;
  align-items: center;
  gap: 4px;
}

.tab-icon {
  width: 16px;
  height: 16px;
}

:deep(#tab-exit) {
  padding: 0 !important;
}

:deep(#tab-open) {
  padding: 0 !important;
}

:deep(#tab-save) {
  padding: 0 !important;
}

:deep(#tab-help) {
  padding: 0 !important;
}

.open-page-header-icons {
  width: 150px;
  display: flex;
  align-items: center;
  justify-content: space-around;
}

.open-page-header-icons .el-button {
  padding: 0;
  border: none;
  margin: 0;
}

.user-dropdown-trigger {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.nickname {
  margin-left: 6px;
}

.userinfo-header {
  display: flex;
  align-items: center;
  justify-content: center;
}

.userinfo-footer {
  display: flex;
  justify-content: center;
}

/* 选中行的样式 */
:deep(.el-table .selected-row) {
  background-color: #f3f8fb !important;
  position: relative;
}

:deep(.el-table .selected-row td:first-child) {
  border-left: 4px solid #12739e !important;
}

:deep(.el-table .selected-row td) {
  border-top: 1px solid #12739e !important;
  /* border-right: 1px solid #12739E !important; */
  border-bottom: 1px solid #12739e !important;
}

:deep(.el-table .selected-row td:last-child) {
  border-right: 1px solid #12739e !important;
}
</style>