<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 roles" :key="index" :label="item.name" :value="item.uuid"></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="name" 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"></el-table-column>
            <el-table-column prop="update_by.username" label="更新者" width="150"></el-table-column>
            <el-table-column label="操作" align="center" width="180" fixed="right">
                <template slot-scope="scope">
                    <el-button size="mini" type="success" :disabled="hasPermission" @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="120px">
                <el-form-item label="角色名称" prop="name">
                    <el-input type="text" v-model="post.name" :disabled="post.is_system" autocomplete="off" placeholder="请输入角色名称"></el-input>
                </el-form-item>
                <el-divider content-position="left">操作权限</el-divider>
                <el-form-item label="基础信息权限" prop="permission">
                    <el-radio-group v-model="post.permission.basic" size="mini">
                        <el-radio-button label="可读"></el-radio-button>
                        <el-radio-button label="可读写"></el-radio-button>
                        <el-radio-button label="无权限"></el-radio-button>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="流程管理权限" prop="permission">
                    <el-radio-group v-model="post.permission.flow" size="mini">
                        <el-radio-button label="可读"></el-radio-button>
                        <el-radio-button label="可读写"></el-radio-button>
                        <el-radio-button label="无权限"></el-radio-button>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="回款计划权限" prop="permission">
                    <el-radio-group v-model="post.permission.paybackPlan" size="mini">
                        <el-radio-button label="可读"></el-radio-button>
                        <el-radio-button label="可读写"></el-radio-button>
                        <el-radio-button label="无权限"></el-radio-button>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="回款进度权限" prop="permission">
                    <el-radio-group v-model="post.permission.paybackProgress" size="mini">
                        <el-radio-button label="可读"></el-radio-button>
                        <el-radio-button label="可读写"></el-radio-button>
                        <el-radio-button label="无权限"></el-radio-button>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="技术资源库权限" prop="permission">
                    <el-radio-group v-model="post.permission.techResources" size="mini">
                        <el-radio-button label="可读"></el-radio-button>
                        <el-radio-button label="可读写"></el-radio-button>
                        <el-radio-button label="无权限"></el-radio-button>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="技术日历权限" prop="permission">
                    <el-radio-group v-model="post.permission.calendar" size="mini">
                        <el-radio-button label="可读"></el-radio-button>
                        <el-radio-button label="可读写"></el-radio-button>
                        <el-radio-button label="无权限"></el-radio-button>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="用户管理权限" prop="permission">
                    <el-radio-group v-model="post.permission.users" size="mini">
                        <el-radio-button label="可读"></el-radio-button>
                        <el-radio-button label="可读写"></el-radio-button>
                        <el-radio-button label="无权限"></el-radio-button>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="角色管理权限" prop="permission">
                    <el-radio-group v-model="post.permission.roles" size="mini">
                        <el-radio-button label="可读"></el-radio-button>
                        <el-radio-button label="可读写"></el-radio-button>
                        <el-radio-button label="无权限"></el-radio-button>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="部门管理权限" prop="permission">
                    <el-radio-group v-model="post.permission.depots" size="mini">
                        <el-radio-button label="可读"></el-radio-button>
                        <el-radio-button label="可读写"></el-radio-button>
                        <el-radio-button label="无权限"></el-radio-button>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="人员资质预警" prop="permission">
                    <el-radio-group v-model="post.permission.personQualification" size="mini">
                        <el-radio-button label="可读"></el-radio-button>
                        <el-radio-button label="可读写"></el-radio-button>
                        <el-radio-button label="无权限"></el-radio-button>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="设备资质预警" prop="permission">
                    <el-radio-group v-model="post.permission.equipmentQualification" size="mini">
                        <el-radio-button label="可读"></el-radio-button>
                        <el-radio-button label="可读写"></el-radio-button>
                        <el-radio-button label="无权限"></el-radio-button>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="公司资质预警" prop="permission">
                    <el-radio-group v-model="post.permission.companyQualification" size="mini">
                        <el-radio-button label="可读"></el-radio-button>
                        <el-radio-button label="可读写"></el-radio-button>
                        <el-radio-button label="无权限"></el-radio-button>
                    </el-radio-group>
                </el-form-item>
                <el-divider content-position="left">数据范围</el-divider>
                <el-form-item label="项目数据范围" prop="permission">
                    <el-radio-group v-model="post.permission.dataScope" size="mini">
                        <el-radio-button label="自己的"></el-radio-button>
                        <el-radio-button label="部门的"></el-radio-button>
                        <el-radio-button label="公司的"></el-radio-button>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="预警数据范围" prop="permission">
                    <el-radio-group v-model="post.permission.warningDataScope" size="mini">
                        <el-radio-button label="自己的"></el-radio-button>
                        <el-radio-button label="部门的"></el-radio-button>
                        <el-radio-button label="公司的"></el-radio-button>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="日历数据范围" prop="permission">
                    <el-radio-group v-model="post.permission.calendarDataScope" size="mini">
                        <el-radio-button label="自己的"></el-radio-button>
                        <el-radio-button label="部门的"></el-radio-button>
                        <el-radio-button label="公司的"></el-radio-button>
                    </el-radio-group>
                </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 { mapState, mapGetters } from "vuex";
import { getRoleList, deleteRole, updateRole, addRole } from '@/api/index'
import checkPermission from '@/utils/permission'
import { mapTrim, compareObjectDiff } from '@/utils/index'

export default {
    data() {
        return {
            total: 0,
            list: [],
            isLoading: false,
            roles: [],
            form: {
                uuid: null,
                name: null,
                pagesize: 15,
                pagenum: 1
            },
            dialogTitle: "",
            dialogVisible: false,
            currentValue: null,
            currentIndex: null,
            post: {
                name: null,
                permission: {
                    basic: '无权限',
                    flow: '无权限',
                    users: '无权限',
                    roles: '无权限',
                    depots: '无权限',
                    paybackPlan: '无权限',
                    paybackProgress: '无权限',
                    personQualification: "无权限",
                    equipmentQualification: "无权限",
                    companyQualification: "无权限",
                    techResources: "无权限",
                    calendar: "无权限",
                    dataScope: "自己的",
                    warningDataScope: "自己的",
                    calendarDataScope: "自己的",
                },
                is_system: false
            },
            rules: {
                name: [
                    { type: 'string', required: true, message: '用户名不能为空', trigger: 'blur' },
                    { min: 1, max: 20, message: '字符串长度在 1 到 20 之间', trigger: 'blur' }
                ],
                permission: [{ type: 'object', required: true, message: '权限不能为空', trigger: 'blur' }]
            }
        }
    },
    computed: {
        ...mapState("user", [ "avatar", ]),
        ...mapGetters([ "role", ]),
        hasPermission: () => JSON.parse(sessionStorage.getItem("user")).role.name === "超级管理员" ? false : true,
    },
    methods: {
        checkPermission,
        fetchData(params) {
            this.isLoading = true
            getRoleList(Object.assign({
                pagenum: this.form.pagenum,
                pagesize: this.form.pagesize,
            }, params)).then(res => {
                this.total = res.count
                this.list = res.data
            }).catch(err => {
                // this.$message.error(err.message)
                console.log(err.message)
            }).finally(() => {
                this.isLoading = false
            })
        },
        fetchSelectData() {
            getRoleList({ "scope_type": "list" }).then(res => {
                if (res.code == 200) this.roles = 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) {
            if (row.is_system && this.hasPermission) return this.$message.error("系统内置角色，无法修改")
            if (row.permission.basic) this.post.permission.basic = row.permission.basic
            if (row.permission.dataScope) this.post.permission.dataScope = row.permission.dataScope
            if (row.permission.flow) this.post.permission.flow = row.permission.flow
            if (row.permission.users) this.post.permission.users = row.permission.users
            if (row.permission.roles) this.post.permission.roles = row.permission.roles
            if (row.permission.depots) this.post.permission.depots = row.permission.depots
            if (row.permission.paybackPlan) this.post.permission.paybackPlan = row.permission.paybackPlan
            if (row.permission.paybackProgress) this.post.permission.paybackProgress = row.permission.paybackProgress
            if (row.permission.personQualification) this.post.permission.personQualification = row.permission.personQualification
            if (row.permission.equipmentQualification) this.post.permission.equipmentQualification = row.permission.equipmentQualification
            if (row.permission.companyQualification) this.post.permission.companyQualification = row.permission.companyQualification
            if (row.permission.techResources) this.post.permission.techResources = row.permission.techResources
            if (row.permission.calendar) this.post.permission.calendar = row.permission.calendar
            if (row.permission.calendarDataScope) this.post.permission.calendarDataScope = row.permission.calendarDataScope
            if (row.permission.warningDataScope) this.post.permission.warningDataScope = row.permission.warningDataScope
            this.post.name = row.name
            this.post.is_system = row.is_system
            this.currentValue = row
            this.currentIndex = index
            this.dialogTitle = "编辑"
            this.dialogVisible = true
        },
        handleDelete(index, row) {
            if (row.is_system) return this.$message.error("系统内置角色，无法删除")
            this.$alert('您确定要删除么？删除操作将不可恢复。如需取消操作，请点击右上角关闭按钮。', '删除提醒', {
                confirmButtonText: '确定',
                callback: action => {
                    if (action == 'confirm') deleteRole(row.uuid).then(res => {
                        console.log(res)
                        this.total -= 1
                        this.$delete(this.list, index)
                        this.$message({ type: 'success', message: `成功删除第${ index }行` })
                        this.fetchData()
                    }).catch(err => {
                        this.$message.error(err.message)
                    })
                }
            })
        },
        submitForm(formName) {
            this.$refs[formName].validate((valid) => {
                let result = true
                if (valid) {
                    if (this.dialogTitle === '添加') addRole(this.post).then(res => {
                        console.log(res)
                        this.$message({ type: 'success', message: '添加成功' })
                        this.fetchData()
                    }).catch(err => {
                        this.$message.error(err.message)
                    })
                    else if (this.dialogTitle === '编辑') updateRole(this.currentValue.uuid, compareObjectDiff(this.post, this.currentValue)).then(res => {
                        console.log(res)
                        this.$message({ type: 'success', message: '更新成功' })
                        this.fetchData()
                    }).catch(err => {
                        this.$message.error(err.message)
                    })
                } else {
                    result = false
                }
                this.dialogVisible = false
                return result
            })
        },
        onAdd() {
            this.dialogTitle = "添加"
            this.dialogVisible = true
        },
        onSubmit() {
            this.form.pagenum = 1
            this.form.pagesize = 15
            this.fetchData(mapTrim(this.form))
        },
        onReset(formName) {
            this.form = {
                account: null,
                username: null,
                pagesize: 15,
                pagenum: 1
            }
            this.$refs[formName].resetFields()
            this.fetchData()
        }
    },
    mounted() {},
    created() {
        this.fetchData()
        this.fetchSelectData()

        const user = JSON.parse(sessionStorage.getItem("user"))
        if (!user || user.role.permission.roles == "无权限") this.$router.push("/403")
    }
}
</script>
<style lang="scss" scoped>
.app-container {
    & > div.page-wrapper {
        margin: 10px 0px;
    }
}
</style>
