<template>
    <div class="default-main" :style="height">
        <!-- 算法库 -->
        <splitpanes style="height: 100%" class="default-theme" id="navigation-splitpanes">
            <pane :size="size">
                <algorithmTree
                    ref="treeRef"
                    :default-expand-all="false"
                    :default-expanded-keys="monitoringPoint.state.lineId ? [monitoringPoint.state.lineId] : []"
                    :current-node-key="monitoringPoint.state.lineId"
                    @node-click="handleNodeClick"
                    @init="handleNodeClick"
                    @onAddTree="onAddTree"
                ></algorithmTree>
            </pane>
            <pane style="background: #fff; width: 100%" :style="height">
                <div class="boxTop">
                    <div>
                        <el-radio-group v-model="radio">
                            <el-radio-button v-for="(item, i) in dotList?.childrens" :label="item.name" :value="i" />
                        </el-radio-group>
                    </div>
                    <div >
                        <el-button icon="el-icon-Plus" type="primary" @click="addUser">新增</el-button>
                        <el-button icon="el-icon-Edit" type="primary" @click="revise">修改</el-button>
                        <el-button icon="el-icon-Delete" type="primary" @click="deletes">删除</el-button>
                    </div>
                </div>

                <div :style="heightTab">
                    <vxe-table height="auto" v-bind="defaultAttribute" :data="dotList?.childrens[radio]?.children">
                        <vxe-column field="name" title="算法名称"></vxe-column>
                        <vxe-column field="createTime" title="创建时间"></vxe-column>

                        <vxe-column field="period" title="计算周期">
                            <template #default="{ row }">
                                {{
                                    row.period == 0
                                        ? '日'
                                        : row.period == 1
                                        ? '月'
                                        : row.period == 2
                                        ? '季'
                                        : row.period == 3
                                        ? '年'
                                        : ''
                                }}
                            </template>
                        </vxe-column>
                        <vxe-column field="source" title="数据来源"></vxe-column>
                        <!-- <vxe-column field="useFLag" title="是否启用">
                            <template #default="{ row }">
                                <el-tag :type="row.useFLag === 1 ? 'success' : 'info'" effect="dark"
                                    style="cursor: pointer" @click="change(row)">
                                    {{ row.useFLag === 1 ? '是' : '否' }}
                                </el-tag>
                            </template>
                        </vxe-column> -->
                        <vxe-column field="definition" title="定义">
                            <template #default="{ row }">
                                <el-button type="primary" link @click="view(row)">查看</el-button>
                            </template>
                        </vxe-column>
                        <!-- <vxe-column title="操作" width="150px">
                            <template #default="{ row }">
                                <el-button type="primary" link @click="edit(row)">修改</el-button>
                                <el-button type="danger" link @click="del(row)">删除</el-button>
                                <el-popconfirm title="确定删除吗？" confirm-button-type='danger'  @confirm="del(row)">
                                    <template #reference>
                                        <el-button type="danger" link>删除</el-button>
                                    </template>
                                </el-popconfirm>
                            </template>
                        </vxe-column> -->
                    </vxe-table>
                </div>
            </pane>
        </splitpanes>
        <!-- 树弹框 -->
        <addTree ref="addTreeRef" @getTree="treeRef.loadData(dotList.id)" />
        <!-- 弹框 -->
        <PopupEdit
            ref="popupEditRef"
            v-if="popupEditFlag"
            @getTree="treeRef.loadData(dotList.id), (popupEditFlag = false)"
        />
        <!-- 定义 -->
        <el-dialog draggable v-model="viewFlag" title="定义" width="60%">
            <div style="min-height: 300px; max-height: 55vh">
                <div class="editor" ref="editorRef" v-html="summary" />
            </div>
        </el-dialog>
        <!-- 删除 -->
        <el-dialog draggable v-model="dialogVisible" title="请选择需要删除的数据" width="400">
            <el-tree-select
                v-model="TreeValue"
                :data="TreeData"
                filterable
                check-strictly
                :props="defaultProps"
                default-expand-all
                :render-after-expand="false"
            />
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="del">删除</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>
<script setup lang="ts">
import { onMounted, ref, provide, nextTick } from 'vue'
import 'splitpanes/dist/splitpanes.css'
import { Splitpanes, Pane } from 'splitpanes'
import algorithmTree from '@/components/tree/pqs/algorithmTree.vue'
import { mainHeight } from '@/utils/layout'
import { defaultAttribute } from '@/components/table/defaultAttribute'
import { getLineExport, selectReleation } from '@/api/event-boot/report'
import addTree from './components/addTree.vue'
import PopupEdit from './components/form.vue'
import { useMonitoringPoint } from '@/stores/monitoringPoint'
import { ElMessage, ElMessageBox } from 'element-plus'
import { deleteyById } from '@/api/supervision-boot/database/index'
import { queryAllAlgorithmLibrary, updateAlgorithmLibrary } from '@/api/supervision-boot/database/index'
import { useAdminInfo } from '@/stores/adminInfo'
import katex from 'katex'
import 'katex/dist/katex.css'
const adminInfo = useAdminInfo()
defineOptions({
    name: 'database/algorithm'
})
const monitoringPoint = useMonitoringPoint()
const height = mainHeight(20)
const heightTab = mainHeight(82)
const size = ref(19)
const addTreeRef = ref()
const editorRef = ref()
const dialogVisible = ref(false)
const viewFlag = ref(false)
const popupEditFlag = ref(false)
const treeRef = ref()
const summary = ref('')
const popupEditRef = ref()
const TreeData = ref([])
const TreeValue = ref([])
const information = adminInfo.roleCode.includes('information_info')

const defaultProps = {
    label: 'name',
    value: 'id'
}
const dotList: any = ref()

const templatePolicy: any = ref([])
// const tableStore = new TableStore({
//     url: '/supervision-boot/libalgorithm/queryAllAlgorithmLibrary',
//     method: 'GET',
//     column: [
//         { title: '算法名称', field: 'name' },
//         {
//             title: '定义',
//             field: 'name1'
//         },
//         {
//             title: '计算公式',
//             field: 'name2'
//         },
//         {
//             title: '计算周期',
//             field: 'name3'
//         },
//         {
//             title: '数据来源',
//             field: 'name4'
//         },
//         {
//             title: '是否启用',
//             field: 'name5',
//             render: 'tag',
//             effect: 'dark',
//             custom: {
//                 0: 'info',
//                 1: 'success'
//             },
//             replaceValue: {
//                 0: '否',
//                 1: '是'
//             }
//         }
//     ],
//     loadCallback: () => {}
// })
const radio = ref(0)

// 新增弹框
const addUser = () => {
    popupEditFlag.value = true
    setTimeout(() => {
        popupEditRef.value.open({
            title: '新增算法'
        })
    }, 100)
}
// 修改弹框
const revise = () => {
    popupEditFlag.value = true
    setTimeout(() => {
        popupEditRef.value.open({
            title: '修改算法',
            row: dotList.value
        })
    }, 100)
}

onMounted(() => {
    const dom = document.getElementById('navigation-splitpanes')
    if (dom) {
        size.value = Math.round((180 / dom.offsetHeight) * 120)
    }
    // tableStore.index()
})

const view = (row: any) => {
    viewFlag.value = true
    summary.value = row.definition
    setTimeout(() => {
        const spans = document.querySelectorAll('span[data-value]')
        // 遍历每个 span 标签
        spans.forEach(function (span) {
            let val = katex.renderToString(span.getAttribute('data-value'), {
                throwOnError: false
            })
            // var newDiv = document.createElement('div');
            var newDiv = span
            newDiv.innerHTML = val

            span.parentNode.replaceChild(newDiv, span)
        })
    }, 100)

    //
}

const handleNodeClick = (data: any, node: any) => {
    if (data.pid != '0') {
        dotList.value = data
        radio.value = 0
    }
}
const onAddTree = () => {
    addTreeRef.value.open('新增')
}
const deletes = () => {
    TreeValue.value = []
    queryAllAlgorithmLibrary().then(res => {
        TreeData.value = res.data
    })
    dialogVisible.value = true
}
// 删除
const del = () => {
    if (TreeValue.value.length == 0) {
        return ElMessage.warning('请选择数据')
    }
    ElMessageBox.confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        deleteyById({ id: TreeValue.value }).then(res => {
            ElMessage.success('删除成功')
            dialogVisible.value = false
            treeRef.value.loadData()
        })
    })

    // if (TreeValue.value.length > 0) {
    //     ElMessage.warning('请选择数据')
    //     return
    // }
}
// 启用
const change = (row: any) => {
    console.log('🚀 ~ change ~ row:', row)
    ElMessageBox.confirm(`请确认是否${row.useFLag == 0 ? '启用' : '关闭'}算法?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        updateAlgorithmLibrary({ ...row, useFLag: row.useFLag == 0 ? 1 : 0 }).then(res => {
            ElMessage.success(row.useFLag == 0 ? '启用' : '关闭' + '成功')
            treeRef.value.loadData(dotList.value.id)
        })
    })
}
const getList = (val: any) => {
    setTimeout(async () => {
        dotList.value = await treeRef.value.setKey(val.data.pid)
        await dotList.value?.childrens.forEach((item: any, i: number) => {
            if (item.id == val.data.id) {
                radio.value = i
            }
        })
    }, 500)
}
defineExpose({
    getList
})
</script>
<style lang="scss">
.splitpanes.default-theme .splitpanes__pane {
    background: #eaeef1;
}

.grid-content {
    text-align: center;
}

.el-divider--horizontal {
    margin: 10px 0;
}

.mTop {
    margin-top: 5px;
    margin-bottom: 5px;
}

.boxTop {
    height: 52px;
    padding: 10px 10px 10px 0;
    display: flex;
    justify-content: space-between;
}

.editor {
    table {
        width: 100%;
        border-collapse: collapse;
    }

    th,
    td {
        border: 1px solid black;
        padding: 8px;
        text-align: center;
    }

    th {
        background-color: #f2f2f2;
        font-weight: bold;
    }

    td {
        background-color: #ffffff;
    }
}
</style>
