<template>
    <div>
        <el-card class="box-card" shadow="always" :style="'height:' + vh + 'px'">
            <div class="clearfix" slot="header">
                <b>
                    <!-- <svg-icon icon-class="route"/> -->
                    {{ menuName }}权限列表
                </b>
            </div>
            <!-- 搜索表单 -->
            <el-form ref="queryForm" :model="queryParams" :inline="true">
                <el-form-item>
                    <el-button type="primary" :disabled="disabled" icon="el-icon-plus" @click="bottonAdd">
                        新增
                    </el-button>
                </el-form-item>
                <el-form-item>
                    <el-input v-model="input" placeholder="请输入关键字搜索" style="width: 500px"></el-input>
                </el-form-item>
            </el-form>

            <!-- 数据表格 -->
            <el-table
                stripe
                ref="table"
                :data="pageList"
                :height="vhh"
                v-loading="loading"
                row-key="id"
                :expand-row-keys="expandRow"
                highlight-current-row
                header-cell-class-name="table_header"
                @selection-change="handleSelectionChange"
                border
                size="mini"
            >
                <!-- <el-table-column type="selection" width="40" align="center"/> -->
                <el-table-column
                    label="普通接口/接口名称"
                    :show-overflow-tooltip="true"
                    min-width="150"
                    prop="name"
                    width="280"
                />
                <el-table-column
                    label="接口类型"
                    align="center"
                    :show-overflow-tooltip="true"
                    min-width="60"
                    prop="type"
                >
                    <template slot-scope="scope">
                        <el-tag type="primary" style="background: blue; color: aliceblue" v-if="scope.row.type == 4">
                            tabs标签页
                        </el-tag>

                        <el-tag type="primary" v-if="scope.row.type == 1">普通接口</el-tag>
                        <el-tag style="background: forestgreen; color: aliceblue" v-if="scope.row.type == 2">
                            公共接口
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column
                    label="URL接口路径"
                    align="center"
                    :show-overflow-tooltip="true"
                    min-width="220"
                    prop="path"
                ></el-table-column>
                <!-- <el-table-column label="按钮权限标识" prop="btnPerm" width="150"/> -->
                <el-table-column label="操作" align="center" width="200">
                    <template slot-scope="scope">
                        <el-button type="primary" size="mini" @click="handleEdit(scope.row)" icon="el-icon-edit">
                            修改
                        </el-button>
                        <el-button type="danger" size="mini" icon="el-icon-delete" @click="handleDelete(scope.row)">
                            删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!-- <pagination
        v-show="pagination.total>0"
        :total="pagination.total"
        :page.sync="pagination.page"
        :limit.sync="pagination.limit"
        @pagination="handleQuery"
      /> -->
            <el-dialog
                :close-on-click-modal="false"
                :title="rowName"
                :visible.sync="dialogVisible"
                width="30%"
                :before-close="closeDialog"
            >
                <el-form ref="form" :model="formData" label-width="120px" :rules="rules">
                    <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="状态">
          <el-radio-group v-model="form.state">
            <el-radio :label="0">不启用</el-radio>
            <el-radio :label="1">启用</el-radio>
          </el-radio-group>
        </el-form-item> -->

                    <el-form-item label="接口路径:" class="top" prop="path">
                        <el-input
                            v-model="formData.path"
                            placeholder="sys/admin/user或sys:user:add"
                            style="width: 100%"
                        />
                    </el-form-item>
                    <!-- <el-form-item label="接口图标:" prop="icon" style="margin-top:20px">
            <el-popover
              placement="bottom-start"
              width="460"
              trigger="click"
              @show="$refs['iconSelect'].reset()"
            >
              <IconSelect ref="iconSelect" @selected="handleIconSelected" />
              <el-input
                slot="reference"
                v-model="formData.icon"
                placeholder="点击选择图标"
              >
                <svg-icon
                  v-if="formData.icon"
                  slot="prefix"
                  :icon-class="formData.icon"
                  class="el-input__icon"
                  style="height: 40px; width: 16px"
                />
                <i v-else slot="prefix" class="el-icon-search el-input__icon" />
              </el-input>
            </el-popover>
          </el-form-item> -->
                    <el-form-item label="排列序号:" prop="sort" class="top">
                        <el-input v-model="formData.sort" placeholder="请输入按钮排序" />
                    </el-form-item>
                    <el-form-item label="接口类型:" prop="type" class="top">
                        <el-radio-group v-model="formData.type">
                            <el-radio :label="1">普通接口</el-radio>
                            <el-radio :label="2">公用接口</el-radio>
                            <!-- <el-radio :label="3">服务间调用接口</el-radio> -->
                            <!-- <el-radio :label="4">tabs标签页</el-radio> -->
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="接口/按钮描述:" prop="roleDescription">
                        <el-input type="textarea" v-model="formData.remark" placeholder="请输入接口描述" />
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <!-- <el-button type="primary" @click="handleSubmit" :disabled="flagb"
            >确 定</el-button
          > -->

                    <el-button @click="closeDialog">取 消</el-button>
                    <el-button type="primary" @click="handleSubmit">确 定</el-button>
                </div>
            </el-dialog>
        </el-card>
    </div>
</template>

<script>
import { buttonlist } from '@/api/admin/permission'
import { add, update, deleteMenu } from '@/api/admin/menu'
import IconSelect from '@/components/IconSelect'
import request from '@/utils/request'
export default {
    name: 'permission',
    components: { IconSelect },
    computed: {
        pageList: function () {
            var searchValue = this.input
            if (searchValue) {
                // 一般表格的查询
                // return  this.tableData.filter(function(dataNews){
                //   return Object.keys(dataNews).some(function(key){
                //     return String(dataNews[key]).toLowerCase().indexOf(search) > -1
                //   })
                // })
                let treeData = this.tableData
                let handleTreeData = this.handleTreeData(treeData, searchValue)
                this.setExpandRow(handleTreeData)
                this.expandRow = this.expandRow.join(',').split(',')
                return handleTreeData
            }
            return this.tableData
        }
    },
    data() {
        return {
            expandRow: [],
            vh: null,
            vhh: null,
            loading: false,
            flagb: false,
            ids: [],
            single: true,
            multiple: true,
            queryParams: {
                queryMode: 'page',
                name: undefined,
                menuId: undefined,
                type: undefined
            },
            pagination: {
                page: 1,
                limit: 10,
                total: 0
            },
            tableData: [],
            rowName: '修改接口/按钮',
            dialogVisible: false,
            formData: {
                code: '',
                icon: '',
                name: '',
                path: '',
                pid: undefined,
                remark: '',
                sort: 0,
                type: 1
            },
            disabled: true,
            t: undefined,
            menu: {},
            menuName: undefined,
            urlPerm: {
                requestMethod: undefined,
                serviceName: undefined,
                requestPath: undefined
            },
            microServiceList: [],
            requestMethodList: [],
            rules: {
                code: [
                    { required: true, message: '标识不能为空', trigger: 'blur' },
                    {
                        pattern: /^[a-zA-Z_]{1}[a-zA-Z0-9_]{2,15}$/,
                        message: '请输入至少3-20位英文',
                        min: 3,
                        max: 20,
                        trigger: 'blur'
                    }
                ],
                name: [{ required: true, message: '请输入接口名称', trigger: 'blur' }],
                sort: [{ required: true, message: '请输入排序', trigger: 'blur' }],
                path: [{ required: true, message: '请输入接口路径', trigger: 'blur' }],
                icon: [{ required: true, message: '请选择菜单图标', trigger: 'blur' }],
                type: [{ required: true, message: '请选择接口类型', trigger: 'blur' }]
            },
            input: ''
        }
    },
    created() {},
    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') - 134
        },
        //  树形表格过滤
        handleTreeData(treeData, searchValue) {
            if (!treeData || treeData.length === 0) {
                return []
            }
            const array = []
            for (let i = 0; i < treeData.length; i += 1) {
                let match = false
                for (let pro in treeData[i]) {
                    if (typeof treeData[i][pro] == 'string') {
                        match |= treeData[i][pro].includes(searchValue)
                        if (match) break
                    }
                }
                if (this.handleTreeData(treeData[i].children, searchValue).length > 0 || match) {
                    array.push({
                        ...treeData[i],
                        children: this.handleTreeData(treeData[i].children, searchValue)
                    })
                }
            }
            return array
        },
        // 将过滤好的树形数据展开
        setExpandRow(handleTreeData) {
            if (handleTreeData.length) {
                for (let i of handleTreeData) {
                    this.expandRow.push(i.id)
                    if (i.children.length) {
                        this.setExpandRow(i.children)
                    }
                }
            }
        },
        handleQuery() {
            this.queryParams.id = this.menu.id
            buttonlist(this.queryParams).then(response => {
                this.tableData = response.data
                //this.pagination.total = response.total
                this.loading = false
            })
        },

        handleReset() {
            this.pagination = {
                page: 1,
                limit: 10,
                total: 0
            }
            this.queryParams.name = undefined
            this.handleQuery()
        },
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.id)
            this.single = selection.length != 1
            this.multiple = !selection.length
        },
        bottonAdd() {
            this.rowName = '接口/按钮新增'
            this.dialogVisible = true
            this.t = 'add'
            this.formData.code = ''
            this.formData.icon = ''
            this.formData.name = ''
            this.formData.path = ''
            this.formData.remark = ''
            this.formData.sort = ''
            this.formData.type = 1
            //   code:'',
            //   icon:'',
            //   name:'',
            //   path:'',
            //   pid:undefined,
            //   remark:'',
            //   sort:0,
            //   type:0
            // }
        },
        loadMicroServices() {
            this.listDictItemByCode('micro_service').then(response => {
                this.microServiceList = response.data
            })
        },
        handleIconSelected(name) {
            this.formData.icon = name
            this.$forceUpdate()
        },
        loadRequestMethods() {
            this.listDictItemByCode('request_method').then(response => {
                this.requestMethodList = response.data
            })
        },
        handleEdit(row) {
            this.resetForm()
            this.t = 'edit'
            this.dialogVisible = true
            this.rowName = row.name + '接口/按钮修改'
            this.formData = {
                id: row.id,
                code: row.code,
                icon: row.icon,
                name: row.name,
                path: row.path,
                pid: row.pid,
                remark: row.remark,
                sort: row.sort,
                type: row.type
            }
        },
        handleSubmit() {
            this.flagb = true
            if (this.t == 'add') {
                add(this.formData).then(response => {
                    if (response.code == 'A0000') {
                        this.$message.success('新增成功')
                        this.flagb = false
                        this.handleQuery()
                        this.dialogVisible = false
                    }
                })
            }
            if (this.t == 'edit') {
                update(this.formData).then(response => {
                    if (response.code == 'A0000') {
                        this.$message.success('修改成功')
                        this.handleQuery()
                        this.dialogVisible = false
                    }
                })
            }
        },

        handleDelete(row) {
            // const ids = [row.id || this.ids].join(',')
            this.$confirm('是否确认删除当前按钮？', '警告', {
                confirmButtonText: '删除',
                cancelButtonText: '取消',
                type: 'warning'
            })
                .then(() => {
                    var p = {
                        id: row.id
                    }
                    deleteMenu(p).then(response => {
                        if (response.code == 'A0000') {
                            this.$message.success('删除成功')
                            this.handleQuery()
                        }
                    })
                })
                .catch(() => this.$message.info('已取消删除'))
        },
        closeDialog() {
            this.resetForm()
            this.dialogVisible = false
            this.dialog = {
                title: undefined,
                visible: false
            }
        },
        resetForm() {
            this.form = {
                //  menuId: this.menu.functionIndex,
            }
            this.urlPerm = {}
            if (this.$refs['form']) {
                this.$refs['form'].resetFields()
            }
        },
        menuClick(row) {
            this.disabled = false
            this.menu = row
            //console.log(row);
            this.menuName = '【' + this.menu.title + '】'
            this.formData.pid = this.menu.id
            //console.log(this.formData.pid);
            this.handleQuery()
        },
        resetPermission() {
            this.disabled = true
            this.pageList = []
            this.queryParams.menuId = undefined
            this.menu = {}
            this.menuName = undefined
        }
    }
}
</script>
<style lang="less" scoped>
@import url('../../../../../styles/comStyle.less');
</style>
<style lang="less" scoped>
::v-deep .el-card__body,
.el-main {
    padding: 10px;
    //background: #abacac;
}
</style>
