<template>
    <el-dialog draggable class="cn-operate-dialog" v-model="dialogVisible" :title="title" width="1200px">

        <el-form :model="form" label-width="120px" class="form-two" :rules="rules" ref="formRef">
            <el-form-item :label="title == '修改算法' ? '选择修改的数据' : '选择父级'" :prop="title == '修改算法' ? 'pid' : ''">
                <el-tree-select v-model="form.pid" :data="dataTree" check-strictly clearable filterable
                    @node-click="changeTree" default-expand-all :render-after-expand="false" :props="defaultProps"
                    @clear="TreeList = {}" />
            </el-form-item>
            <el-form-item label="名称" prop="name" v-if="title == '修改算法' ? TreeList.level != 4 : TreeList.level != 3">
                <el-input v-model="form.name" placeholder="名称" clearable maxlength="32" show-word-limit @input="handleInput('name', $event)"/>
            </el-form-item>
            <el-form-item label="绑定页面" v-if="title == '修改算法' ? TreeList.level == 3 : TreeList.level == 2">
                <el-input v-model="form.path" placeholder="请输入需要绑定的路由" clearable maxlength="32" show-word-limit @input="handleInput('name', $event)"/>
            </el-form-item>
            <!-- <div v-if="title == '修改算法' ? TreeList.level == 4 : TreeList.level == 3"> -->
            <el-form-item label="算法名称" prop="name" v-if="title == '修改算法' ? TreeList.level == 4 : TreeList.level == 3">
                <el-input v-model="form.name" placeholder="请输入算法名称" clearable maxlength="32" show-word-limit @input="handleInput('name', $event)"/>
            </el-form-item>
            <el-form-item label="计算周期" prop="period" v-if="title == '修改算法' ? TreeList.level == 4 : TreeList.level == 3">
                <el-select v-model="form.period" placeholder="请选择计算周期" clearable>
                    <el-option v-for="item in cycle" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
            </el-form-item>
            <el-form-item label="数据来源" prop="source" v-if="title == '修改算法' ? TreeList.level == 4 : TreeList.level == 3">
                <el-input v-model="form.source" placeholder="请输入数据来源" clearable maxlength="32" show-word-limit @input="handleInput('source', $event)"/>
            </el-form-item>
            <!-- <el-form-item label="定义" prop="definition" style="width: 100%;" v-if="title == '修改算法' ? TreeList.level == 4 : TreeList.level == 3">
                      
                        <editor v-model="form.definition" />
                    </el-form-item> -->
            <!-- </div> -->
        </el-form>
        <div style="display: flex" v-if="title == '修改算法' ? TreeList.level == 4 : TreeList.level == 3">
            <div style="width: 140px;margin-right: -20px;text-align: center;flex-shrink: 0;">定义</div>
            <editor v-model="form.definition" />
        </div>

        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submit" v-loading="loading">确认</el-button>
            </span>
        </template>
    </el-dialog>
</template>
<script lang="ts" setup>
import { ref, nextTick } from 'vue'
import { reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { queryAllAlgorithmLibrary, addAlgorithm, updateAlgorithmLibrary } from '@/api/supervision-boot/database/index'
import editor from '@/components/wangEditor/index.vue'
const emit = defineEmits(['getTree'])
const dialogVisible = ref(false)
const title = ref('')
const formRef = ref()
const loading = ref(false)
const dataTree = ref([])
const key = ref(0)
const TreeList: any = ref({})
const List = ref({})
const defaultProps = {
    children: 'children',
    label: 'name',
    value: 'id'
}
// 注意不要和表单ref的命名冲突
const form = reactive<anyObj>({
    name: '',
    period: '',
    definition: '',
    source: '',
    pid: '',
    path: ''
})
const rules = {
    name: [{ required: true, message: '请输入算法名称', trigger: 'blur' }],
    period: [{ required: true, message: '请选择计算周期', trigger: 'change' }],
    pid: [{ required: true, message: '请选择数据', trigger: 'change' }],
    definition: [{ required: true, message: '请输入定义', trigger: 'blur' }],
    source: [{ required: true, message: '请输入数据来源', trigger: 'blur' }]
}
const cycle = [
    { value: '0', label: '日' },
    { value: '1', label: '月' },
    { value: '2', label: '季' },
    { value: '3', label: '年' }
]
const changeTree = (row: any) => {
    console.log("🚀 ~ changeTree ~ row:", row)
    TreeList.value = row
    if (title.value == '修改算法') {
        if (row.level != 4) {
            form.name = row.name

        } else {
            for (let key in form) {
                form[key] = row[key]
            }
        }

        form.id = row.id
        key.value += 1
    }
}

const open = (row: any) => {
    title.value = row.title
    dialogVisible.value = true
    List.value = row.row
    getTheTree()
    // 在此处恢复默认表单
    nextTick(() => {
        for (let key in form) {
            form[key] = ''
        }
        if (row.title == '修改算法') {

            form.pid = row.row.id
            TreeList.value = row.row
            changeTree(row.row)

            // row.row
        }
    })
    formRef.value?.resetFields()
}
const submit = async () => {
    loading.value = true
    formRef.value.validate(async (valid: boolean) => {
        if (valid) {
            if (title.value == '新增算法') {
                let forms: any = {}
                if (TreeList.value.level == 3) {
                    forms = form
                } else {
                    forms.name = form.name
                    forms.pid = form.pid
                    forms.path = form.path||''
                }
                await addAlgorithm(forms).then(res => {
                    ElMessage.success('新增成功')
                    dialogVisible.value = false
                    emit('getTree')
                })
            } else {
                let forms: any = {}
                if (TreeList.value.level == 4) {
                    forms = JSON.parse(JSON.stringify(form))
                } else {
                    forms.name = form.name
                    forms.id = form.id
                }
                forms.pid = null
                await updateAlgorithmLibrary(forms).then(res => {
                    ElMessage.success('修改成功')
                    dialogVisible.value = false
                    emit('getTree')
                })
            }
        }
    })
    await setTimeout(() => {

        loading.value = false
    }, 0)
}
const getTheTree = () => {
    queryAllAlgorithmLibrary().then(res => {
        res.data.forEach((item: any) => {
            item.children.forEach((item2: any) => {
                item2.children.forEach((item3: any) => {
                    if (title.value != '修改算法') {
                        item3.childrens = item3.children
                        item3.children = []
                    }
                })
            })
        })

        dataTree.value = res.data
    })
}


const handleInput = (field: string, value: string) => {
    // 过滤空格
    const filteredValue = value.replace(/\s/g, '')
    if (filteredValue !== value) {
        form[field] = filteredValue
    }
}

defineExpose({ open })
</script>
