<template>
    <!-- 人员选择弹层 -->
    <TableSelectorDialog
        ref="TableSelectorDialogRef"
        v-model:isShow="isShowDialog"
        v-model:selected-content="selectedContentList"
        :defaultTreeExpandLevel="1"
        :search-option="optionList"
        :table-loading="tableLoading"
        :table-options="tableOptions"
        :tableData="tableData"
        :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 { computed, nextTick, ref, useAttrs } from 'vue'
import { refineRequestBody, setQueryValue } from '@/utils/requestWrappers'
import TableSelectorDialog from '@/components/TableSelectorDialog/index.vue'
import { orgTreeList } from '@/api/bridgeMonitoring/BridgeCommon.ts'
import { tableData as tableDataQuery } from '@/api/bridgeMonitoring/MonitorConfigure/SurveyPointManage'

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: '100', prop: 'mobile' },
    { label: '性别', minWidth: '100', prop: 'sex' }
])
const params = ref({
    pageBean: { pageSize: 20, page: 1, total: 0 },
    querys: [
        { operation: 'LIKE', property: 'fullname' },
        { operation: 'LIKE', property: 'account' },
        { operation: 'LIKE', property: 'mobile' }
    ],
    sorter: [{ direction: 'DESC', property: 'updateTime' }]
})
const tableData = ref([])
const treeItem = ref({})
const tableLoading = ref(false)
const orgPathAll = ref([])

// 直接使用 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] || {}
    setQueryValue(params.value, 'bridgeCode', '')
}

/**
 * 树形组件相关
 */
interface TreeNode {
    id: string
    name: string
    path_: string
    children: TreeNode[]

    [key: string]: any // 为了满足接口定义的其他属性[可选]
}

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

function treeInit() {
    treeItem.value = treeData.value[0] || ({} as TreeNode)
    // setQueryValue(params.value, 'orgCode', bridgeCodeAll.value, 'IN')
    nextTick(() => {
        TableSelectorDialogRef.value?.expandHandle(true, 2)
    })
    getTableData()
}

const bridgeCodeAll = ref<string[]>([])
// const transformTreeData = (data, path = '') => {
//     return data.map((item) => {
//         const { id, grade, name, children, bridgeInfos, bridgeCode } = item
//         orgPathAll.value.push(item.id)
//         const path_ = path ? path + ',' + id : id
//         const treeNode = {
//             id,
//             name,
//             grade,
//             path_,
//             bridgeCode,
//             children: children && children.length > 0 ? transformTreeData(children, path_) : null
//         }
//
//         if ((!children || children.length === 0) && bridgeInfos && bridgeInfos.length > 0) {
//             treeNode.children = bridgeInfos.map(
//                 (bridgeInfo: {
//                     id: string
//                     bridgeName: string
//                     bridgeCode: string
//                     bridgeShortName: string
//                 }) => {
//                     const { id, bridgeName, bridgeCode, bridgeShortName } = bridgeInfo
//                     bridgeCode ? bridgeCodeAll.value.push(bridgeCode) : null
//                     return {
//                         id,
//                         name: bridgeName,
//                         grade: 6,
//                         bridgeCode,
//                         bridgeShortName
//                     }
//                 }
//             )
//         }
//
//         treeNode.children === null ? delete treeNode.children : null
//
//         return treeNode
//     })
// }

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) => {
    if (nodeItem.id !== treeItem.value?.id && nodeItem.id) {
        treeItem.value = nodeItem || ({} as TreeNode)
        setQueryValue(params.value, 'orgCode', [nodeItem.id], 'IN')
    } else {
        treeItem.value = {} as TreeNode
        TableSelectorDialogRef.value?.setCurrentKey(null)
        setQueryValue(params.value, 'orgCode', bridgeCodeAll.value, 'IN')
    }
    getTableData()
}
</script>

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