<template>
  <!-- Tabs 切换 Web/APP -->
  <ContentWrap>
    <el-tabs v-model="activeClientType" @tab-change="handleClientTypeChange">
      <el-tab-pane :label="t('SystemManagement.Menu.clientTypeWeb')" :name="1" />
      <el-tab-pane :label="t('SystemManagement.Menu.clientTypeApp')" :name="2" />
    </el-tabs>
  </ContentWrap>

  <!-- 搜索工作栏 -->
  <ContentWrap>
    <el-form
      ref="queryFormRef"
      :inline="true"
      :model="queryParams"
      class="-mb-15px system-menu-query-form"
      label-width="auto"
    >
      <el-form-item :label="t('SystemManagement.Menu.name')" prop="name">
        <el-input
          v-model="queryParams.name"
          class="!w-240px"
          clearable
          :placeholder="t('SystemManagement.Menu.searchNamePlaceholder')"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item :label="t('SystemManagement.Menu.status')" prop="status">
        <el-select
          v-model="queryParams.status"
          class="!w-240px"
          clearable
          :placeholder="t('SystemManagement.Menu.searchStatusPlaceholder')"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon class="mr-5px" icon="ep:search" />
          {{ t('common.query') }}
        </el-button>
        <el-button @click="resetQuery">
          <Icon class="mr-5px" icon="ep:refresh" />
          {{ t('common.reset') }}
        </el-button>
        <el-button
          v-hasPermi="['system:menu:create']"
          plain
          type="primary"
          @click="openForm('create')"
        >
          <Icon class="mr-5px" icon="ep:plus" />
          {{ t('action.add') }}
        </el-button>
        <el-button plain type="danger" @click="toggleExpandAll">
          <Icon class="mr-5px" icon="ep:sort" />
          {{ t('SystemManagement.Menu.toggleExpand') }}
        </el-button>
        <el-button plain @click="refreshMenu">
          <Icon class="mr-5px" icon="ep:refresh" />
          {{ t('SystemManagement.Menu.refreshCache') }}
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
      v-if="refreshTable"
      v-loading="loading"
      :data="list"
      :default-expand-all="isExpandAll"
      row-key="id"
    >
      <el-table-column :show-overflow-tooltip="true" :label="t('SystemManagement.Menu.name')" prop="name" width="200"  sortable />
      <el-table-column :show-overflow-tooltip="true" :label="t('SystemManagement.Menu.enName')" prop="enName" width="220"  sortable />
      <el-table-column align="center" :label="t('SystemManagement.Menu.icon')" prop="icon" width="100">
        <template #default="scope">
          <Icon v-if="activeClientType === 1" :icon="scope.row.icon" />
          <span v-else>{{ scope.row.icon }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="t('SystemManagement.Menu.sort')" prop="sort" width="80" />
      <el-table-column
        v-if="activeClientType === 2"
        :label="t('SystemManagement.Menu.terminalType')"
        prop="terminalType"
        width="120"
      >
        <template #default="scope">
          {{ getTerminalTypeLabel(scope.row.terminalType) }}
        </template>
      </el-table-column>
      <el-table-column :show-overflow-tooltip="true" :label="t('SystemManagement.Menu.permission')" prop="permission" />
      <el-table-column :show-overflow-tooltip="true" :label="t('SystemManagement.Menu.component')" prop="component" />
      <el-table-column :show-overflow-tooltip="true" :label="t('SystemManagement.Menu.componentName')" prop="componentName"  sortable />
      <el-table-column :label="t('SystemManagement.Menu.status')" prop="status" sortable width="80">
        <template #default="scope">
          <el-switch
            class="ml-4px"
            v-model="scope.row.status"
            v-hasPermi="['system:menu:update']"
            :active-value="CommonStatusEnum.ENABLE"
            :inactive-value="CommonStatusEnum.DISABLE"
            :loading="menuStatusUpdating[scope.row.id]"
            @change="(val) => handleStatusChanged(scope.row, val as number)"
          />
        </template>
      </el-table-column>
      <el-table-column align="center" :label="t('SystemManagement.Menu.actions')">
        <template #default="scope">
          <el-button
            v-hasPermi="['system:menu:update']"
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
          >
            {{ t('action.edit') }}
          </el-button>
          <el-button
            v-hasPermi="['system:menu:create']"
            link
            type="primary"
            @click="openForm('create', undefined, scope.row.id)"
          >
            {{ t('action.add') }}
          </el-button>
          <el-button
            v-hasPermi="['system:menu:delete']"
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
          >
            {{ t('action.delete') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <MenuForm ref="formRef" @success="getList" />
</template>
<script lang="ts" setup>
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { handleTree } from '@/utils/tree'
import * as MenuApi from '@/api/system/menu'
import { MenuVO } from '@/api/system/menu'
import MenuForm from './MenuForm.vue'
import { CACHE_KEY, useCache } from '@/hooks/web/useCache'
import { CommonStatusEnum } from '@/utils/constants'

defineOptions({ name: 'SystemMenu' })

const { wsCache } = useCache()
const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const loading = ref(true) // 列表的加载中
const list = ref<any>([]) // 列表的数据
const activeClientType = ref(1) // 客户端类型：1=Web，2=APP
const queryParams = reactive({
  name: undefined,
  status: undefined,
  clientType: 1
})
const queryFormRef = ref() // 搜索的表单
const isExpandAll = ref(false) // 是否展开，默认全部折叠
const refreshTable = ref(true) // 重新渲染表格状态

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await MenuApi.getMenuList(queryParams)
    list.value = handleTree(data)
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  getList()
}

/** 切换客户端类型 */
const handleClientTypeChange = (val: number | string) => {
  queryParams.clientType = val as number
  getList()
}

const getTerminalTypeLabel = (value?: number) => {
  if (Number(value) === 2) return t('SystemManagement.Menu.terminalTypeScanner')
  return t('SystemManagement.Menu.terminalTypeMobile')
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number, parentId?: number) => {
  formRef.value.open(type, id, parentId, activeClientType.value)
}

/** 展开/折叠操作 */
const toggleExpandAll = () => {
  refreshTable.value = false
  isExpandAll.value = !isExpandAll.value
  nextTick(() => {
    refreshTable.value = true
  })
}

/** 刷新菜单缓存按钮操作 */
const refreshMenu = async () => {
  try {
    await message.confirm(t('SystemManagement.Menu.updateCacheConfirm'), t('SystemManagement.Menu.updateCacheTitle'))
    // 清空，从而触发刷新
    wsCache.delete(CACHE_KEY.USER)
    wsCache.delete(CACHE_KEY.ROLE_ROUTERS)
    // 刷新浏览器
    location.reload()
  } catch {}
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await MenuApi.deleteMenu(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 开启/关闭菜单的状态 */
const menuStatusUpdating = ref({}) // 菜单状态更新中的 menu 映射。key：菜单编号，value：是否更新中
const handleStatusChanged = async (menu: MenuVO, val: number) => {
  // 1. 标记 menu.id 更新中
  menuStatusUpdating.value[menu.id] = true
  try {
    // 2. 发起更新状态
    menu.status = val
    await MenuApi.updateMenu(menu)
  } finally {
    // 3. 标记 menu.id 更新完成
    menuStatusUpdating.value[menu.id] = false
  }
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>
