<template>
    <div>
        <el-card shadow="always" :style="'height:' + vh + 'px'">
            <div class="clearfix" slot="header">
                <b>
                    <!-- <svg-icon icon-class="" style="color:#fff"/> -->
                    角色列表
                </b>
            </div>
            <el-form ref="queryForm" :model="queryParams" class="demo-form-inline" :inline="true">
                <el-form-item>
                    <el-button type="primary" size="small" icon="el-icon-plus" @click="roleAdd">新增</el-button>
                </el-form-item>
                <el-form-item label="筛选数据">
                    <el-input
                        size="small"
                        v-model="search"
                        placeholder="请输入匹配数据"
                        clearable
                        @keyup.enter.native="handleQuery"
                    />
                </el-form-item>
                <!-- <el-form-item>
          <el-button type="primary" plain icon="el-icon-search" @click="handleQuery">搜索
          </el-button>
        </el-form-item> -->
            </el-form>

            <el-table
                stripe
                ref="roleTable"
                v-loading="loading"
                :data="tables"
                header-cell-class-name="table_header"
                @selection-change="handleSelectionChange"
                @row-click="handleRowClick"
                border
                :height="vhh"
                highlight-current-row
            >
                <!-- <el-table-column align="center" type="selection" width="55"></el-table-column> -->
                <el-table-column align="center" label="角色名称" prop="name" min-width="140" />
                <el-table-column align="center" label="角色编码" prop="code" min-width="100" />
                <el-table-column align="center" label="角色描述" prop="remark" min-width="100" />
                <!-- <el-table-column align="center" label="更新时间" prop="updateTime">
             <template slot-scope="scope">{{ scope.row.updateTime | formatDate }}</template>
        </el-table-column> -->
                <el-table-column align="center" label="角色状态" prop="state" min-width="80">
                    <template slot-scope="scope">
                        <sapn type="danger" size="mini" v-if="scope.row.state === 0">注销</sapn>
                        <sapn type="success" size="mini" v-if="scope.row.state === 1">正常</sapn>
                    </template>
                </el-table-column>
                <el-table-column label="操作" align="center" width="200">
                    <template slot-scope="scope">
                        <el-button
                            type="primary"
                            size="mini"
                            icon="el-icon-edit"
                            @click.stop="handleEdit(scope.row)"
                            v-if="scope.row.state === 1"
                        >
                            修改
                        </el-button>
                        <el-button
                            type="danger"
                            size="mini"
                            icon="el-icon-delete"
                            v-if="scope.row.state === 1"
                            @click.stop="handleDelete(scope.row)"
                        >
                            删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!-- <el-pagination
     style="float: right;margin-top:10px"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pagination.current"
      :page-sizes="[5, 10, 15]"
      :page-size="pagination.size"
      layout="total, sizes, prev, pager, next, jumper"
      :total="pagination.total">
    </el-pagination> -->
            <!-- 角色弹窗 -->
            <el-dialog
                :close-on-click-modal="false"
                :title="rowName"
                :visible.sync="dialogVisible"
                width="30%"
                :before-close="closeDialog"
            >
                <el-form ref="form" :model="formData" :rules="rules" label-width="90px">
                    <el-form-item label="角色名称:" prop="name">
                        <el-input v-model="formData.name" placeholder="请输入角色名称" />
                    </el-form-item>
                    <el-form-item label="角色编码:" class="top" prop="code">
                        <el-input v-model="formData.code" placeholder="请输入角色编码" />
                    </el-form-item>
                    <el-form-item label="角色描述:" class="top" prop="roleDescription">
                        <el-input
                            @focus="checkStart"
                            @blur="checkEnd"
                            type="textarea"
                            v-model="formData.remark"
                            placeholder="请输入中文描述"
                        />
                    </el-form-item>
                    <!-- <el-form-item label="状态">
            <el-radio-group v-model="formData.state">
              <el-radio :label="1">正常</el-radio>
              <el-radio :label="0">停用</el-radio>
            </el-radio-group>
          </el-form-item> -->
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="closeDialog">取 消</el-button>
                    <el-button type="primary" @click="handleSubmit">确 定</el-button>
                </div>
            </el-dialog>
        </el-card>
    </div>
</template>

<script>
import { list, update, add, deleteRole, getByIdroel, panduan, del, selecRoleDetail } from '@/api/admin/role'

export default {
    name: 'Role',
    computed: {
        // 实时监听表格
        tables: function () {
            const search = this.search
            if (search) {
                return this.pageList.filter(dataNews => {
                    return Object.keys(dataNews).some(key => {
                        return String(dataNews[key]).toLowerCase().indexOf(search) > -1
                    })
                })
            }
            return this.pageList
        }
    },
    filters: {
        formatDate: function (value) {
            //这里的 value 就是需要过滤的数据
            var date = new Date(value)
            var year = date.getFullYear()
            var month = date.getMonth() + 1
            var day = date.getDate()
            var hours = date.getHours()
            var minutes = date.getMinutes()
            var seconds = date.getSeconds()
            return year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds
        }
    },
    data() {
        return {
            search: '',
            vh: null,
            vhh: null,
            dialogVisible: false,
            rowName: '新增角色',
            t: undefined,
            checkedRoleId: undefined,
            forbidden: true,
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            queryParams: {
                queryMode: 'page',
                name: undefined
            },
            pagination: {
                current: 1,
                size: 15,
                total: 0
            },
            pageList: [],
            dialog: {
                title: undefined,
                visible: false
            },
            // 表单参数
            formData: {
                code: '',
                name: '',
                remark: '',
                type: undefined
            },
            checkInterval: '',
            // 表单校验
            rules: {
                name: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }],
                code: [{ required: true, message: '角色编码不能为空', trigger: 'blur' }]
            }
        }
    },
    created() {
        this.handleQuery2()
    },
    mounted() {
        this.setHeight()
        window.addEventListener('resize', this.setHeight)
    },
    beforeDestroy() {
        window.removeEventListener('resize', this.setHeight)
    },
    methods: {
        setHeight() {
            this.vh = window.sessionStorage.getItem('appheight') - 10
            this.vhh = window.sessionStorage.getItem('appheight') - 132
        },
        checkChinese() {
            this.form.roleDescription = this.form.roleDescription.replace(/[^\u4E00-\u9FA5]/g, '')
        },
        checkStart() {
            this.checkInterval = setInterval(this.checkChinese, 100)
        },
        checkEnd() {
            clearInterval(this.checkInterval)
        },
        handleSizeChange(val) {
            this.pagination.size = val
            this.handleQuery()
        },
        handleCurrentChange(val) {
            //console.log(`当前页: ${val}`);
            this.pagination.current = val
            this.handleQuery()
        },
        //查询
        handleQuery() {
            this.queryParams.page = this.pagination.current
            this.queryParams.limit = this.pagination.size
            var p = {
                orderBy: '',
                pageNum: 0,
                pageSize: 0,
                searchBeginTime: '',
                searchEndTime: '',
                searchState: 0,
                searchValue: '',
                sortBy: ''
            }
            list(p).then(response => {
                this.pageList = response.data.records
                //this.pagination.total = response.total
                this.loading = false
            })
        },

        handleQuery2() {
            var data = {
                id: window.sessionStorage.getItem('type')
            }
            selecRoleDetail(data).then(response => {
                this.pageList = response.data
                //this.pagination.total = response.total
                this.loading = false
            })
        },
        //新增
        roleAdd() {
            this.t = 'add'
            this.dialogVisible = true
            this.formData = {
                code: '',
                name: '',
                remark: '',
                type: undefined
            }
            var usertype = window.sessionStorage.getItem('type')
            if (usertype == '0') {
                this.formData.type = 1
            }
            if (usertype == '1') {
                this.formData.type = 2
            }
        },
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.functionIindex)
            this.single = selection.length != 1
            this.multiple = !selection.length
        },
        handleAdd() {
            this.resetForm()
            this.dialog = {
                title: '新增角色',
                visible: true
            }
        },
        handleEdit(row) {
            this.t = 'edit'
            this.rowName = '修改角色'
            this.dialogVisible = true
            this.formData = {
                id: row.id,
                code: row.code,
                name: row.name,
                remark: row.remark
            }
        },
        handleDelete(row) {
            var arr = []
            var id = row.id
            arr.push(id)
            panduan(arr).then(response => {
                this.$confirm('确认删除该角色吗?', '警告', {
                    confirmButtonText: '删除',
                    cancelButtonText: '取消',
                    type: 'warning'
                })
                    .then(() => {
                        del(arr).then(response => {
                            if (response.code == 'A0000') {
                                this.$message.success('删除成功')
                                this.handleQuery2()
                                this.checkedRoleId = row.id // 勾选行
                                const currentRow = JSON.parse(JSON.stringify(row))
                                this.$emit('roleClick', currentRow)
                            }
                        })
                    })
                    .catch(() => this.$message.info('已取消删除'))
            })
        },
        handleSubmit() {
            if (this.t == 'add') {
                add(this.formData).then(response => {
                    if (response.code == 'A0000') {
                        this.$message.success('新增成功')
                        this.handleQuery2()
                        this.dialogVisible = false
                    }
                })
            }
            if (this.t == 'edit') {
                update(this.formData).then(response => {
                    if (response.code == 'A0000') {
                        this.$message.success('修改成功')
                        this.handleQuery2()
                        this.dialogVisible = false
                    }
                })
            }
        },
        resetForm() {
            this.form = {
                sort: 1,
                status: 1
            }
            if (this.$refs['form']) {
                this.$refs['form'].resetFields()
            }
        },
        closeDialog() {
            this.resetForm()
            this.dialogVisible = false
        },
        handleRowClick(row) {
            this.checkedRoleId = row.id // 勾选行
            const currentRow = JSON.parse(JSON.stringify(row))
            this.$emit('roleClick', currentRow)
        }
    }
}
</script>
<style lang="less" scoped>
@import url('../../../../../styles/comStyle.less');
</style>
<style lang="scss" scoped>
::v-deep .el-card__body,
.el-main {
    padding: 10px;
    // background: #e9ebeb;
}

::v-deep .el-tag:not(.el-tag--dark) {
    background-color: #edf8f6;
    border-color: #dbf0ed;
    color: #4ab5a5;
    height: 36px;
    line-height: 36px;
}

::-webkit-scrollbar {
    width: 8px !important;
    height: 14px;
}
</style>
