<template>
    <div class="app-container">
        <el-form :inline="true" :model="form" size="mini">
            <el-form-item label="字典名称">
                <el-select v-model="form.uuid" filterable placeholder="请输入字典名称">
                    <el-option v-for="(item, index) in dicts" :key="index" :label="item.label" :value="item.uuid"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="字典类别">
                <el-select v-model="form.category" filterable placeholder="请输入字典类别">
                    <el-option v-for="(item, index) in categoryList" :key="index" :label="item" :value="item"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item><el-button type="primary" @click="onSubmit">查询</el-button></el-form-item>
            <el-form-item><el-button @click="onReset">重置</el-button></el-form-item>
            <el-form-item><el-button type="warning" @click="onAdd">添加</el-button></el-form-item>
        </el-form>
        <el-table v-loading="isLoading" element-loading-text="Loading" :data="list" size="mini" border stripe fit highlight-current-row>
            <el-table-column prop="label" label="字典名" align="center" width="130" :show-overflow-tooltip="true"></el-table-column>
            <el-table-column prop="value" label="字典值" align="center" width="100" :show-overflow-tooltip="true"></el-table-column>
            <el-table-column prop="category" label="字典类别" align="center" min-width="150" :show-overflow-tooltip="true"></el-table-column>
            <el-table-column prop="is_system" label="是否内置" width="80">
                <template slot-scope="scope">
                    <span>{{ scope.row.is_system ? '是': '否' }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="create_at" label="创建时间" width="150"></el-table-column>
            <el-table-column prop="create_by.username" label="创建者" width="150"></el-table-column>
            <el-table-column prop="update_at" label="更新时间" width="150" :show-overflow-tooltip="true"></el-table-column>
            <el-table-column prop="update_by.username" label="更新者" width="150"></el-table-column>
            <el-table-column prop="remarks" label="备注" width="150" :show-overflow-tooltip="true"></el-table-column>
            <el-table-column label="操作" align="center" width="180" fixed="right">
                <template slot-scope="scope">
                    <el-button size="mini" type="success" :disabled="scope.row.is_system" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                    <el-button size="mini" type="danger" :disabled="scope.row.is_system" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <div class="page-wrapper">
            <el-pagination @current-change="handleCurrentChange" :current-page.sync="form.pagenum" background small :page-size="form.pagesize" :pager-count="5" layout="pager, prev, next, total" :total="total"></el-pagination>
        </div>
        <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="45%">
            <el-form :model="post" status-icon :rules="rules" :inline="true" ref="post" size="mini" label-width="80px">
                <el-form-item label="字典名" prop="label">
                    <el-input type="text" v-model="post.label" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="字典值" prop="value">
                    <el-input type="text" v-model="post.value" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="字典类别" prop="category">
                    <el-input type="text" v-model="post.category" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="排序" prop="sort">
                    <el-input type="number" v-model.number="post.sort" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="备注" prop="remarks">
                    <el-input type="text" v-model="post.remarks" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="是否内置" prop="is_system">
                    <el-switch :disabled="!enableDelete" v-model="post.is_system" @change="onSwitchChange"></el-switch>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" size="mini" plain @click="submitForm('post')">提交</el-button>
                <el-button type="success" size="mini" plain @click="onReset('post')">重置</el-button>
                <el-button size="mini" @click="dialogVisible = false">关闭</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script>
import { getDictsList, deleteDict, addDict, updateDict } from '@/api/index'
import { mapTrim, compareObjectDiff } from '@/utils/index'
import { formatUTCDateTime } from '@/utils/utils'
export default {
    data() {
        return {
            total: 0,
            list: [],
            isLoading: false,
            dicts: [],
            categoryList: [],
            form: {
                uuid: null,
                category: null,
                pagesize: 15,
                pagenum: 1
            },
            dialogTitle: "",
            dialogVisible: false,
            currentValue: null,
            currentIndex: null,
            enableDelete: false,
            post: {
                label: null,
                value: null,
                category: null,
                sort: null,
                remarks: null,
                is_system: null
            },
            rules: {
                label: [{ type: 'string', required: true, message: '字典名不能为空', trigger: 'blur' }],
                value: [{ type: 'string', required: true, message: '字典值不能为空', trigger: 'blur' }],
                category: [{ type: 'string', required: true, message: '字典类别不能为空', trigger: 'blur' }],
                sort: [{ type: 'number', required: false, message: '排序不能为空', trigger: 'blur' }],
                remarks: [{ type: 'string', required: false, message: '备注不能为空', trigger: 'blur' }],
                is_system: [{ type: 'boolean', required: false, message: '能否删除必选', trigger: 'blur' }],
            }
        }
    },
    computed: {
        role: () => this.$store.state.user.role
    },
    methods: {
        fetchCategoryData() {
            getDictsList({ is_category: 1, }).then(res => {
                this.categoryList = res.data
            }).catch(err => {
                // this.$message.error(err.message)
                console.log(err.message)
            })
        },
        fetchData(params) {
            this.isLoading = true
            getDictsList(Object.assign({
                pagenum: this.form.pagenum,
                pagesize: this.form.pagesize,
            }, params)).then(res => {
                if (res.code == 200) {
                    this.total = res.count
                    this.list = res.data.map(item => {
                        item.create_at = formatUTCDateTime(item.create_at)
                        item.update_at = formatUTCDateTime(item.update_at)
                        return item
                    })
                }
            }).catch(err => {
                // this.$message.error(err.message)
                console.log(err.message)
            }).finally(() => {
                this.isLoading = false
            })
        },
        fetchSelectData() {
            getDictsList({ "scope_type": "list" }).then(res => {
                if (res.code == 200) this.dicts = res.data
            }).catch(err => {
                // this.$message.error(err.message)
                console.log(err.message)
            })
        },
        handleSizeChange(e) {
            this.form.pagesize = e
            this.fetchData(mapTrim(this.form))
        },
        handleCurrentChange(e) {
            this.form.pagenum = e
            this.fetchData(mapTrim(this.form))
        },
        handleEdit(index, row) {
            this.post.label = row.label
            this.post.value = row.value
            this.post.category = row.category
            this.post.sort = row.sort
            this.post.remarks = row.remarks
            this.post.is_system = row.is_system
            this.dialogTitle = "编辑"
            this.dialogVisible = true
            this.enableDelete = row.is_system
            this.currentIndex = index
            this.currentValue = row
        },
        handleDelete(index, row) {
            this.$alert('您确定要删除么？删除操作将不可恢复。如需取消操作，请点击右上角关闭按钮。', '删除提醒', {
                confirmButtonText: '确定',
                callback: action => {
                    if (action == 'confirm') deleteDict(row.uuid).then(res => {
                        console.log(res)
                        this.total -= 1
                        this.$delete(this.list, index)
                        this.$message({ type: 'success', message: res.message })
                    }).catch(err => {
                        this.$message.error(err.message)
                    })
                }
            })
        },
        submitForm(formName) {
            this.$refs[formName].validate((valid) => {
                let result = true
                if (valid) {
                    if (this.dialogTitle === '添加') addDict(this.post).then(res => {
                        this.$message({ type: 'success', message: res.message })
                    }).catch(err => {
                        this.$message.error(err.message)
                    })
                    else if (this.dialogTitle === '编辑') updateDict(this.currentValue.uuid, compareObjectDiff(this.post, this.currentValue)).then(res => {
                        // this.$set(this.list, this.currentIndex, Object.assign(this.currentValue, tmp))
                        this.$message({ type: 'success', message: res.message })
                    }).catch(err => {
                        this.$message.error(err.message)
                    })
                } else {
                    result = false
                }
                this.dialogVisible = false
                return result
            })
        },
        onAdd() {
            this.dialogTitle = "添加"
            this.enableDelete = true
            this.dialogVisible = true
        },
        onSubmit() {
            this.form.pagenum = 1
            this.form.pagesize = 15
            this.fetchData(mapTrim(this.form))
        },
        onReset(formName) {
            this.form.uuid = null 
            this.form.category = null
            this.form.pagesize = 15
            this.form.pagenum = 1
            this.$refs[formName].resetFields()
            this.fetchData()
        },
        onSwitchChange() {
            console.log(this.post.is_system)
        }
    },
    mounted() {},
    created() {
        this.fetchData()
        this.fetchSelectData()
        this.fetchCategoryData()

        const user = JSON.parse(sessionStorage.getItem("user"))
        if (!user || user.role.name != "超级管理员") this.$router.push("/403")
    }
}
</script>
<style lang="scss" scoped>
.app-container {
    & > div.page-wrapper {
        margin: 10px 0px;
    }
}
</style>
