<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="fullname"
        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 { getOrgUserPage 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: 'fullname', type: 'input', default: true },
    { title: '账号', prop: 'account', type: 'input' },
    { title: '电话', prop: 'mobile', type: 'input' }
])
const tableOptions = ref([
    { label: '名称', minWidth: '100', prop: 'fullname' },
    { label: '账号', minWidth: '100', prop: 'account' },
    { label: '电话', minWidth: '80', prop: 'mobile' },
    { label: '性别', minWidth: '60', prop: 'sex' }
])
const params = ref({
    pageBean: { pageSize: 20, page: 1, total: 0 },
    querys: [
        { group: 'orgTree', operation: 'IN', property: 'ORG_ID_', value: '' },
        {
            group: 'quick',
            operation: 'LIKE',
            property: 'fullname',
            relation: 'OR',
            value: ''
        },
        {
            group: 'quick',
            operation: 'LIKE',
            property: 'account',
            relation: 'OR',
            value: ''
        },
        {
            group: 'quick',
            operation: 'LIKE',
            property: 'mobile',
            relation: 'OR',
            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, 'ORG_ID_', '')
}

/**
 * 树形组件相关
 */
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
    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, 'ORG_ID_', nodeItem.id || '')
    getTableData()
}
</script>

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