<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="name"
        title="测点选择"
        v-bind="attrs"
        @closed="closed"
        @open="open"
        @tableRefresh="getTableData"
        @treeChange="treeChange"
    />
</template>

<script lang="ts" setup>
import { ref, computed, onMounted, nextTick, watch } from 'vue'
import { useAttrs } from 'vue'
import { refineRequestBody, setQueryValue } from '@/utils/requestWrappers'
import TableSelectorDialog from '@/components/TableSelectorDialog/index.vue'
// import moment from 'moment'
// import 'moment-duration-format'
import { dictionaryEscape, getDictionaryByCode } from '@/utils/dictionary'
import { bridgeTree } from '@/api/bridgeMonitoring/bridgeCommon'
import { tableData as tableDataQuery } from '@/api/bridgeMonitoring/MonitorConfigure/SurveyPointManage'

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: 'name',
        type: 'input',
        default: true
    },
    {
        title: '测点编码',
        prop: 'measurementCode',
        type: 'input'
    }
])
const tableOptions = ref([
    { label: '测点名称', minWidth: '120', prop: 'name' },
    { label: '测点编码', minWidth: '120', prop: 'measurementCode' }
])
const params = ref({
    pageBean: { pageSize: 20, page: 1, total: 0 },
    querys: [
        { operation: 'IN', property: 'bridgeId' },
        { operation: 'LIKE', property: 'name' },
        { operation: 'LIKE', property: 'measurementCode' },
        { operation: 'NOT_EQUAL', property: 'status', value: 4 }
    ],
    sorter: []
})
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, 'bridgeId', '')
}

/**
 * 树形组件相关
 */
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, 'bridgeId', 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) {
        setQueryValue(params.value, 'bridgeId', nodeItem.bridgeId, 'EQUAL')
    } else {
        const bridgeId = getChildrenBridgeId(nodeItem, [])
        bridgeId.push(nodeItem.id)
        setQueryValue(params.value, 'bridgeId', 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>
