<template>

  <GiPageLayout>
    <div>
      <a-radio-group v-model="viewType" type="button" size="small" style="margin-bottom: 16px;">
        <a-radio value="table">表格视图</a-radio>
        <a-radio value="tree">组织架构图</a-radio>
      </a-radio-group>
    </div>
    <GiTable
      v-show="viewType === 'table'"
      ref="tableRef"
      row-key="deptId"
      :data="dataList"
      :columns="columns"
      :loading="loading"
      :scroll="{ x: '100%', y: '100%', minWidth: 1000 }"
      :pagination="false"
      :disabled-column-keys="['name']"
      :expanded-keys="expandedKeys"
      @expand="onExpand"
      @refresh="search"
    >
      <template #expand-icon="{ expanded }">
        <IconDown v-if="expanded" />
        <IconRight v-else />
      </template>
      <template #toolbar-left>
        <a-input v-model="name" placeholder="搜索名称" allow-clear>
          <template #prefix><icon-search /></template>
        </a-input>
        <a-button @click="reset">
          <template #icon><icon-refresh /></template>
          <template #default>重置</template>
        </a-button>
      </template>
      <template #toolbar-right>
        <a-button v-permission="['system:dept:create']" type="primary" @click="onAdd()">
          <template #icon><icon-plus /></template>
          <template #default>新增</template>
        </a-button>
        <a-button v-permission="['system:dept:export']" @click="onExport">
          <template #icon><icon-download /></template>
          <template #default>导出</template>
        </a-button>
      </template>
      <template #status="{ record }">
        <GiCellStatus :status="Number(record.status) as 1 | 2" />
      </template>
      <template #action="{ record }">
        <a-space>
          <a-link v-permission="['system:dept:update']" title="修改" @click="onUpdate(record)">修改</a-link>
          <a-link
            v-permission="['system:dept:delete']"
            :disabled="record.children && record.children.length > 0"
            status="danger"
            title="删除"
            @click="onDelete(record)"
          >
            删除
          </a-link>
          <a-link v-permission="['system:dept:create']" title="新增" @click="onAdd(record.deptId)">新增</a-link>
        </a-space>
      </template>
    </GiTable>
    <!-- 组织架构图视图 -->
    <div v-show="viewType === 'tree'">
      <a-card>
        <a-dropdown trigger="contextMenu">
          <Vue3TreeOrg
            v-if="dataList.length"
            :data="dataList[0]"
            :collapsable="true"
            :horizontal="false"
            :define-menus="menus"
            :default-expand-level="999"
            :props="{ id: 'deptId', parentId: 'parentId', label: 'deptName', children: 'children' }"
            center
            :node-add="handleAdd"
            :node-delete="onDelete"
            :node-edit="onUpdate"
            :expanded-keys="nodeExpandedKeys"
            @node-click="(node) => toggleExpand(node.deptId)"
          >
          </Vue3TreeOrg>
        </a-dropdown>
      </a-card>
    </div>
    <DeptAddModal ref="DeptAddModalRef" :depts="dataList" @save-success="search" />
  </GiPageLayout>
</template>

<script setup lang="ts">
import 'vue3-tree-org/lib/vue3-tree-org.css'
import { Vue3TreeOrg } from 'vue3-tree-org'
import type { TableInstance } from '@arco-design/web-vue'
import { Message } from '@arco-design/web-vue'
import DeptAddModal from './DeptAddModal.vue'
import { type DeptQuery, type DeptResp, deleteDept, getDeptTree } from '@/apis/system/dept'
import type GiTable from '@/components/GiTable/index.vue'
import { useDownload, useTable } from '@/hooks'
import { isMobile } from '@/utils'
import has from '@/utils/has'

const $message = Message

defineOptions({ name: 'SystemDept' })

const queryForm = reactive<DeptQuery>({})
const tableRef = ref<InstanceType<typeof GiTable>>()
const {
  tableData,
  loading,
  search,
  handleDelete,
} = useTable<DeptResp>(() => getDeptTree(queryForm), {
  immediate: true,
  onSuccess: () => {
    if (isFirstLoad.value) {
      // 初始全部展开：递归收集所有节点 id
      const collectKeys = (nodes: DeptResp[]): string[] => {
        let keys: string[] = []
        nodes.forEach(node => {
          keys.push(node.deptId)
          if (node.children && node.children.length) {
            keys = keys.concat(collectKeys(node.children))
          }
        })
        return keys
      }
      expandedKeys.value = collectKeys(tableData.value)
      isFirstLoad.value = false
    }
  },
})
// 查看视图类型
const viewType = ref('table')
// 组织架构图右键菜单
const menus = [
  { name: '添加部门', command: 'add' },
  { name: '编辑部门', command: 'edit' },
  { name: '删除部门', command: 'delete' },
]
// 所有节点展开状态
// 表格视图展开的节点
const expandedKeys = ref<string[]>([])
const isFirstLoad = ref(true)
// 过滤树
const searchData = (name: string) => {
  const loop = (data: DeptResp[]) => {
    const result = [] as DeptResp[]
    data.forEach((item: DeptResp) => {
      if (item.deptName?.toLowerCase().includes(name.toLowerCase())) {
        result.push({ ...item })
      } else if (item.children) {
        const filterData = loop(item.children)
        if (filterData.length) {
          result.push({
            ...item,
            children: filterData,
          })
        }
      }
    })
    return result
  }
  return loop(tableData.value)
}

const name = ref('')
const dataList = computed(() => {
  if (!name.value) return tableData.value
  return searchData(name.value)
})

const columns: TableInstance['columns'] = [
  { title: '名称', dataIndex: 'deptName', minWidth: 170, ellipsis: true, tooltip: true },
  { title: '状态', dataIndex: 'status', slotName: 'status', align: 'center' },
  { title: '排序', dataIndex: 'orderNum', align: 'center', show: false },
  { title: '负责人ID', dataIndex: 'leaderId', ellipsis: true, tooltip: true, show: false },
  { title: '父级部门ID', dataIndex: 'parentId', ellipsis: true, tooltip: true, show: false },
  { title: '创建人', dataIndex: 'createUserString', ellipsis: true, tooltip: true, show: false },
  { title: '创建时间', dataIndex: 'createTime', width: 180 },
  { title: '修改人', dataIndex: 'updateUserString', ellipsis: true, tooltip: true, show: false },
  { title: '修改时间', dataIndex: 'updateTime', width: 180, show: false },
  {
    title: '操作',
    dataIndex: 'action',
    slotName: 'action',
    width: 160,
    align: 'center',
    fixed: !isMobile() ? 'right' : undefined,
    show: has.hasPermOr(['system:dept:update', 'system:dept:delete', 'system:dept:create']),
  },
]

// 重置
const reset = () => {
  name.value = ''
}

// 删除
const onDelete = (record: DeptResp) => {
  // 检查是否存在子节点
  if (record.children && record.children.length > 0) {
    // 如果有子节点，显示提示信息
    $message.warning('该部门存在子部门，无法直接删除')
    return Promise.reject()
  }
  
  return handleDelete(() => deleteDept(record.deptId), {
    content: `是否确定删除部门「${record.deptName}」？`,
    showModal: true,
  })
}

// 导出
const onExport = () => {
  // useDownload(() => exportDept(queryForm))
  // 注释导出功能，因为新API中没有导出接口
}

const DeptAddModalRef = ref<InstanceType<typeof DeptAddModal>>()
// 新增
const onAdd = (parentId?: string) => {
  DeptAddModalRef.value?.onAdd(parentId)
}
const handleAdd = (record: DeptResp) => {
  onAdd(record.deptId)
}
// 修改
const onUpdate = (record: DeptResp) => {
  DeptAddModalRef.value?.onUpdate(record.deptId)
}

const onExpand = (expanded: boolean, record: DeptResp) => {
  const key = record.deptId
  if (expanded) {
    if (!expandedKeys.value.includes(key)) {
      expandedKeys.value.push(key)
    }
  } else {
    expandedKeys.value = expandedKeys.value.filter(k => k !== key)
  }
}

// 添加一个方法来切换所有节点的展开/收缩状态
const toggleExpandAll = () => {
  nodeExpandAll.value = !nodeExpandAll.value
}

// 修改: 添加响应式展开状态和切换方法
const nodeExpandedKeys = ref<string[]>([])
const toggleExpand = (deptId: string) => {
  const index = nodeExpandedKeys.value.indexOf(deptId)
  index > -1 
    ? nodeExpandedKeys.value.splice(index, 1)
    : nodeExpandedKeys.value.push(deptId)
}
</script>

<style scoped lang="scss">
:deep(.zm-draggable) {
  margin-top: 4px;
}

:deep(.zm-tree-org .zoom-container) {
  background-color: var(--color-bg-1);
  color: var(--color-text-1);
}

:deep(.tree-org-node__content) {
  background-color: var(--color-bg-2);
  color: var(--color-text-1);
  cursor: pointer;
  position: relative;
}

.zm-tree-org {
  background-color: var(--color-bg-1);
  height: calc(100vh - 265px);
}

:global(.zm-tree-contextmenu) {
  color: var(--color-text-1) !important;
  position: fixed !important;
  background: var(--color-bg-2) !important;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1) !important;
  border: 1px solid var(--color-border) !important;
  border-radius: 4px !important;
  padding: 4px 0 !important;
  min-width: 120px !important;
  z-index: 999 !important;

  ul {
    background: var(--color-bg-1) !important;
    list-style-type: none !important;
    padding: 10px !important;
    margin: 0 !important;
  }

  .zm-tree-menu-item {
    background-color: var(--color-bg-1) !important;
    padding: 5px 15px !important;
    margin-top: 10px !important;
    cursor: pointer !important;
    transition: background-color 0.1s ease !important;
    list-style: none !important;
  }
}
:deep(.tree-org-node__expand){
  background-color: var(--color-bg-1) !important;
}
</style>
