<template>
    <div>
        <div class="coentent">
            <div class="contents-area">
                <div class="areas">
                    <div class="headers">
                        <div class="headers-left">
                            <div class="headers-name">数据类型表</div>
                           
                        </div>
                        <div class="headers-right">
                            <el-input placeholder="请输入内容" style="border: 1px solid #EDEFFE;" v-model="queryForm.keyword" class="input-with-select" clearable>
                            <el-button slot="append" icon="el-icon-search" @click="handleSearch"></el-button>
                        </el-input>
                        </div>
                    </div>

                    <div class="content-table">
                        <el-table
                            :data="pagedData"
                            border
                            v-loading="loading"
                            :header-cell-style="{ background: '#EDEFFE', color: '#363636', textAlign: 'center' }"
                            :cell-style="cellStyle"
                            :row-class-name="rowClassName"
                            style="width: 100%">
                            <el-table-column type="index" label="序号" width="70" align="center" :index="formatIndex"></el-table-column>
                            <el-table-column prop="category" label="类型" min-width="160"></el-table-column>
                            <el-table-column prop="description" label="摘要描述" min-width="420"></el-table-column>
                            <el-table-column label="操作" width="120" align="center">
                                <template #default="scope">
                                    <el-button type="text" class="link-btn" @click="handleDetail(scope.row)">详情</el-button>
                                </template>
                            </el-table-column>
                        </el-table>

                        <div class="footer">
                            <el-pagination
                                @size-change="handleSizeChange"
                                @current-change="handleCurrentChange"
                                :current-page="currentPage"
                                :page-sizes="[10, 20, 30, 50]"
                                :page-size="pageSize"
                                layout="total, sizes, prev, pager, next, jumper"
                                :total="total">
                            </el-pagination>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <el-dialog
            :visible.sync="detailDialogVisible"
            width="820px"
            class="dictionary-dialog"
            :close-on-click-modal="false"
            :destroy-on-close="true"
            @closed="resetDetailDialog">
            <template #title>
                <div class="dialog-title">{{ currentCategory }}</div>
            </template>
            <div class="dialog-content">
                <div class="dialog-section">
                    <div class="section-header">
                        <div class="section-title">{{ currentCategory }}信息</div>
                        <el-button type="text" class="link-btn" @click="handleAddRoot">添加</el-button>
                    </div>
                    <el-tree
                        ref="detailTree"
                        :data="detailTreeData"
                        node-key="id"
                        :props="detailTreeProps"
                        default-expand-all
                        :expand-on-click-node="false"
                        class="dictionary-tree">
                        <template #default="{ data, node }">
                            <div class="tree-node">
                                <div class="node-content">
                                    <div class="node-buttons">
                                        <button class="node-btn node-btn-add" @click.stop="openAddNodeDialog(node, data)">+</button>
                                        <button class="node-btn node-btn-remove" @click.stop="handleDeleteNode(node, data)">-</button>
                                    </div>
                                    <span class="node-prefix" v-if="node.level > 1">-</span>
                                    <span class="node-label">{{ data.label }}</span>
                                </div>
                            </div>
                        </template>
                    </el-tree>
                </div>
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button size="small" @click="handleCancelDetail">取消</el-button>
                    <el-button type="primary" size="small" @click="handleSaveDetail">保存</el-button>
                </div>
            </template>
        </el-dialog>
        <el-dialog
            :visible.sync="addDialogVisible"
            width="520px"
            class="dictionary-add-dialog"
            :close-on-click-modal="false"
            :destroy-on-close="true"
            @closed="resetAddDialog">
            <template #title>
                <div class="add-dialog-title">{{ addDialogTitle }}</div>
            </template>
            <div class="add-dialog-body">
                <el-input v-model="newNodeName" style="border: 1px solid #EDEFFE;"  placeholder="请输入" maxlength="50"></el-input>
            </div>
            <template #footer>
                <div class="add-dialog-footer">
                    <el-button size="small" @click="cancelAddNode">取消</el-button>
                    <el-button type="primary" size="small" @click="confirmAddNode">保存</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script>
import {all} from '@/api/system/Configuration/index'
export default {
    data() {
        return {
            loading: false,
            queryForm: {
                keyword: ''
            },
            currentPage: 1,
            pageSize: 10,
            total: 0,
            detailDialogVisible: false,
            currentCategory: '',
            detailTreeData: [],
            detailTreeProps: {
                children: 'children',
                label: 'label'
            },
            addDialogVisible: false,
            addDialogTitle: '',
            newNodeName: '',
            pendingAddNode: null,
            detailTemplates: {
                default: [
                    {
                        id: 'electronics',
                        label: '电子信息',
                        children: []
                    },
                    {
                        id: 'biomedicine',
                        label: '生物与新医药',
                        children: [
                            {
                                id: 'biopharmaceutical',
                                label: '医药生物技术',
                                children: [
                                    { id: 'vaccine', label: '新型疫苗' },
                                    { id: 'therapeutics', label: '生物治疗技术和蛋白工程药物' },
                                    { id: 'molecule', label: '生物大分子类药物制备技术' },
                                    { id: 'natural', label: '天然药物结合物合成技术' },
                                    { id: 'testing', label: '生物药的原料、试剂、装置及相关检验检测技术' }
                                ]
                            },
                            {
                                id: 'traditional',
                                label: '中药、天然药物',
                                children: []
                            },
                            {
                                id: 'chemical',
                                label: '化学药物技术',
                                children: []
                            },
                            {
                                id: 'material',
                                label: '特种新型复合制剂技术',
                                children: []
                            }
                        ]
                    },
                    {
                        id: 'service',
                        label: '高新技术服务',
                        children: []
                    },
                    {
                        id: 'manufacture',
                        label: '先进制造与自动化',
                        children: []
                    },
                    {
                        id: 'aerospace',
                        label: '航空航天',
                        children: []
                    },
                    {
                        id: 'newmaterial',
                        label: '新材料',
                        children: []
                    },
                    {
                        id: 'newenergy',
                        label: '新能源与节能',
                        children: []
                    }
                ]
            },
            tableData: [
                {
                    id: 1,
                    category: '技术领域',
                    description: '电子信息、高新技术服务、先进制造与自动化、航空航天等'
                },
                {
                    id: 2,
                    category: '技术来源',
                    description: '地方属科研院所、中央属科研院所、企业自有技术等'
                },
                {
                    id: 3,
                    category: '标准制定类型',
                    description: '国际、国家、行业、地方、团体'
                },
                {
                    id: 4,
                    category: '标准制定参与方式',
                    description: '主持、参与'
                },
                {
                    id: 5,
                    category: '知识产权获得方式',
                    description: '自主研发、受让、受赠、并购、其他'
                },
                {
                    id: 6,
                    category: '上市类型',
                    description: '新三板、深交所中小板、东交所、深交所主板、上交所、香港、纳斯达克等'
                },
                {
                    id: 7,
                    category: '研发项目类型',
                    description: '自研项目、科技项目等'
                },
                {
                    id: 8,
                    category: '期刊类型',
                    description: '普通期刊、一般核心、重要核心、权威核心'
                },
                {
                    id: 9,
                    category: '合同类型',
                    description: '技术合同、采购租赁、外聘劳务、其他'
                },
                {
                    id: 10,
                    category: '产品收入类型',
                    description: '产品收入、技术性收入等'
                },
                {
                    id: 11,
                    category: '客户类型',
                    description: '政府机构、事业单位、企业客户等'
                },
                {
                    id: 12,
                    category: '联系人角色',
                    description: '主要联系人、技术联系人、财务联系人'
                }
            ]
        }
    },
    computed: {
        filteredData() {
            const keyword = this.queryForm.keyword.trim()
            if (!keyword) {
                return this.tableData
            }
            return this.tableData.filter((item) =>
                item.category.includes(keyword) || item.description.includes(keyword)
            )
        },
        pagedData() {
            // 如果使用后端分页，直接返回 tableData
            // 如果使用前端分页，则进行切片
            const keyword = this.queryForm.keyword.trim()
            if (keyword) {
                // 有搜索关键词时，使用前端分页
                const start = (this.currentPage - 1) * this.pageSize
                return this.filteredData.slice(start, start + this.pageSize)
            }
            // 无搜索关键词时，直接返回 tableData（后端已分页）
            return this.tableData
        }
    },
    mounted(){
        this.getall()
    },
    methods: {
        //获取所有数据字典类型列表
        getall(){
            this.loading = true
            const params = {
                page: this.currentPage,
                limit: this.pageSize
            }
            if (this.queryForm.keyword) {
                params.keyword = this.queryForm.keyword.trim()
            }
            all(params).then((res)=>{
                if (res && res.code === 1 && res.data) {
                    // 处理返回的数据
                    const list = res.data.data || res.data.list || res.data.records || []
                    // 更新总数
                    this.total = res.data.total || res.data.count || list.length || 0
                    // 更新表格数据
                    if (Array.isArray(list)) {
                        this.tableData = list.map(item => ({
                            id: item.id || item.dictTypeId,
                            category: item.name || item.dictTypeName || item.category || '',
                            description: item.description || item.desc || item.remark || ''
                        }))
                    } else {
                        this.tableData = []
                    }
                } else {
                    this.tableData = []
                    this.total = 0
                }
            }).catch(error => {
                console.error('获取数据字典列表失败:', error)
                this.tableData = []
                this.total = 0
                // 错误信息已经在 request.js 的拦截器中处理并显示
            }).finally(() => {
                this.loading = false
            })  
        },
        handleSearch() {
            this.currentPage = 1
            this.getall()
        },
        handleSizeChange(val) {
            this.pageSize = val
            this.currentPage = 1
            this.getall()
        },
        handleCurrentChange(val) {
            this.currentPage = val
            this.getall()
        },
        formatIndex(index) {
            return (this.currentPage - 1) * this.pageSize + index + 1
        },
        rowClassName() {
            return 'dictionary-row'
        },
        cellStyle({ column }) {
            const leftAlignedProps = ['category', 'description']
            return {
                textAlign: leftAlignedProps.includes(column.property) ? 'left' : 'center',
                color: '#363636'
            }
        },
        handleDetail(row) {
            this.currentCategory = row.category
            this.detailTreeData = this.getDetailTemplate(row.category)
            this.detailDialogVisible = true
        },
        getDetailTemplate() {
            return JSON.parse(JSON.stringify(this.detailTemplates.default))
        },
        handleAddRoot() {
            this.pendingAddNode = { parent: null, data: null }
            this.addDialogTitle = `${this.currentCategory}添加`
            this.newNodeName = ''
            this.addDialogVisible = true
        },
        openAddNodeDialog(node, data) {
            this.pendingAddNode = { parent: node, data }
            this.addDialogTitle = `${data.label}添加`
            this.newNodeName = ''
            this.addDialogVisible = true
        },
        confirmAddNode() {
            const name = this.newNodeName.trim()
            if (!name) {
                this.$message.warning('名称不能为空')
                return
            }
            const id = `${Date.now()}`
            if (this.pendingAddNode && this.pendingAddNode.data) {
                const { data } = this.pendingAddNode
                const children = data.children || []
                children.push({
                    id: `${data.id}-${id}`,
                    label: name,
                    children: []
                })
                this.$set(data, 'children', children)
            } else {
                this.detailTreeData.push({
                    id: `root-${id}`,
                    label: name,
                    children: []
                })
            }
            this.$message.success('添加成功')
            this.addDialogVisible = false
        },
        cancelAddNode() {
            this.addDialogVisible = false
        },
        resetAddDialog() {
            this.newNodeName = ''
            this.pendingAddNode = null
        },
        handleDeleteNode(node, data) {
            this.$confirm(`确定删除【${data.label}】吗？`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                const parent = node.parent
                const children = parent.data.children || parent.data
                const index = children.findIndex((item) => item.id === data.id)
                if (index !== -1) {
                    children.splice(index, 1)
                }
                this.$message.success('删除成功')
            }).catch(() => {})
        },
        handleSaveDetail() {
            this.$message.success('保存成功')
            this.detailDialogVisible = false
        },
        handleCancelDetail() {
            this.detailDialogVisible = false
        },
        resetDetailDialog() {
            this.currentCategory = ''
            this.detailTreeData = []
        }
    }
}
</script>

<style scoped>
.coentent {
    width: 100%;
    height: 100%;
    background: white;
}

.contents-area {
    width: 100%;
    margin-top: 20px;
}

.areas {
    width: 97%;
    margin: 0 auto;
   
}

.headers {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    padding-top: 18px;
}

.headers-left {
    display: flex;
    align-items: center;
    gap: 20px;
}

.headers-name {
    font-size: 15px;
    color: #17192C;
}

.headers-count {
    display: flex;
    align-items: baseline;
    gap: 6px;
    color: #5165F7;
}

.count-label {
    font-size: 12px;
    color: #979BBC;
}

.count-value {
    font-size: 20px;
    font-weight: bold;
}

.headers-right {
    display: flex;
    align-items: center;
    gap: 12px;
}

.search-input {
    width: 200px;
}

.search-btn {
    padding: 0 18px;
}

.content-table {
    background: #fff;

    border-radius: 8px;

}

.link-btn {
    color: #5165F7;
}

.footer {
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;
}

::v-deep .dictionary-row td {
    color: #363636;
}

::v-deep .el-table__body tr:hover > td {
    background-color: #F7F8FF !important;
}

.dictionary-dialog ::v-deep .el-dialog {
    border-radius: 8px;
}

.dictionary-dialog ::v-deep .el-dialog__header {
    padding: 18px 24px;
    border-bottom: 1px solid #EBEEF5;
}

.dictionary-dialog ::v-deep .el-dialog__body {
    padding: 0 24px 24px;
}

.dictionary-dialog ::v-deep .el-dialog__footer {
    padding: 12px 24px 20px;
    border-top: 1px solid #EBEEF5;
}

.dialog-title {
    font-size: 16px;
    font-weight: bold;
    color: #17192C;
}

.dialog-content {
    background: #fff;
    padding-top: 24px;
}

.dialog-section {
    border: 1px solid #E5E7F5;
    border-radius: 8px;
    background: #F9FAFF;
}

.section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 14px 18px;
    border-bottom: 1px solid #E5E7F5;
    background: #F0F2FF;
    border-top-left-radius: 8px;
    border-top-right-radius: 8px;
}

.section-title {
    font-size: 14px;
    font-weight: 600;
    color: #363636;
}

.dictionary-tree {
    background: #fff;
    padding: 16px 18px;
    border-bottom-left-radius: 8px;
    border-bottom-right-radius: 8px;
}

.tree-node {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    width: 100%;
    padding-right: 12px;
}

.node-content {
    display: flex;
    align-items: center;
    gap: 8px;
    color: #363636;
}

.node-buttons {
    display: flex;
    align-items: center;
    gap: 8px;
}

.node-btn {
    width: 16px;
    height: 16px;
    border-radius: 4px;
    border: 1px solid transparent;
    font-size: 14px;
    font-weight: 600;
    line-height: 16px;
    text-align: center;
    cursor: pointer;
    color: inherit;
    padding: 0;
    background: #fff;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.04);
    transition: all 0.15s ease;
}

.node-btn-add {
    color: #5165F7;
    border-color: #DCE0FD;
}

.node-btn-remove {
    color: #F56C6C;
    border-color: #FADBD8;
}

.node-btn-add:hover {
    background: #EEF1FF;
    border-color: #C7D0FE;
}

.node-btn-remove:hover {
    background: #FDF0EF;
    border-color: #F8C7C2;
}

.node-btn:focus {
    outline: none;
    box-shadow: 0 0 0 2px rgba(81, 101, 247, 0.12);
}

.node-btn:active {
    transform: scale(0.96);
}

.node-prefix {
    color: #B8BBD9;
}

.node-label {
    font-size: 13px;
}

.node-actions {
    text-align: center;
}

.dialog-footer .el-button + .el-button {
    margin-left: 16px;
}

.dictionary-add-dialog ::v-deep .el-dialog {
    border-radius: 12px;
}

.dictionary-add-dialog ::v-deep .el-dialog__header {
    padding: 20px 24px 12px;
}

.dictionary-add-dialog ::v-deep .el-dialog__body {
    padding: 10px 40px 0;
}

.dictionary-add-dialog ::v-deep .el-dialog__footer {
    padding: 24px 40px 30px;
}

.add-dialog-title {
    font-size: 18px;
    font-weight: 600;
    color: #17192C;
    text-align: center;
}

.add-dialog-body {
    margin-top: 20px;
}

.add-dialog-footer {
    text-align: center;
}

.add-dialog-footer .el-button + .el-button {
    margin-left: 16px;
}

::v-deep .el-tree-node__content {
    height: 40px;
}

::v-deep .el-tree-node__content:hover {
    background: rgba(81, 101, 247, 0.05);
}
</style>