<template>

    <el-dialog title="标准详情" v-model="dialogFormVisible" style="width: 800px; height: 700px;">
        <el-tabs v-model="dialogCurrentTab" style="width: 100%;">
            <el-tab-pane label="实体类型" name="tab1">
                <el-row>
                    <!-- <el-col :span="12" style=" border-right:1px solid #CDCDCD;"> -->

                    <el-button @click="handleAddSchema('entity')">增加</el-button>

                    <el-table :data="currentData?.entities" style="width: 100%; height: 500px;"
                        :tree-props="{ children: 'props' }" row-key="id"
                        :default-sort="{ props: 'id', order: 'descending' }">
                        <el-table-column prop="name" label="名称" width="200">
                            <template v-slot="scope">
                                <el-input v-if="scope.row.editable && scope.row.action != 'delete'"
                                    v-model="scope.row.name" placeholder="请输入名称" style="width: 100px">{{ scope.name
                                    }}</el-input>
                                <span v-else-if="scope.row.action == 'delete'"
                                    style="color: red; text-decoration: line-through;"><i>{{ scope.row.name
                                        }}</i></span>
                                <span v-else-if="scope.row.action == 'create'" style="color: green; ">{{ scope.row.name
                                    }}</span>
                                <span v-else>{{ scope.row.name }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="category" label="类型" width="250">
                            <template v-slot="scope">
                                <el-input v-if="scope.row.editable && scope.row.action != 'delete'"
                                    v-model="scope.row.category" placeholder="请输入类型" style="width: 100px">{{
                                        scope.category }}</el-input>
                                <span v-else-if="scope.row.action == 'delete'"
                                    style="color: red; text-decoration: line-through;"><i>{{ scope.row.category
                                        }}</i></span>
                                <span v-else-if="scope.row.action == 'create'" style="color: green; ">{{
                                    scope.row.category }}</span>
                                <span v-else>{{ scope.row.category }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" width="200">
                            <template v-slot="scope">
                                <el-link v-if="!scope.row.editable && scope.row.action != 'delete'" type="primary"
                                    @click="handleEditSchema('entity', scope.row.id, true)">编辑</el-link> &nbsp;
                                <el-link v-if="!scope.row.editable && scope.row.action != 'delete'" type="primary"
                                    @click="handleDeleteSchema('entity', scope.row.id)">删除</el-link>
                                <el-link v-if="scope.row.editable && scope.row.action != 'delete'" type="success"
                                    @click="handleSaveSchema('entity', scope.row.id)">保存</el-link>&nbsp;
                                <el-link v-if="scope.row.editable && scope.row.action != 'delete'" type="warning"
                                    @click="handleCancelEditSchema('entity', scope.row.id)">取消</el-link>
                            </template>
                        </el-table-column>
                    </el-table>

                </el-row>
            </el-tab-pane>
            <el-tab-pane label="关系类型" name="tab2">
                <el-row>

                    <el-button @click="handleAddSchema('relation')">增加</el-button>

                    <el-table :data="currentData?.relations" style="width: 100%; height: 500px;"
                        :tree-props="{ children: 'props' }" row-key="id"
                        :default-sort="{ props: 'id', order: 'descending' }">
                        <el-table-column prop="name" label="名称" width="200">
                            <template v-slot="scope">
                                <el-input v-if="scope.row.editable && scope.row.action != 'delete'"
                                    v-model="scope.row.name" placeholder="请输入名称" style="width: 100px">{{ scope.name
                                    }}</el-input>
                                <span v-else-if="scope.row.action == 'delete'"
                                    style="color: red; text-decoration: line-through;"><i>{{ scope.row.name
                                        }}</i></span>
                                <span v-else-if="scope.row.action == 'create'" style="color: green; ">{{ scope.row.name
                                    }}</span>
                                <span v-else>{{ scope.row.name }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="category" label="类型" width="250">
                            <template v-slot="scope">
                                <el-input v-if="scope.row.editable && scope.row.action != 'delete'"
                                    v-model="scope.row.category" placeholder="请输入类型" style="width: 100px">{{
                                        scope.category }}</el-input>
                                <span v-else-if="scope.row.action == 'delete'"
                                    style="color: red; text-decoration: line-through;"><i>{{ scope.row.category
                                        }}</i></span>
                                <span v-else-if="scope.row.action == 'create'" style="color: green; ">{{
                                    scope.row.category }}</span>
                                <span v-else>{{ scope.row.category }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" width="200">
                            <template v-slot="scope">
                                <el-link v-if="!scope.row.editable && scope.row.action != 'delete'" type="primary"
                                    @click="handleEditSchema('relation', scope.row.id, true)">编辑</el-link> &nbsp;
                                <el-link v-if="!scope.row.editable && scope.row.action != 'delete'" type="primary"
                                    @click="handleDeleteSchema('relation', scope.row.id)">删除</el-link>
                                <el-link v-if="scope.row.editable && scope.row.action != 'delete'" type="success"
                                    @click="handleSaveSchema('relation', scope.row.id)">保存</el-link>&nbsp;
                                <el-link v-if="scope.row.editable && scope.row.action != 'delete'" type="warning"
                                    @click="handleCancelEditSchema('relation', scope.row.id)">取消</el-link>
                            </template>
                        </el-table-column>
                    </el-table>

                </el-row>
            </el-tab-pane>
            <el-tab-pane label="调试" name="debug">
                <el-row>
                    <div style="width: 100%; height: 500px; overflow: auto;">{{ JSON.stringify(currentData) }}</div>
                </el-row>

            </el-tab-pane>
        </el-tabs>
        <template #footer>
            <el-button type="primary" @click="handleUpdateStdSchema">更新图谱标准</el-button>
            <el-button type="success" @click="handleApply">应用</el-button>
            <el-button @click="dialogFormVisible = false">取消</el-button>
        </template>
    </el-dialog>
</template>
<script setup lang="ts">
import { ElMessage } from 'element-plus'
import { ref, defineEmits } from 'vue'
import { ElMessageBox, ElNotification } from 'element-plus'
import { updateStdSchemaContent, reindexSchema } from '@/api/GraphApi'
import { type SchemaData } from '@/types/dataset'


const currentSchemaId = ref(0)
const currentData = ref<SchemaData>()
const currentDialogRelation = ref({})
// const entitiesEditable = ref({})
// const propsEditable = ref({})

const dialogFormVisible = ref(false)
const dialogCurrentTab = ref('tab1')
const currentId = ref(0)

const emits = defineEmits(['stdUpdated']);

const handleAddSchema = (schemaType: string) => {
    currentId.value++
    if (currentData.value == null) {
        return
    }

    if (schemaType == "entity") {
        currentData.value.entities.unshift({ id: `${currentId.value}`, name: "", category: "", old_name: "", old_category: "", action: "create", editable: false, is_new: true, props: [] })
        handleEditSchema(schemaType, `${currentId.value}`, true)
    }
    if (schemaType == "relation") {
        currentData.value.relations.unshift({ id: `${currentId.value}`, name: "", category: "", old_name: "", old_category: "", action: "create", editable: false, is_new: true, props: [] })
        handleEditSchema(schemaType, `${currentId.value}`, true)
    }

}
const handleApplyDataChange = () => {
    if (currentData.value == null) {
        return
    }

    var targetData = currentData.value.entities
    for (var i = 0; i < targetData.length;) {

        if (targetData[i].action == "delete") {
            targetData.splice(i, 1)
            continue
        }
        i++

    }
    targetData = currentData.value.relations
    for (var i = 0; i < targetData.length;) {

        if (targetData[i].action == "delete") {
            targetData.splice(i, 1)
            continue
        }
        i++
    }
}
const handleApply = (need_confirm: boolean = false) => {
    if (currentData.value == null) {
        return
    }

    if (need_confirm) {
        ElMessageBox.confirm('接受数据变更会更新当前的对话框数据，但是不会对原始数据产生影响。若需保存变更，请点击‘更新图谱标准’按钮', '提示', {}).then(() => {
            handleApplyDataChange()
        }).catch(() => { })
    } else {
        handleApplyDataChange()
    }

}
const handleSaveSchema = (schemaType: string, id: any) => {
    console.log("handleSaveEntity")
    if (currentData.value == null) {
        return
    }
    var targetData = currentData.value.entities
    if (schemaType == "relation") {
        targetData = currentData.value.relations
    }
    for (var i = 0; i < targetData.length; i++) {
        if (targetData[i].id == id) {

            if (targetData[i].name == "") {
                ElMessage({ type: 'warning', message: '名称不能为空' })
                return
            }
            if (targetData[i].category == "") {
                ElMessage({ type: 'warning', message: '类型不能为空' })
                return
            }
            if (targetData[i].action == "create") {
                targetData[i].action = "create"
                targetData[i].props = []
            } else {
                targetData[i].action = "update"
            }
            targetData[i].is_new = false

        } else {
            for (var j = 0; j < targetData[i].props.length; j++) {
                if (targetData[i].props[j].id == id) {
                    if (targetData[i].props[j].name == "") {
                        ElMessage({ type: 'warning', message: '名称不能为空' })
                        return
                    }
                    if (targetData[i].props[j].category == "") {
                        ElMessage({ type: 'warning', message: '类型不能为空' })
                        return
                    }
                    if (targetData[i].props[j].action == "create") {
                        targetData[i].props[j].action = "create"
                    } else {
                        targetData[i].props[j].action = "update"
                    }
                    targetData[i].is_new = false
                }
            }
        }
    }
    handleEditSchema(schemaType, id, false)
}
const handleCancelEditSchema = (schemaType: string, id: any) => {
    console.log("handleCancelEditEntity")
    if (currentData.value == null) {
        return
    }
    var targetData = currentData.value.entities
    if (schemaType == "relation") {
        targetData = currentData.value.relations
    }
    for (var i = 0; i < targetData.length; i++) {
        if (targetData[i].id == id && targetData[i].is_new == true) {
            targetData.splice(i, 1)
            break
        }
        if (targetData[i].id == id) {
            targetData[i].name = targetData[i].old_name
            targetData[i].category = targetData[i].old_category
            handleEditSchema(schemaType, id, false)
            break
        } else {
            for (var j = 0; j < targetData[i].props.length; j++) {
                if (targetData[i].props[j].id == id) {
                    targetData[i].props[j].name = targetData[i].props[j].old_name
                    targetData[i].props[j].category = targetData[i].props[j].old_category
                    handleEditSchema(schemaType, id, false)
                    break
                }
            }
        }
    }
}
const handleCancelEditSchemaAll = (schemaType: string) => {
    if (currentData.value == null) {
        return
    }

    var targetData = currentData.value.entities
    if (schemaType == "relation") {
        targetData = currentData.value.relations
    }
    for (var i = 0; i < targetData.length; i++) {
        if (targetData[i].editable == true) {
            targetData[i].editable = false
            if (targetData[i].is_new) {
                targetData.splice(i, 1)
            }
            break
        }

        for (var j = 0; j < targetData[i].props.length; j++) {
            if (targetData[i].props[j].editable == true) {
                targetData[i].props[j].editable = false
                if (targetData[i].props[j].is_new) {
                    targetData[i].props.splice(j, 1)
                }
                break
            }
        }
    }
}
const handleEditSchema = (schemaType: string, id: any, newValue: boolean) => {
    console.log("handleEditEntity")
    if (currentData.value == null) {
        return
    }
    handleCancelEditSchemaAll(schemaType)
    var targetData = currentData.value.entities
    if (schemaType == "relation") {
        targetData = currentData.value.relations
    }
    for (var i = 0; i < targetData.length; i++) {
        if (targetData[i].id == id) {
            targetData[i].editable = newValue
            if (newValue == true) {
                targetData[i].old_name = targetData[i].name
                targetData[i].old_category = targetData[i].category
            }
        } else {
            for (var j = 0; j < targetData[i].props.length; j++) {
                if (targetData[i].props[j].id == id) {
                    targetData[i].props[j].editable = newValue
                    if (newValue == true) {
                        targetData[i].props[j].old_name = targetData[i].props[j].name
                        targetData[i].props[j].old_category = targetData[i].props[j].category
                    }
                } else {
                    targetData[i].props[j].editable = false
                }
            }

            targetData[i].editable = false
        }
    }
}
const handleDeleteSchema = (schemaType: string, id: any, confirm: boolean = true) => {
    if (currentData.value == null) return
    var targetData = currentData.value.entities
    if (schemaType == "relation") {
        targetData = currentData.value.relations
    }
    if (confirm == false) {
        for (var i = 0; i < targetData.length; i++) {
            if (targetData[i].id == id) {
                targetData[i].action = "delete"
                break
            }
        }
        return
    }
    ElMessageBox.confirm('是否删除该实体类型？', '提示', {}).then(() => {
        for (var i = 0; i < targetData.length; i++) {
            if (targetData[i].id == id) {
                targetData[i].action = "delete"
                for (var j = 0; j < targetData[i].props.length; j++) {
                    targetData[i].props[j].action = "delete"
                }
                break
            } else {
                for (var j = 0; j < targetData[i].props.length; j++) {
                    if (targetData[i].props[j].id == id) {
                        targetData[i].props[j].action = "delete"
                        break
                    }
                }
            }
        }
        ElMessage({ type: 'success', message: '删除成功' })

    })
}

const handleUpdateStdSchema = () => {
    if (currentData.value == null) return


    ElMessageBox.confirm('请注意，此操作将更新图谱标准数据，引用该标准的图谱数据不会被自动更新', '提示', {}).then(() => {
        var content = JSON.stringify(currentData.value);
        updateStdSchemaContent({ schema_id: currentSchemaId.value, content: content }).then(response => {
            ElNotification({
                title: 'Success',
                message: '更新图谱标准成功',
                type: 'success',
            })
            emits('stdUpdated')
            // reindexSchema({schema_id: currentData.value.data.id}).then(response => {
            //     ElNotification({
            //     title: 'Success',
            //     message: '更新图谱索引成功',
            //     type:'success', 
            //     }) 
            // })
        })

        dialogFormVisible.value = false
    })
}
// function handleCurrentEntityChange(data:any) {
//     if (data == null) {
//         return
//     }
//     currentDialogEntity.value = data
// }

// function generateIdForData(){
//     var id = currentId.value
//     for (var i=0;i<currentData.value.data.entities.length;i++) {
//         currentData.value.data.entities[i].id=`${id}`
//         currentData.value.data.entities[i].new_name= ""
//         currentData.value.data.entities[i].new_category= ""
//         currentData.value.data.entities[i].editable = false
//         var subId =0
//         for (var j=0;j<currentData.value.data.entities[i].props.length;j++) {
//             currentData.value.data.entities[i].props[j].id=`${id}-${subId}`
//             currentData.value.data.entities[i].props[j].new_name=""
//             currentData.value.data.entities[i].props[j].new_category=""
//             currentData.value.data.entities[i].props[j].editable=false
//             subId++ 
//         }
//         id ++ 
//     }
//     for (var i=0;i<currentData.value.data.relations.length;i++) {
//         currentData.value.data.relations[i].id=id 
//         id++
//     }
//     currentId.value = id
// }
function handleCurrentRelationChange(data: any) {
    if (data == null) {
        return
    }
    currentDialogRelation.value = data
}
function showDialog(visible: boolean = true, schemaData: any, id: number) {
    var data = schemaData
    console.log("schemaData", schemaData)
    currentSchemaId.value = id
    console.log("showDialog", data)
    dialogFormVisible.value = visible
    currentData.value = { entities: [], relations: [] }


    for (var i = 0; i < data.entities.length; i++) {
        var entity = { ...data.entities[i], editable: false, is_new: false, action: "", props: [] }
        if ("props" in data.entities[i] == false) {
            data.entities[i].props = []
        }
        for (var j = 0; j < data.entities[i].props.length; j++) {
            entity.props.push({ ...data.entities[i].props[j], editable: false, is_new: false, action: "", })
        }
        currentData.value.entities.push(entity)
    }
    for (var i = 0; i < data.relations.length; i++) {
        var entity = { ...data.relations[i], editable: false, is_new: false, action: "", props: [] }
        if ("props" in data.relations[i] == false) {
            data.relations[i].props = []
        }
        for (var j = 0; j < data.relations[i].props.length; j++) {
            entity.props.push({ ...data.relations[i].props[j], editable: false, is_new: false, action: "", })
        }
        currentData.value.relations.push(entity)
    }
    //generateIdForData()

}
defineExpose({ showDialog })
</script>