<template>
    <!-- 类型管理 -->
    <div class="app-container" id="toolsType">
        <el-row :gutter="20">
            <!--左侧树数据-->
            <el-col :span="6" :xs="24">
                <div
                    class="head-container"
                    style="
                        display: flex;
                        justify-content: space-between;
                        align-items: center;
                        margin-bottom: 20px;
                    "
                >
                    <el-input
                        v-model="contentName"
                        placeholder="请输入类型名称"
                        clearable
                        maxlength="50"
                        size="small"
                        prefix-icon="el-icon-search"
                        style="width: 75%"
                    />
                    <el-button
                        type="primary"
                        icon="el-icon-plus"
                        size="mini"
                        @click="handleAddNewNode"
                        style="width: 20%"
                        >新增
                    </el-button>
                </div>
                <div class="head-container" style>
                    <el-tree
                        style="height: 700px; overflow: scroll"
                        :data="treeOptions"
                        :props="defaultProps"
                        :expand-on-click-node="false"
                        :filter-node-method="filterNode"
                        ref="tree"
                        node-key="id"
                        :default-expand-all="true"
                        highlight-current
                        @node-click="handleNodeClick"
                    >
                        <span
                            class="custom-tree-node"
                            slot-scope="{ node, data }"
                            @mousemove="onMousemove(data)"
                            @mouseleave="onMouseleave()"
                        >
                            <span
                                v-if="
                                    isMousemoveId === data.id &&
                                    node.label.length > 5
                                "
                                >{{ node.label.slice(0, 3) + '...' }}</span
                            >
                            <span v-else>{{ node.label }}</span>

                            <span
                                class="btn-items"
                                v-if="isMousemoveId === data.id"
                            >
                                <el-button
                                    v-if="data.level < 3"
                                    type="text"
                                    size="mini"
                                    icon="el-icon-plus"
                                    @click.stop="() => appendTreeNode(data)"
                                >
                                </el-button>
                                <el-button
                                    type="text"
                                    size="mini"
                                    icon="el-icon-edit-outline"
                                    style="color: #67c23a"
                                    v-if="data.id !== 0"
                                    @click.stop="() => editTreeNode(data)"
                                >
                                </el-button>
                                <el-button
                                    type="text"
                                    size="mini"
                                    icon="el-icon-delete"
                                    style="color: #f56c6c"
                                    v-if="data.id !== 0 && data.level !== 0"
                                    @click.stop="() => removeTreeNode(data)"
                                >
                                </el-button>
                            </span>
                        </span>
                    </el-tree>
                </div>
            </el-col>
            <!--右侧-->
            <el-col :span="18" :xs="24">
                <el-form
                    :model="queryParams"
                    ref="queryForm"
                    size="small"
                    :inline="true"
                    v-show="showSearch"
                    label-width="68px"
                    @submit.native.prevent
                >
                    <el-form-item label="" prop="contentName">
                        <el-input
                            v-model="queryParams.contentName"
                            placeholder="请输入类型名称"
                            clearable
                            style="width: 240px"
                            @keyup.enter.native="handleQuery"
                        />
                    </el-form-item>

                    <el-form-item>
                        <el-button
                            type="primary"
                            icon="el-icon-search"
                            size="mini"
                            @click="handleQuery"
                            >查询
                        </el-button>
                        <el-button
                            icon="el-icon-refresh"
                            size="mini"
                            @click="resetQuery"
                            >重置
                        </el-button>
                    </el-form-item>
                </el-form>

                <el-row :gutter="10" class="mb8">
                    <el-col :span="1.5">
                        <el-button
                            type="primary"
                            icon="el-icon-plus"
                            size="mini"
                            :disabled="!nodeId"
                            @click="handleAdd"
                            >新增
                        </el-button>
                    </el-col>
                    <!-- <el-col :span="1.5">
                        <el-button
                            type="warning"
                            plain
                            icon="el-icon-download"
                            size="mini"
                            @click="handleExport"
                            >导出
                        </el-button>
                    </el-col> -->
                    <right-toolbar
                        :showSearch.sync="showSearch"
                        @queryTable="getList"
                    ></right-toolbar>
                </el-row>

                <el-table v-loading="loading" :data="typeList" border>
                    <el-table-column
                        label="序号"
                        align="center"
                        width="80"
                        type="index"
                    >
                        <template slot-scope="scope">
                            <span>{{
                                (queryParams.pageNum - 1) * 10 +
                                scope.$index +
                                1
                            }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column
                        label="文件名称"
                        align="center"
                        key="contentName"
                        prop="contentName"
                        show-overflow-tooltip
                    />
                    <el-table-column
                        label="案卷期限"
                        align="center"
                        key="term"
                        prop="term"
                        show-overflow-tooltip
                    />
                    <el-table-column
                        label="档案标识代码"
                        align="center"
                        key="markCode"
                        prop="markCode"
                        show-overflow-tooltip
                    />
                    <el-table-column
                        label="所属专业"
                        align="center"
                        key="major"
                        prop="major"
                        show-overflow-tooltip
                    />
                    <el-table-column
                        label="文件分类标记"
                        align="center"
                        key="classifyMark"
                        prop="classifyMark"
                        show-overflow-tooltip
                    />

                    <el-table-column label="操作" align="center" width="180">
                        <template slot-scope="scope">
                            <el-button
                                size="mini"
                                type="text"
                                icon="el-icon-warning-outline"
                                @click="handleView(scope.row)"
                                style="color: #2b938d"
                            >
                                详情
                            </el-button>
                            <el-button
                                size="mini"
                                type="text"
                                icon="el-icon-edit"
                                @click="handleUpdate(scope.row)"
                            >
                                编辑
                            </el-button>
                            <el-button
                                size="mini"
                                type="text"
                                icon="el-icon-delete"
                                @click="handleDelete(scope.row)"
                                style="color: #f56c6c"
                            >
                                删除
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <pagination
                    v-show="total > 0"
                    :total="total"
                    :page.sync="queryParams.pageNum"
                    :limit.sync="queryParams.pageSize"
                    @pagination="getList"
                />
            </el-col>
        </el-row>

        <!-- 新增/编辑-分类弹框 -->
        <el-dialog
            :title="addTitle"
            :visible.sync="addTitleVisible"
            v-if="addTitleVisible"
            width="50%"
            append-to-body
            :close-on-click-modal="false"
            v-loading="loading"
        >
            <el-form
                label-width="120px"
                :model="addFormParams"
                :rules="addFormParamsRules"
                ref="addFormParamsRef"
            >
                <el-row :gutter="24">
                    <el-col :span="24">
                        <el-form-item
                            label="上级节点"
                            prop="nodeId"
                            v-if="isNew"
                        >
                            <treeselect
                                v-model="addFormParams.nodeId"
                                :options="treeOptions"
                                :normalizer="normalizer"
                                show-count
                                noChildrenText="没有数据了"
                                noOptionsText="没有数据了"
                                noResultsText="没有搜索结果"
                                placeholder="请选择节点"
                                @select="selectNode"
                                style="width: 100%"
                            />
                        </el-form-item>
                        <el-form-item label="上级节点" v-else>
                            <el-input
                                style="width: 100%"
                                disabled
                                v-model="addFormParams.label"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="分类名称" prop="contentName">
                            <el-input
                                style="width: 100%"
                                v-model="addFormParams.contentName"
                                placeholder="请输入"
                                clearable
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="分类号" prop="sort">
                            <el-input-number
                                style="width: 100%"
                                v-model="addFormParams.sort"
                                placeholder="请输入"
                                clearable
                                :min="0"
                                :precision="0"
                                controls-position="right"
                            />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button
                    size="small"
                    type="primary"
                    style="color: #fff"
                    @click="onSubmit"
                    >确 定</el-button
                >
                <el-button size="small" @click="onCancel">取 消</el-button>
            </span>
        </el-dialog>

        <el-dialog
            :visible.sync="dialogVisible"
            v-if="dialogVisible"
            width="50%"
            :close-on-click-modal="false"
            v-loading="loading"
            :title="title"
        >
            <el-form
                label-width="120px"
                :model="addFormDetails"
                :rules="addFormDetailsRules"
                ref="formDetails"
                :disabled="isView"
            >
                <el-form-item label="所属案卷" prop="parentName">
                    <el-input
                        v-model="addFormDetails.parentName"
                        placeholder="请输入所属案卷"
                        disabled
                    />
                </el-form-item>
                <el-form-item label="文件题名" prop="contentName">
                    <el-input
                        v-model="addFormDetails.contentName"
                        placeholder="请输入文件题名"
                        maxlength="100"
                    />
                </el-form-item>
                <el-form-item label="保管期限" prop="term">
                    <el-input
                        v-model="addFormDetails.term"
                        placeholder="请输入保管期限"
                        maxlength="100"
                    />
                </el-form-item>
                <el-form-item label="归档责任单位" prop="unitName">
                    <el-input
                        v-model="addFormDetails.unitName"
                        placeholder="请输入归档责任单位"
                        maxlength="100"
                    />
                </el-form-item>
                <el-form-item label="所属专业" prop="major">
                    <el-input
                        v-model="addFormDetails.major"
                        placeholder="请输入所属专业"
                        maxlength="100"
                    />
                </el-form-item>
                <el-form-item label="档案标识代码" prop="markCode">
                    <el-select
                        v-model="addFormDetails.markCode"
                        placeholder="请选择档案标识代码"
                        style="width: 100%"
                    >
                        <el-option
                            v-for="item in markCodeList"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="文件分类标记" prop="classifyMark">
                    <el-select
                        v-model="addFormDetails.classifyMark"
                        placeholder="请选择文件分类标记"
                        style="width: 100%"
                    >
                        <el-option
                            v-for="item in classifyMarkList"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        />
                    </el-select>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button
                    v-if="!isView"
                    size="small"
                    type="primary"
                    style="color: #fff"
                    @click="submitForm"
                    >确 定</el-button
                >
                <el-button size="small" @click="dialogVisible = false">{{
                    isView ? '关 闭' : '取 消'
                }}</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import {
    getArchivalCatalogueTreeApi,
    addArchiveApi,
    putArchiveApi,
    delArchiveApi,
    getArchivalCatalogueByIdApi,
    getArchivalCatalogueListApi,
} from '@/api/archivesManagement'

export default {
    name: 'ArchCatalogue',
    components: { Treeselect },
    data() {
        return {
            // 遮罩层
            loading: false,
            isSubmit: false,
            // 显示搜索条件
            showSearch: true,
            // 类型名称
            contentName: undefined,
            // 树选项
            treeOptions: [],
            //列表数据
            typeList: [],
            total: 0,
            parentId: undefined,
            defaultProps: {
                children: 'children',
                label: 'contentName',
            },
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                parentId: null,
                contentName: null,
            },
            // 弹框参数
            isAdd: true,
            isView: false,
            addFormDetails: {
                parentId: '', // 所属案卷id
                parentName: '', // 所属案卷
                level: 4,
                contentName: '', // 文件题名
                term: '', // 保管期限
                unitName: '', // 归档责任单位
                major: '', // 所属专业
                markCode: '', // 档案标识代码
                classifyMark: '', // 文件分类标记
            },
            addFormDetailsRules: {
                contentName: [
                    {
                        required: true,
                        message: '请输入文件题名',
                        trigger: 'blur',
                    },
                ],
                term: [
                    {
                        required: true,
                        message: '请输入保管期限',
                        trigger: 'blur',
                    },
                ],
                unitName: [
                    {
                        required: true,
                        message: '请选择归档责任单位',
                        trigger: 'change',
                    },
                ],
                major: [
                    {
                        required: true,
                        message: '请输入所属专业',
                        trigger: 'change',
                    },
                ],
            },
            markCodeList: [],
            classifyMarkList: [],
            title: '', // 弹出层标题
            dialogVisible: false,
            /* 新增弹框等数据源定义 */
            isNew: false,
            addTitleVisible: false,
            addTitle: '', // 新增弹框标题
            addFormParams: {
                label: '',
                contentName: '',
                sort: '',
            },
            addFormParamsRules: {
                nodeId: [
                    {
                        required: true,
                        message: '上级节点不能为空',
                        trigger: 'change',
                    },
                ],
                contentName: [
                    {
                        required: true,
                        message: '名称不能为空',
                        trigger: 'blur',
                    },
                ],
                sort: [
                    {
                        required: true,
                        message: '分类号不能为空',
                        trigger: 'blur',
                    },
                ],
            },
            isMousemoveId: null,
            nodeId: null,
            nodeName: null,
        }
    },
    watch: {
        // 根据名称筛选部门树
        contentName(val) {
            this.$refs.tree.filter(val)
        },
    },
    created() {
        this.getTreeData()
    },
    methods: {
        selectNode(data) {
            console.log('🚀 ~ selectNode ~ data:', data)
            this.addFormParams.level = data.level + 1
            this.addFormParams.parentId = data.id
        },
        normalizer(node) {
            console.log('🚀 ~ normalizer ~ node:', node)
            if (node.children && !node.children.length) {
                delete node.children
            }
            return {
                id: node.id,
                label: node.contentName,
                children: node.children,
            }
        },
        /** 查询新增页面-上级类型下拉树结构 */
        getTreeData() {
            getArchivalCatalogueTreeApi().then((response) => {
                this.treeOptions = response.data
                console.log(
                    '🚀 ~ getTreeData ~ this.treeOptions:',
                    this.treeOptions,
                )
            })
        },
        /** 查询列表 */
        getList() {
            this.loading = true
            console.log('🚀 ~ getList ~ this.queryParams:', this.queryParams)
            getArchivalCatalogueListApi(this.queryParams)
                .then((res) => {
                    this.loading = false
                    if (!res.rows) return
                    this.typeList = res.rows || []
                    this.total = res.total || 0
                })
                .catch(() => {
                    this.loading = false
                })
        },
        // 筛选节点 - 左侧树
        filterNode(value, data) {
            if (!value) return true
            return data.contentName.indexOf(value) !== -1
        },
        // 节点单击事件 - 左侧树
        async handleNodeClick(data, node) {
            console.log('🚀 ~ handleNodeClick ~ data:', data)
            this.nodeId = data.level == 3 ? data.id : null
            this.nodeName = data.level == 3 ? data.contentName : null
            this.queryParams.parentId = data.level == 3 ? data.id : null

            if (data.level == 3) {
                this.getList()
            }
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1
            this.queryParams.pageSize = 10
            this.getList()
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm('queryForm')
            this.queryParams.pageNum = 1
            this.queryParams.pageSize = 10
            this.getList()
        },
        //查看
        handleView(row) {
            this.isAdd = false
            this.isView = true
            console.log('🚀 ~ handleView ~ row:', row)
            this.dialogVisible = true
            this.title = '查看卷内文件'
            setTimeout(() => {
                this.$refs.formDetails.resetFields()
                this.getInfo(row.id)
            }, 300)
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.isAdd = true
            this.isView = false
            this.dialogVisible = true
            this.title = '新增卷内文件'
            setTimeout(() => {
                this.$refs.formDetails.resetFields()
                this.addFormDetails.parentId = this.nodeId
                this.addFormDetails.parentName = this.nodeName
                console.log('🚀 ~ parentName:', this.addFormDetails.parentName)
            }, 300)
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            console.log('🚀 ~ handleUpdate ~ row:', row)
            this.isAdd = false
            this.isView = false
            this.dialogVisible = true
            this.title = '修改卷内文件'
            setTimeout(() => {
                this.$refs.formDetails.resetFields()
                this.getInfo(row.id)
            }, 300)
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            this.$modal
                .confirm('是否确认删除数据项？')
                .then(async () => {
                    try {
                        this.isLoading = true
                        await delArchiveApi({ id: row.id })
                        this.$modal.msgSuccess('删除成功')
                    } catch (error) {
                        console.log('🚀 ~ handleDelete ~ error:', error)
                    } finally {
                        this.isLoading = false
                        this.getList()
                    }
                })
                .catch(() => {})
        },
        /** 提交按钮 */
        submitForm() {
            this.$refs['formDetails'].validate(async (valid) => {
                if (!valid) return
                try {
                    if (this.isSubmit) return
                    this.isSubmit = true
                    this.isLoading = true
                    const params = { ...this.addFormDetails }
                    console.log('🚀 ~ submitForm ~ params:', params)
                    if (this.isAdd) {
                        await addArchiveApi(params)
                    } else {
                        await putArchiveApi(params)
                    }

                    this.$message({
                        message: '添加成功',
                        type: 'success',
                    })
                } catch (error) {
                    console.log('🚀 ~ submitForm ~ error:', error)
                } finally {
                    this.isLoading = false
                    this.isSubmit = false
                    this.dialogVisible = false
                    this.getList()
                }
            })
        },
        /** 导出按钮作 */
        handleExport() {
            const formatTime = (date) => {
                const year = date.getFullYear()
                const month = String(date.getMonth() + 1).padStart(2, '0')
                const day = String(date.getDate()).padStart(2, '0')
                const hours = String(date.getHours()).padStart(2, '0')
                const minutes = String(date.getMinutes()).padStart(2, '0')
                const seconds = String(date.getSeconds()).padStart(2, '0')
                return `${year}${month}${day}_${hours}${minutes}${seconds}`
            }

            const currentTime = formatTime(new Date())
            let queryTemp = this.queryParams
            // queryTemp.level = 0;
            this.download(
                '/export',
                {
                    ...queryTemp,
                },
                `导出_${currentTime}.xlsx`,
            )
        },
        async getInfo(id) {
            try {
                const { data } = await getArchivalCatalogueByIdApi({ id })
                this.addFormParams = { ...data }
                this.addFormParams.label = data.parentName
                this.addFormDetails = { ...data }
            } catch (error) {
                console.log('🚀 ~ getInfo ~ error:', error)
            }
        },
        handleAddNewNode() {
            this.isNew = true
            this.addFormParams = {
                label: '',
                contentName: '',
                sort: '',
                nodeId: null,
            }
            this.addTitle = '新增分类'
            this.addTitleVisible = true
        },
        /* 树节点增加 */
        appendTreeNode(data) {
            console.log('dataAdd', data)
            this.isNew = false
            this.addFormParams.sort = null
            this.addFormParams.contentName = ''
            this.addFormParams.nodeId = data.id
            this.addFormParams.level = data.level + 1
            this.addFormParams.parentId = data.id
            this.addFormParams.label = data.contentName || ''
            console.log(
                '🚀 ~ appendTreeNode ~ this.addFormParams:',
                this.addFormParams,
            )
            this.addTitle = '新增分类'
            this.addTitleVisible = true
        },
        /* 树节点修改 */
        editTreeNode(data) {
            this.isNew = false
            this.addTitle = '修改分类'
            this.addTitleVisible = true
            this.getInfo(data.id)
        },
        /* 树节点删除 */
        removeTreeNode(data) {
            console.log('🚀 ~ removeTreeNode ~ data:', data)
            this.$modal
                .confirm('是否确认删除数据项？')
                .then(function () {
                    return delArchiveApi({ id: data.id })
                })
                .then(() => {
                    this.$modal.msgSuccess('删除成功')
                    this.getTreeData()
                })
                .catch(() => {})
        },
        /* 确定 */
        onSubmit() {
            console.log(
                '🚀 ~ onSubmit ~ this.addFormParams:',
                this.addFormParams,
            )

            const params = {
                id: this.addFormParams.id || '',
                parentId: this.addFormParams.parentId,
                contentName: this.addFormParams.contentName,
                sort: this.addFormParams.sort,
                level: this.addFormParams.level,
            }

            this.$refs['addFormParamsRef'].validate(async (valid) => {
                if (valid) {
                    try {
                        if (this.isSubmit) return
                        this.isSubmit = true
                        this.isLoading = true
                        if (this.addTitle === '新增分类') {
                            await addArchiveApi(params)
                            this.$message.success('新增成功！')
                        } else {
                            await putArchiveApi(params)
                            this.$message.success('修改成功！')
                        }
                    } catch (error) {
                        console.log('🚀 ~ onSubmit ~ error:', error)
                    } finally {
                        this.isLoading = false
                        this.isSubmit = false
                        this.addTitleVisible = false
                        this.getTreeData()
                        // this.getList()
                    }
                }
            })
        },
        /* 取消 */
        onCancel() {
            this.addTitleVisible = false
        },
        onMousemove(data) {
            this.isMousemoveId = data.id
        },
        onMouseleave() {
            this.isMousemoveId = null
        },
    },
}
</script>
<style lang="scss" scoped>
::v-deep.el-table .fixed-width .el-button--mini {
    width: 60px !important;
    margin-bottom: 10px;
}

::v-deep .btn-items .el-button + .el-button {
    margin-left: 6px;
}

.btn-items {
    margin-left: 4px;

    .el-button--text {
        font-size: 16px;
    }
}

::v-deep .el-tree .el-tree-node__expand-icon.expanded {
    -webkit-transform: rotate(0deg);
    transform: rotate(0deg);
}

::v-deep .el-tree .el-icon-caret-right:before {
    content: '\e783';
    font-size: 16px;
}

::v-deep
    .el-tree
    .el-tree-node__expand-icon.expanded.el-icon-caret-right:before {
    content: '\e781';
    font-size: 16px;
    color: #1890ff;
}

::v-deep .el-tree-node__content > .el-tree-node__expand-icon {
    color: #1890ff !important;
}

::v-deep .el-tree-node__expand-icon.is-leaf {
    color: transparent !important;
}

::v-deep
    .el-tree--highlight-current
    .el-tree-node.is-current
    > .el-tree-node__content {
    background-color: #8decf1;
}

::v-deep .el-dialog {
    // 表单标签文字样式
    .el-form-item__label {
        font-size: 14px;
        color: #606266;
        font-weight: 500;
        // line-height: 1.5;
    }

    // 输入框文字样式
    .el-input__inner {
        font-size: 14px;
        color: #303133;

        &::placeholder {
            font-size: 13px;
            color: #c0c4cc;
        }
    }

    // 单位文字样式
    span {
        font-size: 14px;
        // color: #606266;
        margin-left: 8px;
    }

    // 下拉选择框文字样式
    .el-select {
        .el-input__inner {
            font-size: 14px;
            color: #303133;
        }
    }

    // 只读输入框样式
    .el-input.is-disabled .el-input__inner {
        background-color: #f5f7fa;
        border-color: #e4e7ed;
        color: #606266;
        cursor: not-allowed;
    }
}

// 表格内文字样式
::v-deep .el-table {
    font-size: 14px;

    th {
        font-weight: 500;
        color: #303133;
    }

    td {
        color: #606266;
    }
}

// 按钮文字样式
::v-deep .el-button {
    font-size: 14px;

    &--text {
        font-size: 13px;
    }
}

// 树节点文字样式
::v-deep .el-tree-node__label {
    font-size: 14px;
    color: #606266;
}

// 搜索框文字样式
::v-deep .el-input--small {
    .el-input__inner {
        font-size: 13px;

        &::placeholder {
            font-size: 13px;
            color: #c0c4cc;
        }
    }
}

::v-deep .el-dialog .el-input__inner {
    text-align: start !important;
}
</style>
