<!-- 角色模板管理页面 -->
<template>
  <div class="role-template-page art-full-height">
    <!-- 搜索栏 -->
    <RoleTemplateSearch v-model="searchForm" @search="handleSearch" @reset="resetSearchParams" />

    <ElCard class="art-table-card" shadow="never">
      <ArtTableHeader v-model:columns="columnChecks" :loading="loading" @refresh="refreshData">
        <template #left>
          <ElButton type="primary" @click="showDialog('add')" v-ripple>
            <template #icon><ArtSvgIcon icon="ri:add-line" /></template>
            新增模板
          </ElButton>
          <ElButton type="success" @click="showInitDialog" v-ripple>
            <template #icon><ArtSvgIcon icon="ri:refresh-line" /></template>
            批量初始化
          </ElButton>
        </template>
      </ArtTableHeader>

      <!-- 表格 -->
      <ArtTable
        :loading="loading"
        :data="data"
        :columns="columns"
        :pagination="pagination"
        @pagination:size-change="handleSizeChange"
        @pagination:current-change="handleCurrentChange"
      >
        <template #status="{ row }">
          <ElTag :type="row.isActive ? 'success' : 'danger'">
            {{ row.isActive ? '启用' : '禁用' }}
          </ElTag>
        </template>
        <template #actions="{ row }">
          <div class="action-wrap">
            <button class="art-action-btn primary" type="button" @click="showDialog('edit', row)">
              <ArtSvgIcon icon="ri:edit-2-line" class="art-action-icon" />
              <span>编辑</span>
            </button>
            <button class="art-action-btn warning" type="button" @click="showPermissionDialog(row)">
              <ArtSvgIcon icon="ri:shield-keyhole-line" class="art-action-icon" />
              <span>权限</span>
            </button>
            <ElDropdown @command="(cmd) => handleRowCommand(row, cmd as RowAction)">
              <button class="art-action-btn info" type="button">
                <ArtSvgIcon icon="ri:more-2-line" class="art-action-icon" />
                <span>更多</span>
              </button>
              <template #dropdown>
                <ElDropdownMenu>
                  <ElDropdownItem command="clone">
                    <span class="dropdown-item">
                      <ArtSvgIcon icon="ri:file-copy-line" class="dropdown-icon" />
                      <span>克隆</span>
                    </span>
                  </ElDropdownItem>
                  <ElDropdownItem divided command="delete">
                    <span class="dropdown-item danger">
                      <ArtSvgIcon icon="ri:delete-bin-line" class="dropdown-icon" />
                      <span>删除</span>
                    </span>
                  </ElDropdownItem>
                </ElDropdownMenu>
              </template>
            </ElDropdown>
          </div>
        </template>
      </ArtTable>
    </ElCard>

    <!-- 角色模板编辑/克隆弹窗 -->
    <RoleTemplateDialog
      v-model="dialogVisible"
      :dialog-type="dialogType"
      :template-data="currentTemplateData"
      @success="refreshData"
    />

    <!-- 权限分配弹窗 -->
    <RoleTemplatePermissionDialog
      v-model="permissionDialogVisible"
      :template-data="currentTemplateData"
      @success="refreshData"
    />
  </div>
</template>

<script setup lang="ts">
  import { ref } from 'vue'
  import { useTable } from '@/hooks/core/useTable'
  import {
    fetchGetRoleTemplates,
    fetchDeleteRoleTemplate,
    fetchInitRoleTemplates
  } from '@/api/role-template'
  import RoleTemplateDialog from './modules/role-template-dialog.vue'
  import RoleTemplatePermissionDialog from './modules/role-template-permission-dialog.vue'
  import RoleTemplateSearch from './modules/role-template-search.vue'
  import ArtSvgIcon from '@/components/core/base/art-svg-icon/index.vue'
  import { ElMessageBox, ElMessage } from 'element-plus'

  defineOptions({ name: 'RoleTemplate' })

  type RoleTemplateDto = Api.RoleTemplate.RoleTemplateDto
  type RowAction = 'clone' | 'delete'

  // 搜索表单
  const searchForm = ref({
    keyword: ''
  })

  // 表格 Hook
  type RoleTemplateApiFn = (params: { current: number; size: number }) => Promise<{
    data: { list: RoleTemplateDto[]; total: number }
  }>

  const {
    loading,
    data,
    pagination,
    columns,
    columnChecks,
    refreshData,
    handleSizeChange,
    handleCurrentChange
  } = useTable<RoleTemplateApiFn, RoleTemplateDto>({
    core: {
      apiFn: async (params: { current: number; size: number }) => {
        const res = await fetchGetRoleTemplates({
          keyword: searchForm.value.keyword || undefined,
          Page: params.current,
          PageSize: params.size
        })

        // 兼容不同的返回格式
        let list: RoleTemplateDto[] = []
        let total = 0

        if ((res as any).items) {
          list = (res as any).items
          total = (res as any).totalCount || (res as any).items.length
        } else if (Array.isArray(res)) {
          list = res
          total = res.length
        }

        return {
          data: {
            list,
            total
          }
        }
      },
      immediate: true,
      columnsFactory: () => [
        { prop: 'templateCode', label: '模板编码', width: 150 },
        { prop: 'name', label: '模板名称', width: 150 },
        { prop: 'description', label: '描述', minWidth: 200 },
        { prop: 'isActive', label: '状态', width: 100, slotName: 'status', useSlot: true },
        {
          prop: 'actions',
          label: '操作',
          width: 260,
          fixed: 'right',
          slotName: 'actions',
          useSlot: true
        }
      ]
    }
  })

  // 搜索
  const handleSearch = () => {
    refreshData()
  }

  const resetSearchParams = () => {
    searchForm.value.keyword = ''
    refreshData()
  }

  // 弹窗控制
  const dialogVisible = ref(false)
  const permissionDialogVisible = ref(false)
  const dialogType = ref<'add' | 'edit' | 'clone'>('add')
  const currentTemplateData = ref<RoleTemplateDto | undefined>(undefined)

  const showDialog = (type: 'add' | 'edit' | 'clone', row?: RoleTemplateDto) => {
    dialogType.value = type
    currentTemplateData.value = row ? { ...row } : undefined
    dialogVisible.value = true
  }

  const showPermissionDialog = (row: RoleTemplateDto) => {
    currentTemplateData.value = { ...row }
    permissionDialogVisible.value = true
  }

  const handleRowCommand = (row: RoleTemplateDto, command: RowAction) => {
    if (command === 'clone') {
      showDialog('clone', row)
      return
    }

    if (command === 'delete') {
      handleDelete(row)
    }
  }

  // 删除
  const handleDelete = (row: RoleTemplateDto) => {
    ElMessageBox.confirm(`确认要删除模板 "${row.name}" 吗？`, '提示', {
      type: 'warning'
    }).then(async () => {
      try {
        await fetchDeleteRoleTemplate(row.templateCode)
        ElMessage.success('删除成功')
        refreshData()
      } catch (error) {
        console.error(error)
      }
    })
  }

  // 批量初始化
  const showInitDialog = () => {
    // 简单的确认框，后续可以做成选择模板的弹窗
    ElMessageBox.prompt('请输入要初始化的模板编码（多个用逗号分隔）', '批量初始化', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputPattern: /.+/,
      inputErrorMessage: '请输入模板编码'
    }).then(async ({ value }) => {
      try {
        const codes = value
          .split(',')
          .map((s) => s.trim())
          .filter((s) => s)
        await fetchInitRoleTemplates(codes)
        ElMessage.success('初始化请求已发送')
        refreshData()
      } catch (error) {
        console.error(error)
      }
    })
  }
</script>

<style scoped lang="scss">
  .search-card {
    padding: 18px 18px 0;
    margin-bottom: 12px;
  }

  .action-wrap {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    align-items: center;
  }

  .dropdown-item {
    display: inline-flex;
    gap: 8px;
    align-items: center;
  }

  .dropdown-item.danger {
    color: var(--el-color-danger);
  }

  .dropdown-icon {
    font-size: 16px;
  }
</style>
