<template>
    <div class="default-main">
        <div class="custom-table-header">
            <div>
                关键字筛选
                <el-input maxlength="32" show-word-limit class="ml10" v-model="searchValue" placeholder="请输入工程/项目名称"
                    clearable style="width: 200px" @input="inpChaange" />
            </div>
            <div style="margin-left: auto;">
                <el-button :icon="Plus" type="primary" @click="addRole">新增工程</el-button>
                <!-- <el-button type="primary" icon="el-icon-Plus" class="ml10" @click="add">新增项目</el-button> -->
            </div>
        </div>
        <Table ref="tableRef" :tree-config="{ childrenField: 'children', rowField: 'id' }"
            @current-change="currentChange">
            <template #columns>
                <vxe-column title="拓扑图" width="130">
                    <template #default="{ row }">
                        <template v-if="row.rowType === 'project'">
                            <el-image v-if="row.topologyInfo" :hide-on-click-modal="true" :preview-teleported="true"
                                :preview-src-list="[row.topologyImageUrl]" :src="row.topologyImageUrl" />
                            <span v-else>/</span>
                        </template>
                        <span v-else>/</span>
                    </template>
                </vxe-column>
                <vxe-column title="排序" field="sort" width="100"> </vxe-column>
            </template>
        </Table>
        <popup ref="popupRef" />
        <itemAdd ref="itemAddRef" />
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted, provide, nextTick } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import TableStore from '@/utils/tableStore'
import Table from '@/components/table/index.vue'
import { deleteProject, deleteEngineering } from '@/api/cs-device-boot/edData'
import { ElMessage } from 'element-plus'
import popup from './components/popup.vue'
import itemAdd from './components/itemAdd.vue'
import { downLoadFile } from '@/api/cs-system-boot/manage'

defineOptions({
    name: 'govern/manage/engineering'
})

const popupRef = ref()
const tableRef = ref()
const itemAddRef = ref()
const searchValue = ref('')
const rawList = ref<any[]>([])
const currentRow = ref<any>(null)

function buildTreeData(list: any[]) {
    return list.map(eng => ({
        ...eng,
        id: eng.engineeringId,
        rowType: 'engineering',
        name: eng.engineeringName,
        area: eng.engineeringAreaName || '/',
        remark: eng.engineeringRemark || '/',
        sort: eng.engineeringSort,
        children: (eng.projectInfoList || []).map((proj: any) => ({
            ...proj,
            id: proj.projectId,
            rowType: 'project',
            name: proj.projectName,
            area: proj.projectArea || '/',
            remark: proj.projectRemark || '/',
            sort: proj.projectSort,
            engineeringId: eng.engineeringId
        }))
    }))
}

async function loadTopologyImages(treeData: any[]) {
    for (const eng of treeData) {
        for (const proj of eng.children || []) {
            if (proj.topologyInfo && proj.topologyInfo !== '/') {
                const blob = (await downLoadFile(proj.topologyInfo)) as unknown as Blob
                if (blob?.type && blob.type !== 'application/json') {
                    proj.topologyImageUrl = window.URL.createObjectURL(blob)
                }
            }
        }
    }
}

function filterEngineeringList(list: any[], keyword: string) {
    if (!keyword) return list

    return list
        .map(eng => {
            const parentMatch = eng.engineeringName?.includes(keyword)
            const matchedProjects = (eng.projectInfoList || []).filter((proj: any) =>
                proj.projectName?.includes(keyword)
            )

            if (parentMatch) {
                return eng
            }
            if (matchedProjects.length > 0) {
                return { ...eng, projectInfoList: matchedProjects }
            }
            return null
        })
        .filter(Boolean)
}

function expandFirstTreeNode() {
    nextTick(() => {
        const treeInstance = tableRef.value?.getRef()
        if (!treeInstance) return
        treeInstance.setAllTreeExpand(false)
        const firstNode = tableStore.table.data[0]
        if (firstNode) {
            treeInstance.setTreeExpand([firstNode], true)
            treeInstance.setCurrentRow(firstNode)
            currentRow.value = firstNode
        }
    })
}

function applyTreeData() {
    const list = filterEngineeringList(rawList.value, searchValue.value)
    tableStore.table.data = buildTreeData(list)
    expandFirstTreeNode()
    loadTopologyImages(tableStore.table.data)
}

const tableStore: any = new TableStore({
    url: '/cs-device-boot/engineeringProjectRelation/list',
    method: 'POST',
    publicHeight: 60,
    showPage: false,
    column: [
        { field: 'name', title: '工程/项目名称', align: 'left', treeNode: true, minWidth: '250' },
        { field: 'area', title: '区域', minWidth: '180' },
        { field: 'remark', title: '备注', minWidth: '180' },

        {
            title: '操作',
            fixed: 'right',
            width: '220',
            render: 'buttons',
            buttons: [
                {
                    title: '新增项目',
                    type: 'primary',
                    icon: 'el-icon-Plus',
                    render: 'basicButton',
                    disabled: (row: any) => row.rowType !== 'engineering',
                    click: (row: any) => {
                        itemAddRef.value.open('新增项目', rawList.value, undefined, row.engineeringId)
                    }
                },
                {
                    title: '编辑',
                    type: 'primary',
                    icon: 'el-icon-EditPen',
                    render: 'basicButton',
                    click: (row: any) => {
                        if (row.rowType === 'engineering') {
                            popupRef.value.open('编辑工程', row)
                        } else {
                            itemAddRef.value.open('编辑项目', rawList.value, row, row.engineeringId)
                        }
                    }
                },
                {
                    title: '删除',
                    type: 'danger',
                    icon: 'el-icon-Delete',
                    render: 'confirmButton',
                    popconfirm: {
                        confirmButtonText: '确认',
                        cancelButtonText: '取消',
                        confirmButtonType: 'danger',
                        title: '确定删除吗？'
                    },
                    click: (row: any) => {
                        if (row.rowType === 'engineering') {
                            deleteEngineering({ id: row.engineeringId }).then(() => {
                                ElMessage.success('删除成功')
                                tableStore.index()
                            })
                        } else {
                            deleteProject({ id: row.projectId }).then(() => {
                                ElMessage.success('删除成功')
                                tableStore.index()
                            })
                        }
                    }
                }
            ]
        }
    ],
    loadCallback: () => {
        rawList.value = JSON.parse(JSON.stringify(tableStore.table.data))
        applyTreeData()
    }
})

provide('tableStore', tableStore)

const inpChaange = () => {
    applyTreeData()
}

const currentChange = ({ row }: any) => {
    currentRow.value = row
}

const addRole = () => {
    popupRef.value.open('新增工程')
}

const add = () => {
    const engineeringId =
        currentRow.value?.rowType === 'engineering'
            ? currentRow.value.engineeringId
            : currentRow.value?.rowType === 'project'
                ? currentRow.value.engineeringId
                : ''
    if (!engineeringId) {
        ElMessage.warning('请先选择工程')
        return
    }
    itemAddRef.value.open('新增项目', rawList.value, undefined, engineeringId)
}

onMounted(() => {
    tableStore.index()
})
</script>

<style scoped>
.el-image {
    height: 36px;
}
</style>
