<template>
    <!-- 设备选择弹层 -->
    <TableSelectorDialog
        ref="TableSelectorDialogRef"
        :defaultTreeExpandLevel="1"
        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="sensorName"
        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 { bridgeTree } from '@/api/bridgeMonitoring/bridgeCommon'
import { tableData as tableDataQuery } from '@/api/bridgeMonitoring/MonitorConfigure/DeviceManage'

const attrs = useAttrs()
const props = defineProps({
    isShow: {
        default: false,
        type: Boolean
    },
    selectedContent: {
        type: Array,
        default: () => []
    },
    // 默认查询未完成审批的设备
    isFinishApprove: {
        type: Boolean,
        default: false
    }
})

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

// 状态定义
const TableSelectorDialogRef = ref(null)
const treeData = ref([])
const optionList = ref([
    {
        title: '设备名称',
        prop: 'sensorName',
        type: 'input',
        default: true
    },
    {
        title: '设备编码',
        prop: 'sensorCode',
        type: 'input'
    }
])
const tableOptions = ref([
    { label: '设备名称', minWidth: '120', prop: 'sensorName' },
    { label: '设备编码', minWidth: '120', prop: 'sensorCode' },
    {
        label: '规格型号',
        minWidth: '120',
        prop: 'sensorModel',
        formatter: ({ sensorModel }: { sensorModel: string }) => {
            return sensorModel || '-'
        }
    },
    {
        label: '设备类型',
        minWidth: '120',
        prop: 'sensorType',
        formatter: ({ sensorType }: { sensorType: string }) => {
            return sensorType || '-'
        }
    }
])
const params = ref({
    pageBean: { pageSize: 20, page: 1, total: 0 },
    querys: [
        { operation: 'IN', property: 's.bridge_id_' },
        { operation: 'LIKE', property: 's.sensor_name_' },
        { operation: 'LIKE', property: 's.sensor_code_' },
        { operation: 'NOT_EQUAL', property: 's.status_', value: 4 }
    ],
    sorter: []
})
const tableData = ref([])
const treeItem = ref({})
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] || {}
    setQueryValue(params.value, 's.bridge_id_', '')
}

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

async function getOrgTreeData() {
    try {
        const value = await bridgeTree() // 调用 API 获取树形数据
        const originTreeData = transformTreeData(value)
        treeData.value = originTreeData
        treeInit()
    } finally {
    }
}

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

// 所有桥梁编码
const bridgeIdAll = ref<string[]>([])

const transformTreeData = (data: any, path = '') => {
    return data.map((item: any) => {
        const { id, grade, name, children, bridgeInfos, bridgeId } = item
        const path_ = path ? path + ',' + id : id
        const treeNode = {
            id,
            name,
            grade,
            path_,
            bridgeId,
            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; bridgeShortName: string }) => {
                    const { id, bridgeName, bridgeShortName } = bridgeInfo
                    id ? bridgeIdAll.value.push(id) : null
                    return {
                        id,
                        name: bridgeName,
                        grade: 6,
                        bridgeId: id,
                        bridgeShortName
                    }
                }
            )
        }

        treeNode.children === null ? delete treeNode.children : null

        return treeNode
    })
}

const getTableData = async () => {
    try {
        tableLoading.value = true
        if (props.isFinishApprove) {
            setQueryValue(params.value, 'status', 4, 'EQUAL')
        } else {
            setQueryValue(params.value, 'status', 4, 'NOT_EQUAL')
        }
        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) return
    treeItem.value = nodeItem || ({} as TreeNode)

    if (nodeItem.bridgeId) {
        treeItem.value = nodeItem || ({} as TreeNode)
        setQueryValue(params.value, 's.bridge_id_', nodeItem.bridgeId, 'EQUAL')
    } else {
        const bridgeId = getChildrenBridgeId(nodeItem, [])
        bridgeId.push(nodeItem.id)
        setQueryValue(params.value, 's.bridge_id_', bridgeId, 'IN')
    }
    getTableData()
}
/**
 * 获取当前节点及其子节点的桥梁编码
 * @param node 节点
 * @param bridgeIds 桥梁编码数组
 * @return bridgeIds 所有桥梁编码
 */
function getChildrenBridgeId(node: any, bridgeIds: string[] = []): string[] {
    if (node.bridgeId) {
        bridgeIds.push(node.bridgeId)
    }

    if (node.children?.length) {
        node.children.forEach((child: any) => {
            getChildrenBridgeId(child, bridgeIds)
        })
    }

    return bridgeIds
}
</script>

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