<template>
  <div class="main-box">
    <TreeFilter title="组织架构" ref="treeRef" :request-api="OrgApi.tree" label="name" :default-value="initParam.orgId" @change="changeTree" />
    <div class="table-box">
      <ProTable
        ref="proTableRef"
        title="组织列表"
        row-key="roleId"
        :indent="20"
        :columns="columns"
        :init-param="initParam"
        :search-columns="searchColumns"
        :request-api="getTableList">
        <!-- 表格 header 按钮 -->
        <template #tableHeader="scope">
          <el-button type="primary" icon="CirclePlus" @click="openDrawer('新增')"> 新增组织 </el-button>
          <el-button type="danger" icon="Delete" plain :disabled="!scope.isSelected"> 批量删除 </el-button>
        </template>

        <template #operation="{ row }">
          <el-button type="primary" link icon="EditPen" @click="openDrawer('编辑', row)"> 编辑 </el-button>
          <el-button v-if="row.id !== 1" type="primary" link icon="Delete"> 删除 </el-button>
        </template>
      </ProTable>
    </div>
    <OrgDrawer ref="drawerRef" @submit="refreshTree" />
  </div>
</template>
<script lang="tsx" setup name="OrgManage">
import { RoleInfo, RoleQuery } from '@/api/interface/system/role'
import OrgApi from '@/api/module/system/org'
import OrgDrawer from './components/OrgDrawer.vue'
import TreeFilter from '@/components/TreeFilter/index.vue'
import { ColumnProps, ProTableInstance, SearchProps } from '@/components/ProTable/interface'
import { OrgFormBo } from '@/api/interface/system/org'
const initParam = reactive({ orgId: '', parentId: '' })

const selectTreeId = ref<string>('')
const proTableRef = ref<ProTableInstance>()
const treeRef = ref<InstanceType<typeof TreeFilter>>()

// 树形筛选切换
const changeTree = (val: string) => {
  if (val) {
    selectTreeId.value = val
    initParam.parentId = val
    proTableRef.value?.clearSelection()
  }
}

// 刷新树表
const refreshTree = () => {
  treeRef.value?.refresh()
}

// 表格配置项
const columns: ColumnProps<RoleInfo>[] = [
  { type: 'selection', width: 60 },
  { prop: 'name', label: '组织名称' },
  { prop: 'orderNum', label: '排序' },
  { prop: 'leader', label: '负责人' },
  { prop: 'remark', label: '备注' },
  { prop: 'createByName', label: '创建人' },
  { prop: 'createTime', label: '创建时间' },
  { prop: 'operation', label: '操作', width: 250, fixed: 'right' }
]

// 表格配置项
const searchColumns: SearchProps[] = [{ prop: 'name', label: '组织名称', el: 'input' }]

// 获取table列表
const getTableList = (params: RoleQuery) => OrgApi.page(params)

// 打开 drawer(新增、查看、编辑)
const drawerRef = ref<InstanceType<typeof OrgDrawer> | null>(null)
const openDrawer = (title: string, row: Partial<OrgFormBo> = {}) => {
  const params = {
    title,
    row: row ? { ...row } : { parentId: selectTreeId.value },
    isView: title === '查看',
    api: title === '新增' ? OrgApi.add : title === '编辑' ? OrgApi.edit : undefined,
    getTableList: proTableRef.value?.getTableList
  }
  drawerRef.value?.acceptParams(params)
}
</script>
