<template>
    <!-- 部门选择弹层 -->
    <TableSelectorDialog
        ref="TableSelectorDialogRef"
        :defaultTreeExpandLevel="0"
        v-model:isShow="isShowDialog"
        v-model:selected-content="selectedContentList"
        :search-option="optionList"
        :tableData="tableData"
        :table-loading="tableLoading"
        :table-options="tableOptions"
        :tableParams="params"
        :tree-item="treeItem"
        :treeData="treeData"
        :treeOptions="{ children: 'children', label: 'name' }"
        hintLanguage="提示：请在列表中选择部门后，点击确认。"
        select-title-name="已选部门"
        selectLabel="name"
        title="部门选择"
        v-bind="attrs"
        @closed="closed"
        @open="open"
        @tableRefresh="getTableData"
        @treeChange="treeChange"
    />
</template>

<script lang="ts" setup>
import { ref, computed, nextTick } from 'vue'
import { useAttrs } from 'vue'
import { refineRequestBody, setQueryValue } from '@/utils/requestWrappers'
import TableSelectorDialog from '@/components/TableSelectorDialog/index.vue'
import { getOrgPage as tableDataQuery, treeDataByDem } from '@/api/system/organization'

const attrs = useAttrs()
const props = defineProps({
    isShow: {
        default: false,
        type: Boolean
    },
    selectedContent: {
        type: Array,
        default: () => []
    }
})

const emit = defineEmits(['update:isShow', 'update:selectedContent'])

// 状态定义
const TableSelectorDialogRef = ref(null)
const treeData = ref([])
const optionList = ref([
    { title: '部门名称', prop: 'name', type: 'input', default: true },
    { title: '部门编码', prop: 'code', type: 'input', default: false }
])
const tableOptions = ref([
    { label: '部门名称', minWidth: '80', prop: 'name' },
    { label: '部门编码', minWidth: '60', prop: 'code' },
    { label: '组织路径', minWidth: '100', prop: 'pathName' }
])
const params = ref({
    pageBean: { pageSize: 20, page: 1, total: 0 },
    querys: [
        { operation: 'RIGHT_LIKE', property: 'path', value: '' },
        { operation: 'LIKE', property: 'name', value: '' },
        { operation: 'LIKE', property: 'code', value: '' }
    ],
    sorter: [{ direction: 'DESC', property: 'updateTime' }]
})
const tableData = ref([])
const treeItem = ref<TreeNode | null>(null)
const tableLoading = ref(false)

// 直接使用 props.isShow
const isShowDialog = computed({
    get: () => {
        return props.isShow
    },
    set: (val) => {
        emit('update:isShow', val)
    }
})

// 直接使用 props.selectedContent
const selectedContentList = computed({
    get: () => {
        return props.selectedContent
    },
    set: (val) => {
        emit('update:selectedContent', val)
    }
})

// 方法定义
const open = () => {
    getOrgTreeData()
}

const closed = () => {
    // 只做清理工作，不触发额外的事件
    treeItem.value = treeData.value[0] || null
    setQueryValue(params.value, 'path', '')
}

/**
 * 树形组件相关
 */
interface TreeNode {
    id: string
    name: string
    path: string
    grade: number
    children?: TreeNode[]
    [key: string]: any // 为了满足接口定义的其他属性[可选]
}

async function getOrgTreeData() {
    try {
        const value = (await treeDataByDem()) as any // 调用 API 获取树形数据
        treeData.value = value || []
        treeInit()
    } finally {
    }
}

function treeInit() {
    treeItem.value = treeData.value[0] || null
    setQueryValue(params.value, 'path', treeItem.value?.path || '', 'RIGHT_LIKE')
    nextTick(() => {
        TableSelectorDialogRef.value?.expandHandle(true, 1)
    })
    getTableData()
}

const getTableData = async () => {
    try {
        tableLoading.value = true
        const query = refineRequestBody(params.value)
        const { total = 0, rows = [] } = await tableDataQuery(query)
        params.value.pageBean.total = total
        tableData.value = rows
    } finally {
        tableLoading.value = false
    }
}

const treeChange = (nodeItem: TreeNode) => {
    setQueryValue(params.value, 'path', nodeItem.path || '', 'RIGHT_LIKE')
    getTableData()
}
</script>

<style lang="scss" scoped></style>
