<template>
    <div class="ajm-panel-container">
        <div class="main-left-tree">
            <el-input :placeholder="$t('message.MenuMain.conMenu')" v-model="filterMenuName" prefix-icon="el-icon-search" class="tree-search">
            </el-input>
            <el-tree class="" lazy ref="menuTree" :props="menuTreeProps" :load="loadNodes" :highlight-current="true" @node-click="viewNode"
                     :indent="30" node-key="nodeId" :default-expanded-keys="defaultExpandedKeys" :current-node-key="currentNodeKey">
                <span class="custom-tree-node" slot-scope="{ node, data }">
                    <span>{{ node.label }}</span>
                    <span class="span-tree-icons">
                          <el-tooltip :content="$t('message.add')" placement="top">
                                    <el-button size="small" type="text" @click="goAddResource(data)">
                                        <i class="el-icon-ajm-add"></i>
                                    </el-button>
                          </el-tooltip>
                          <el-tooltip :content="$t('message.edit')" placement="top" v-if="!data.systemCategoryId">
                                    <el-button size="small" type="text" @click="goEditResource(data)">
                                        <i class="el-icon-ajm-edit"></i>
                                    </el-button>
                          </el-tooltip>
                          <el-tooltip :content="$t('message.delete')" placement="top" v-if="!data.systemCategoryId">
                                    <el-button size="small" type="text" @click="deleteResource(data)">
                                        <i class="el-icon-ajm-delete"></i>
                                    </el-button>
                          </el-tooltip>
                    </span>
                </span>
            </el-tree>
        </div>
        <div class="main-right-panel">
            <div class="main-right-list">
                <div class="ajm-search-form">
                    <el-form ref="searchForm" :model="searchForm" :inline="true">
                        <el-row>
                            <el-col :span="6">
                                <el-form-item class="operate-buttons">
                                    <el-button type="primary" icon="el-icon-ajm-add" @click="goAddResource()">{{$t("add")}}</el-button>
                                </el-form-item>
                            </el-col>
                            <el-col :span="18" class="ajm-search-items">
                                <el-form-item>
                                    <el-input id="enterSearch" class="search-item" v-model="searchForm.resourceName" :placeholder="$t('message.MenuMain.confirmName')">
                                    </el-input>
                                </el-form-item>
                                <el-form-item class="ajm-search-btns">
                                    <el-button icon="el-icon-ajm-search" @click="search"></el-button>
                                    <el-button icon="el-icon-ajm-refresh" @click="refreshSearch"></el-button>
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-form>
                </div>
                <div class="ajm-table-list">
                    <el-table :data="pageResult.list" tooltip-effect="light" style="width: 100%" v-loading="listLoading" @filter-change="handleFilterChange">
                        <el-table-column type="index" :label="$t('message.Table.index')" width="70">
                        </el-table-column>
                        <el-table-column prop="resourceName" :label="$t('message.MenuMain.resourceName')" :show-overflow-tooltip="true" min-width="120">
                        </el-table-column>
                        <el-table-column prop="resourceCode" :label="$t('message.MenuMain.resourceCode')" :show-overflow-tooltip="true" min-width="120">
                        </el-table-column>
                        <el-table-column prop="resourceType.name" :label="$t('message.MenuMain.resourceType')" column-key="type" :filters="resourceType" :filter-method="filterType" :filter-multiple="false" width="120">
                        </el-table-column>
                        <el-table-column :label="$t('message.MenuMain.resourceIcon')" width="70">
                            <template slot-scope="scope">
                            <span>
                                <i :class="scope.row.icon"></i>
                            </span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="resourcePath" :label="$t('message.MenuMain.resourcePath')" width="350">
                        </el-table-column>
                        <el-table-column prop="orderNo" :label="$t('message.MenuMain.orderNo')" width="120">
                        </el-table-column>
                        <el-table-column prop="remark" :label="$t('message.MenuMain.describe')" :show-overflow-tooltip="true" min-width="120">
                        </el-table-column>
                        <el-table-column :label="$t('message.Table.operate')" width="90" fixed="right">
                            <template slot-scope="scope">
                                <el-tooltip :content="$t('message.edit')"  placement="top">
                                    <el-button size="small" type="text" @click="goEditResource(scope.row)">
                                        <i class="el-icon-ajm-edit"></i>
                                    </el-button>
                                </el-tooltip>
                                <el-tooltip :content="$t('message.delete')"  placement="top">
                                    <el-button v-if="scope.row.resourceId != 0" size="small" type="text" @click="deleteResource(scope.row)">
                                        <i class="el-icon-ajm-delete"></i>
                                    </el-button>
                                </el-tooltip>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
                <div class="ajm-pagination-bar">
                    <el-pagination background @current-change="changePage" @size-change="changePageSize" :current-page="pageResult.pageNum" :page-sizes="[10, 20, 50, 100]" :page-size="pageResult.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="pageResult.total">
                    </el-pagination>
                </div>
            </div>
        </div>

        <el-dialog :title="dialogTitle" width="30%" custom-class="ajm-dialog-middle" :visible.sync="resourceFormVisible" top="0" :modal-append-to-body="false" :close-on-click-modal="false">
            <el-form class="ajm-form" :model="editForm" :rules="editFormRules" label-width="80px" ref="editForm">
                <el-form-item :label="$t('message.Base.systemName')">
                    <el-select v-model="currentNodeData.systemCode" disabled :placeholder="$t('message.Table.choose')">
                        <el-option
                            v-for="item in systems"
                            :key="item.systemCode"
                            :label="item.systemName"
                            :value="item.systemCode">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item :label="$t('message.MenuMain.resourceName')" prop="resourceName">
                    <el-input auto-complete="off" v-model="editForm.resourceName" :maxlength="10"></el-input>
                </el-form-item>
                <el-form-item :label="$t('message.MenuMain.resourcePath')" prop="resourcePath">
                    <el-input auto-complete="off" v-model="editForm.resourcePath" :maxlength="200"></el-input>
                </el-form-item>
                <el-form-item :label="$t('message.MenuMain.parePer')">
                    <el-input auto-complete="off" v-model="editForm.parentResourceName" :disabled="true"></el-input>
                </el-form-item>
                <el-form-item :label="$t('message.MenuMain.resourceType')" required>
                    <el-select :placeholder="$t('message.MenuMain.confirmType')" v-model="editForm.resourceType.value">
                        <el-option :label="$t('message.MenuMain.menu')" value="1"></el-option>
                        <el-option :label="$t('message.MenuMain.button')" value="2"></el-option>
                        <el-option :label="$t('message.MenuMain.page')" value="3"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item :label="$t('message.MenuMain.resourceIcon')">
                    <el-col :span="22">
                        <el-select :placeholder="$t('message.MenuMain.confirmIcon')" v-model="editForm.icon">
                            <el-option v-for="item in menuIcons" :key="item.value" :label="item.label" :value="item.value">
                                <span class="fl">{{item.label}}</span>
                                <span class="fr">
                                <i :class="item.value"></i>
                            </span>
                            </el-option>
                        </el-select>
                    </el-col>
                    <el-col :span="2">
                    <span>&nbsp;&nbsp;&nbsp;
                        <i :class="editForm.icon"></i>
                    </span>
                    </el-col>
                </el-form-item>
                <el-form-item :label="$t('message.MenuMain.orderNo')" prop="orderNo">
                    <el-input auto-complete="off" v-model="editForm.orderNo" type="number"></el-input>
                </el-form-item>
                <el-form-item :label="$t('message.MenuMain.describe')" prop="remark">
                    <el-input auto-complete="off" :rows="4" style="max-width: 260px" v-model="editForm.remark" type="textarea" :maxlength="200"></el-input>
                </el-form-item>
            </el-form>

            <div slot="footer" class="ajm-dialog-footer">
                <div class="ajm-dialog-btns">
                    <el-button type="primary" size="small" :loading="saveUpdateLoading" @click="saveOrUpdateResource('editForm')">{{$t('message.save')}}</el-button>
                    <el-button size="small" @click="resourceFormVisible = false">{{$t('message.cancel')}}</el-button>
                </div>
            </div>
        </el-dialog>

    </div>

</template>

<style>
</style>

<script>
import resourceService from "../services/resourceService";
import $ from 'jquery'
import menuIcons from "@/assets/icons";
import SecurityManager from "ajm-framework/core/manager/SecurityManager";

export default {
    data() {
        return {
            //弹窗标题
            dialogTitle:'',
            // 列表加载
            listLoading: false,
            //资源表单显示
            resourceFormVisible: false,
            // 保存资源表单动画
            saveUpdateLoading:false,
            // 当前节点
            currentNode : null,
            // 当前节点数据
            currentNodeData : {
                systemCode : null
            },
            //系统列表
            systems:[],
            // 默认展开数组
            defaultExpandedKeys : [],
            //默认选中节点
            currentNodeKey:'',
            // 菜单属性
            menuTreeProps: {
                label: "nodeName",
                isLeaf: "leaf"
            },
            // 资源类型
            resourceType: [{ text: this.$t('message.MenuMain.menu'), value: 1 }, { text: this.$t('message.MenuMain.button'), value: 2 },
                { text: this.$t('message.MenuMain.page'), value: 3 }],
            // 查询表单
            searchForm: {
                // 资源名称
                resourceName: "",
                // 资源编码
                resourceCode: "",
                // 父资源ID
                parentResourceId: "",
                //模糊资源编码（查询所有子节点）
                resourceCodeLike: ""
            },
            //编辑新增表单
            editForm: {
                //资源id
                resourceId: "",
                // 资源名称
                resourceName: "",
                //资源路径
                resourcePath:"",
                // 资源编码
                resourceCode: "",
                // 资源类型
                resourceType: {
                    value: 1
                },
                // 父资源ID
                parentResourceId: null,
                //父资源名称
                parentResourceName: "",
                //备注
                remark: "",
                orderNo: 0,
                icon: ""
            },
            /*editFormRules: {
                resourceName: [
                    { required: true, message: "请输入权限名称", trigger: "blur" },
                    {min:1,max:20,message:"长度最大为20位字符"}
                ],
                resourceType: [
                    {required: true, validator: checkResourceType, trigger: 'blur' }
                ],
                orderNo:[{type:'number', validator: checkOrder, trigger: 'blur' }]
            },*/
            //资源结果集合
            pageResult: {
                pageNum: 1,
                pageSize: 10,
                total: 0,
                list: []
            },
            // 菜单图标集合
            menuIcons: menuIcons,
            //权限类型搜索
            permissionType:'',
            //过滤菜单名
            filterMenuName: "",
            //是否修改资源
            isEdit:false,
        };
    },
    watch: {
        // 过滤菜单名
        filterMenuName(value) {
            this.$refs.menuTree.filter(value);
        }
    },
    computed:{
        editFormRules(){
            var checkResourceType = (rule, value, callback) => {
                if (value.value == '') {
                    callback(new Error(this.$t('message.MenuMain.confirmType')));
                } else {
                    callback();
                }
            };
            var checkOrder = (rule, value, callback) => {
                if (value) {
                    if (!/^[0-9]+$/.test(value)) {
                        callback(new Error(this.$t('message.MenuMain.checkOrder')));
                    } else {
                        callback();
                    }
                } else {
                    callback();
                }
            };
            return{
                resourceName: [
                    { required: true, message: this.$t('message.MenuMain.confirmName'), trigger: "blur" },
                    {min:1,max:20,message:this.$t('message.MenuMain.nameClue')}
                ],
                resourceType: [
                    {required: true, validator: checkResourceType, trigger: 'blur' }
                ],
                orderNo:[{type:'number', validator: checkOrder, trigger: 'blur' }]
            }
        },
    },
    methods: {
        // 查询资源分页列表
        findResourceListByPage() {
            this.$refs.menuTree.setCurrentNode({nodeId:this.currentNodeData.nodeId});
            if(!this.isEdit){
                this.editForm.parentResourceId = this.currentNodeData.resourceId;
            }
            this.editForm.parentResourceName = this.currentNodeData.resourceName;
            this.listLoading = true;
            let params = {
                page: this.pageResult.pageNum,
                rows: this.pageResult.pageSize,
                resourceCodeLike:this.currentNodeData.resourceCode,
                resourceName:this.searchForm.resourceName,
                systemCode:this.currentNodeData.systemCode
            };
            // 需要查询资源类型
            let resourceType = this.permissionType;
            if (resourceType) {
                params.resourceType = {
                    value: resourceType
                };
            }

            //查询资源集合分页
            resourceService.findResourceListByPage(params).then(resp => {
                var result = resp.data || resp;
                this.pageResult = result;
                this.listLoading = false;
            });
        },
        // 显示节点
        viewNode(data, node, store) {
            this.currentNode = node;
            this.currentNodeData = data;
            this.search();
            node.expanded = true;
        },
        //加载树
        loadNodes(node, resolve) {
            this.currentNode = node;
            if(node.data){
                this.currentNodeData = node.data;
            }
            if (node.level === 0) {
                let systemNodes =[]
                resourceService.findAllSystemList().then(resp =>{
                    if (resp && resp.length > 0) {
                        systemNodes = [];
                        resp.forEach(item => {
                            systemNodes.push({
                                nodeId: item.systemId,
                                nodeName: item.systemName,
                                systemCode:item.systemCode,
                                systemName: item.systemName,
                                systemCategoryId:item.systemCategoryId
                            })
                        });
                        this.systems = resp;
                    }
                    // 渲染节点
                    resolve(systemNodes);
                    this.currentNode = node;
                    if(systemNodes && systemNodes.length > 0){
                        let systemNode = systemNodes[0];
                        this.currentNodeData = systemNode;
                        this.defaultExpandedKeys.push(systemNode.nodeId);
                        this.currentNodeKey = systemNode.nodeId;
                    }
                })
            }else{
                let params = {
                    systemCode:node.data.systemCode,
                };
                if(node.level > 1){
                    params.parentResourceId = node.data.nodeId;
                }
                let menuItemNodes = [];
                resourceService.findResourceList(params).then(resp => {
                    if (resp && resp.length > 0) {
                        menuItemNodes = [];
                        resp.forEach(item => {
                            menuItemNodes.push({
                                nodeId:item.resourceId,
                                nodeName: item.resourceName,
                                systemCode: item.systemCode,
                                resourceCode:item.resourceCode,
                                resourceId:item.resourceId,
                                resourceType:item.resourceType,
                                resourceName:item.resourceName,
                                resourcePath:item.resourcePath,
                                remark:item.remark,
                                orderNo:item.orderNo,
                                parentResourceId:item.parentResourceId
                            })
                        });
                    }
                    resolve(menuItemNodes);
                    this.currentNode = node;
                    this.currentNodeData = node.data;
                });
                // 查询资源分页列表
                this.search();
            }
        },

        // 搜索
        search() {
            this.listLoading = true;
            this.findResourceListByPage();
        },
        //刷新页面
        refreshSearch(){
            this.searchForm.resourceName = '';
            this.pageResult.pageNum = 1
            this.pageResult.pageSize = 10
            this.findResourceListByPage();
        },
        //重置表单
        resetForm(formName) {
            if (this.$refs[formName] !== undefined) {
                this.$refs[formName].resetFields();
            }
        },

        //切换页面
        changePage(page) {
            this.pageResult.pageNum = page;
            this.findResourceListByPage();
        },
        //切换页面
        changePageSize(pageSize) {
            this.pageResult.pageSize = pageSize;
            this.findResourceListByPage();
        },
        //筛选权限类型
        filterType(value,row){
            return row.resourceType.value === value;
        },
        // 执行筛选查询
        handleFilterChange(filters){
            this.type = filters.type[0];
            this.findResourceListByPage();
        },
        //过滤菜单节点
        filterMenuNode(value, data) {
            if (!value) return true;
            return data.nodeName.indexOf(value) !== -1;
        },

        // 进入添加表单
        goAddResource(data) {
            //重置editForm
            this.resetForm("editForm");
            this.dialogTitle = this.$t('message.MenuMain.addResource');
            this.editForm.resourceId = "";
            this.editForm.resourceName = "";
            this.editForm.resourceType.value = "1";
            this.editForm.resourcePath = "";
            this.editForm.remark = "";
            this.editForm.orderNo = 0;
            this.editForm.icon = "";
            if(data){
               this.editForm.parentResourceName = data.resourceName;
               this.editForm.parentResourceId = data.parentResourceId;
            }
            this.resourceFormVisible = true;
        },
        // 进入编辑资源
        goEditResource(data){
            this.dialogTitle = this.$t('message.edit');
            this.editForm.resourceId = data.resourceId;
            this.editForm.resourceName = data.resourceName;
           /* if(data.nodeId){
                this.editForm.resourceType.value = data.resourceType.value;
            }else{*/
                this.editForm.resourceType.value = data.resourceType.value.toString();
            /*}*/
            this.editForm.resourcePath = data.resourcePath;
            this.editForm.resourceCode = data.resourceCode;
            this.editForm.orderNo = data.orderNo;
            this.editForm.icon = data.icon || data.resourceIcon;
            this.editForm.remark = data.remark;
            this.editForm.parentResourceId = data.parentResourceId;
            resourceService.findResourceByResourceId(data.parentResourceId).then(resp => {
                if (resp.status == 500) {
                    this.editForm.parentResourceName = ''
                }else{
                    this.editForm.parentResourceName = resp.resourceName
                }
            })
            this.resourceFormVisible = true;
            this.isEdit = true;
        },
        // 删除资源树
        deleteResource(data) {
            var resourceId = data.resourceId;
            var resourceName = data.resourceName;
            this.$confirm(
                this.$t('message.confirmRequest') +"[" + resourceName + "]?", this.$t('message.delClue'),
                {
                    cancelButtonClass:"message-cancel-button",
                    confirmButtonText: this.$t('message.confirm'),
                    cancelButtonText: this.$t('message.cancel'),
                    type: "warning"
                }
            ).then(() => {
                resourceService.deleteResourceByResourceId(resourceId).then(resp => {
                    if (resp.status == 500) {
                        this.$message({
                            message: resp.message,
                            type: "error"
                        });
                    }else{
                        //删除树节点
                        this.$refs.menuTree.remove({
                            nodeId:resourceId
                        });

                        this.$message({
                            type: "success",
                            message: this.$t('message.delSuccess')
                        });
                        //输出列表
                        this.findResourceListByPage();
                    }
                });
            })
        },

        // 保存或更新资源
        saveOrUpdateResource(formName) {
            this.resourceFormVisible = true;
            var menuVO = {
                resourceId: this.editForm.resourceId,
                resourceName: this.editForm.resourceName,
                resourceCode: this.editForm.resourceCode,
                resourceType: this.editForm.resourceType,
                parentResourceId: this.editForm.parentResourceId,
                remark: this.editForm.remark,
                orderNo: this.editForm.orderNo,
                icon: this.editForm.icon,
                resourcePath:this.editForm.resourcePath,
                systemCode:this.currentNodeData.systemCode
            };
            this.$refs[formName].validate(valid => {
                if (valid) {
                    resourceService.saveOrUpdateResource(menuVO).then(resp => {
                        if(resp.status == 500){
                            this.$message({
                                message: resp.message,
                                type: "warning"
                            });
                        }else{
                            this.findResourceListByPage();
                            this.$message({
                                message: this.$t('message.saveSuccess'),
                                type: "success"
                            });
                            this.saveUpdateLoading = false;
                            this.resourceFormVisible = false;
                            if(!this.isEdit){
                                // 追加节点
                                this.$refs.menuTree.append({
                                    nodeId:resp.resourceId,
                                    nodeName: resp.resourceName,
                                    systemCode: resp.systemCode,
                                    resourceCode:resp.resourceCode,
                                    systemName:resp.systemName,
                                    resourceId:resp.resourceId,
                                    resourceType:resp.resourceType,
                                    resourceName:resp.resourceName,
                                    resourcePath:resp.resourcePath,
                                    remark:resp.remark,
                                    orderNo:resp.orderNo,
                                    parentResourceId:resp.parentResourceId
                                },this.currentNode);
                            }else{
                                //删除树节点
                                this.$refs.menuTree.remove({
                                    nodeId:resp.resourceId
                                });
                                // 追加节点
                                this.$refs.menuTree.append({
                                    nodeId:resp.resourceId,
                                    nodeName: resp.resourceName,
                                    systemCode: resp.systemCode,
                                    resourceCode:resp.resourceCode,
                                    systemName:resp.systemName,
                                    resourceId:resp.resourceId,
                                    resourceType:resp.resourceType,
                                    resourceName:resp.resourceName,
                                    resourcePath:resp.resourcePath,
                                    remark:resp.remark,
                                    orderNo:resp.orderNo,
                                    parentResourceId:resp.parentResourceId
                                },resp.parentResourceId);
                            }
                        }
                    });
                }
            });
        },
    },
    //初始化
    mounted() {
        let self = this;
        document.getElementById("enterSearch").addEventListener("keydown", function (event) {
            if (event.keyCode === 13) {
                self.search(event);
            }
        }, false);
    }
};
</script>

