<template>
    <el-container style="height: 100%">
        <el-header style="height: auto;">
            <div class="search-form-parent el-card">
                <el-form :inline="true" :model="crud.searchForm" size="small" class="demo-form-inline"
                         @submit.native.prevent="crud.doSearch()">
                    <el-form-item label="选项卡名称">
                        <el-input v-model="crud.searchForm.tabName" placeholder="选项卡名称"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" icon="el-icon-search" @click="crud.doSearch()">查询</el-button>
                        <el-button icon="el-icon-close" @click="crud.resetSearch()">清空</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </el-header>

        <el-main id="tableMain" style="height: 100%">
            <el-container style="height:100%" class="table-list-container">
                <el-header style="height: auto;" size="medium">
                    <el-button type="primary" size="small" round icon="el-icon-circle-plus" @click="add()">新增
                    </el-button>
                    <el-button type="danger" size="small" round icon="el-icon-delete" @click="remove()">删除
                    </el-button>
                    <el-button type="primary" size="small" round icon="el-icon-tickets" @click="complexPreviewFunc()">预览
                    </el-button>
                </el-header>
                <el-main style="height: 100%;" ref="tableMain">
                    <el-table :data="crud.dataStore.records" :ref="crud.tableRef" stripe border height="100%"
                              header-row-class-name="list-default-row"
                              style="width: 100%;">
                        <el-table-column type="selection" width="40" align="center"></el-table-column>
                        <el-table-column type="index" label="序号" align="center" width="60"></el-table-column>
                        <el-table-column label="选项卡名称" prop="tabName" align="center"></el-table-column>
                        <el-table-column label="链接类型" align="center">
                            <template slot-scope="scope">
                                <span>{{formatterUrlType(scope.row.urlType)}}</span>
                            </template>
                        </el-table-column>
                        <el-table-column label="图标" prop="tabIcon" align="center">
                            <template slot-scope="scope">
                                <i :class="scope.row.tabIcon"></i>
                            </template>
                        </el-table-column>
                        <el-table-column label="排列顺序" prop="sort" align="center"></el-table-column>
                        <el-table-column label="操作" align="center">
                            <template slot-scope="scope">
                                <el-button type="primary" @click="update(scope.row)">修改</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-main>
            </el-container>
        </el-main>
        <el-footer>
            <el-pagination
                    :ref="crud.pageRef"
                    :page-sizes="crud.pageSizes"
                    :page-size="crud.pageSize"
                    :current-page="crud.page"
                    :total="crud.dataStore.total"
                    @size-change="crud.sizeChange()"
                    @current-change="crud.currentPage()"
                    layout="total, sizes, prev, pager, next, jumper">
            </el-pagination>
        </el-footer>
        <el-dialog :close-on-click-modal=false title="复合页面选项卡设置信息" top="15vh" :visible.sync="crud.dialogVisible"
                   append-to-body>
            <el-form :model="crud.formData" :ref="crud.addFormRef">
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="选项卡名称" label-width="120px" prop="tabName" :rules="plValidate('required')">
                            <el-input v-model="crud.formData.tabName"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="选项卡图标" label-width="120px">
                            <el-input v-model="crud.formData.tabIcon" style="display: none"></el-input>
                            <el-button @click="iconDialog = true">
                                <i :class="(currentIcon || '').indexOf('saspiconfont') > -1 ? currentIcon : 'saspiconfont pl-icon-tuxiang'"
                                   style="font-size:15px"></i></el-button>
                            <el-button @click="clearIcon()">清空</el-button>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="链接类型" label-width="120px" prop="urlType" :rules="plValidate('required')">
                            <el-cascader style="width: 100%" @change="changeBindSource"
                                         :options="urlTypeOptionArr"
                                         filterable
                                         clearable
                                         v-model="crud.formData.urlType">
                            </el-cascader>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-form-item label="权限信息" label-width="120px">
                    <el-row>
                        <el-col :span="12">
                            <el-card class="box-card-class">
                                <div slot="header" class="clearfix">
                                    <el-checkbox label="全选" @change="optChange"
                                                 v-model="crud.formData.allOptAuth"
                                                 style="margin-right: 0"></el-checkbox>
                                    <span style="font-size: 15px;margin-left: 70px">操作权限</span>
                                </div>
                                <div class="tree">
                                    <el-tree
                                            :data="operationFormData"
                                            show-checkbox
                                            default-expand-all
                                            node-key="id"
                                            @check-change="checkeOptChangeFnc"
                                            :render-content="renderOperateContent"
                                            ref="operatePermisRef"
                                            :props="defaultTreeProps">
                                    </el-tree>
                                </div>
                            </el-card>
                        </el-col>
                        <el-col :span="12">
                            <el-card class="box-card-class">
                                <div slot="header" class="clearfix">
                                    <el-checkbox label="全选" @change="dataChange"
                                                 v-model="crud.formData.allDataAuth"
                                                 style="margin-right: 0"></el-checkbox>
                                    <span style="font-size: 15px;margin-left: 70px">数据权限</span>
                                </div>
                                <div class="tree">
                                    <el-tree
                                            :data="dataPermisFormData"
                                            show-checkbox
                                            default-expand-all
                                            node-key="id"
                                            @check-change="checkeDataChangeFnc"
                                            ref="dataPermisRef"
                                            :props="defaultTreeProps">
                                    </el-tree>
                                </div>
                            </el-card>
                        </el-col>
                    </el-row>

                </el-form-item>

                <el-row>
                    <el-col :span="24">
                        <el-form-item label="排列顺序" label-width="120px" prop="sort"
                                      :rules="plValidate('required','intNotZero')">
                            <el-input v-model="crud.formData.sort"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm()" size="small" icon="el-icon-success">确 定</el-button>
                <el-button @click="crud.dialogVisible = false" size="small" icon="el-icon-error">取 消</el-button>
            </div>
        </el-dialog>
        <el-dialog :close-on-click-modal=false :visible.sync="iconDialog" class="font-dialog" title="选择图标" width="70%"
                   height="80%" top="10vh" append-to-body>
            <font-icon :callback="getmenuIcon"></font-icon>
        </el-dialog>
    </el-container>
</template>

<script>
    import {FontIcon} from 'sasp-base';

    const groupBy = (arr, func) =>
        arr.map(typeof func === 'function' ? func : val => val[func]).reduce((acc, val, i) => {
            acc[val] = (acc[val] || []).concat(arr[i]);
            return acc;
        }, {});
    export default {
        name: "complex-setting",
        components: {FontIcon},
        props: {
            viewObj: {
                type: Object,
                default: function () {
                    return {}
                }
            },
            urlTypeOptionArr: {
                type: Array,
                default: function () {
                    return []
                }
            },
            urlTypeOptionObj: {
                type: Object,
                default: function () {
                    return {}
                }
            },
            complexPreview: {
                type: Function,
                default() {
                }
            },
            resourceId:{
                type:String,
                default:''
            }
        },
        data() {
            return {
                crud: new this.CrudUtil({
                    vue: this,
                    entityName: "complextab",
                    url: this.api.complextab.url,
                    searchForm: {"order": "SORT ASC"},
                    noClearSearchColumns: ['viewId', "order"],
                    addDefaultData: {"formTreename": "", "formTreeid": "", "viewId": this.viewObj.id},
                    afterRemoveSuccess: this.afterRemoveSuccess,
                    updateLoadData: this.updateLoadData,
                    initNoSearch: true,
                }),
                optionObj: {
                    "form": "智能建表",
                    "singleForm": "单表表单",
                    "flow": "工作流",
                    "statRep": "统计报表",
                    "url": "url资源",
                    "sysFea": "自定义功能",
                    "sysFun": "系统功能"
                },

                options: [ // 链接类型
                    {label: '系统功能', value: 'sysFun'},
                    {label: '自定义功能', value: 'sysFea'},
                    {label: '智能建表', value: 'form'},
                    {label: '单表表单', value: 'singleForm'},
                    {label: '工作流', value: 'flow'},
                    {label: '统计报表', value: 'statRep'},
                    {label: 'url资源', value: 'url'},
                ],
                showTypeOption: [{ // 自定义表单展示方式
                    value: '列表视图',
                    label: '列表视图'
                }, {
                    value: '列表&树视图',
                    label: '列表&树视图'
                }],
                sysFeatureMenuTypeOptions: [], // 系统功能菜单
                sysFunctionMap: {}, // 系统功能菜单map键值对
                customFunctionMenuOptions: [], // 自定义功能菜单
                customFunctionMap: {}, // 自定义功能菜单map键值对
                lastUrlType: "", // 上一次的链接类型
                conditionOption: [], // 加载条件选项
                currentIcon: "", // tab页图标
                iconDialog: false, // tab页图片选择对话框
                workFlowNodeOptions: [], // 工作流节点选项
                chooseFormDialog: false, // 选择自定义表单
                chooseFlowFormDialog: false, // 选择工作流
                chooseTreeDialog: false, // 选择树
                chooseStatisticalFormDialog: false, // 选则统计报表
                flowTabDialog: false, // 工作流配置项
                flowPreviewDialog: false, // 工作流tab页预览
                defaultGzltabs: { // 工作流默认值配置
                    "tabs":
                        {
                            "draft": {
                                "sfqy": true,
                                "defaultShow": false,
                                "gzlswitch": true,
                                "icon": "saspiconfont pl-icon-cunrucaogaoxiang",
                                "tabName": "草稿"
                            },
                            "pending": {
                                "sfqy": true,
                                "defaultShow": true,
                                "gzlswitch": true,
                                "icon": "saspiconfont pl-icon-daichuli",
                                "tabName": "待处理"
                            },
                            "finished": {
                                "sfqy": true,
                                "defaultShow": false,
                                "gzlswitch": true,
                                "icon": "saspiconfont pl-icon-yichuli",
                                "tabName": "已处理"
                            },
                            "end": {
                                "sfqy": true,
                                "defaultShow": false,
                                "gzlswitch": true,
                                "icon": "saspiconfont pl-icon-jieshu",
                                "tabName": "已办结"
                            },
                            "cancel": {
                                "sfqy": true,
                                "defaultShow": false,
                                "gzlswitch": true,
                                "icon": "saspiconfont pl-icon-chexiao",
                                "tabName": "已撤销"
                            },
                            "stopped": {
                                "sfqy": true,
                                "defaultShow": false,
                                "gzlswitch": true,
                                "icon": "saspiconfont pl-icon-yizhongzhi",
                                "tabName": "已中止"
                            },
                            "query": {
                                "sfqy": true,
                                "defaultShow": false,
                                "gzlswitch": false,
                                "icon": "saspiconfont pl-icon-chaxun",
                                "tabName": "流程查询"
                            }
                        },
                    "tWidth": "", "tHeight": ""
                },
                operationFormData: [], //操作权限树数据
                dataPermisFormData: [], //数据权限树数据
                operationFormObj: {}, //操作权限节点数据key obj
                dataPermisFormObj: {}, //数据节点权限obj
                isHalfOperationKeyArr: [], //已经在半选中保存数据
                isAllOperationKeyArr: [], //已经在全选中保存的数据
                initCheckOperion: {},//默认选中操作权限
                initCheckData: {}, //默认选中数据权限
                defaultTreeProps: {
                    children: 'children',
                    label: 'powerName',
                    id: 'id'
                },

                refreshProper: '', //权限刷新

                allCheckOperateKeyArr: [],
                allCheckDataKeyArr: [],

                defaultProps: {children: 'children', label: 'powerName', id: 'id', key: 'powerKey'}, // 树组件的配置信息

                deleteIdArr: [], //删除id
                updateResourceId: '', //当前修改的resoucedId
            }
        },
        created() {
            this.init();
        },
        watch: {
            'crud.formData.urlType'(val) { // 此处在select的change事件后触发，这里可以记住update时的初始值
                this.lastUrlType = val;
            },
            resourceId() {
                this.updateResourceId = this.resourceId;
            }
        },
        methods: {

            /**
             * 预览方法
             */
            complexPreviewFunc() {
                this.complexPreview(this.viewObj);
            },

            /**
             * 初始化功能菜单等数据
             */
            initLinkData() {
                let vm = this;
                vm.sysFeatureMenuTypeOptions = [];
                vm.customFunctionMenuOptions = [];
                // vm.axios.post(vm.api.sysFunction.find,{"order":"GNLB ASC,SX ASC"}).then(res => {
                //     let [arrSys,arrCus] = [[],[]];
                //     (res.data || []).forEach(item => {
                //         if(item.ifcustomizemenu == "no"){
                //             vm.sysFunctionMap[item.id] = item;
                //             arrSys.push(item);
                //         }
                //         if(item.ifcustomizemenu == "yes"){
                //             vm.customFunctionMap[item.id] = item;
                //             arrCus.push(item);
                //         }
                //     });
                //     let SysData = groupBy(arrSys,'gnlb');
                //     let CusData = groupBy(arrCus,'gnlb');
                //     Object.keys(SysData).forEach(key => {
                //         let item = SysData[key];
                //         let options = [];
                //         for (let {id, gnmc} of item) {
                //             options.push({
                //                 value: id,
                //                 label: gnmc
                //             })
                //         }
                //         vm.sysFeatureMenuTypeOptions.push({
                //             label: key,
                //             options: options
                //         });
                //     });
                //     Object.keys(CusData).forEach(key => {
                //         let item = CusData[key];
                //         let options = [];
                //         for (let {id, gnmc} of item) {
                //             options.push({
                //                 value: id,
                //                 label: gnmc
                //             })
                //         }
                //         vm.customFunctionMenuOptions.push({
                //             label: key,
                //             options: options
                //         });
                //     });
                // });
            },
            /**
             * 初始化表单、搜索条件数据
             */
            init() {
                let vm = this;
                vm.updateResourceId = vm.resourceId;
                vm.initLinkData();
                let arr = ['viewId', 'tabName', 'tabIcon', 'urlType', 'urlId', 'urlName', 'formviewName', 'formviewId', 'formviewShowtype',
                    'formTreeid', 'formTreename', 'url', 'parameter', 'sort', 'formCondition', 'menuGzljd', 'menuGzltabs'];
                arr.forEach(key => {
                    vm.$set(vm.crud.formData, key, "");
                });
                this.crud.searchForm["viewId"] = this.viewObj.id;
                this.crud.search();
            },
            /**
             * 链接类型变化清除表单数据
             */
            changeBindSource(val) {
                let vm = this;
                let obj = { // 切换清除数据
                    "sysFunciton": ["urlId", "urlName"],
                    "diyFunction": ["urlId", "urlName"],
                    "form": ["urlId", "formviewId", "urlName", "formviewName", "formCondition", "formviewShowtype", "formTreeid", "formTreename"],
                    "flow": ["urlId", "urlName", "menuGzljd", "menuGzltabs"],
                    "statReport": ["urlId", "urlName"],
                    "url": ["urlId"],
                };
                if (this.lastUrlType && obj[this.lastUrlType]) {
                    obj[this.lastUrlType].forEach(key => {
                        vm.$set(vm.crud.formData, key, "");
                    })
                }
                vm.$set(vm.crud.formData, "allOptAuth", false);
                vm.$set(vm.crud.formData, "allDataAuth", false);
                let operatePermis = [];
                let dataPermis = [];
                this.operationFormData = [];
                this.dataPermisFormData = [];
                this.allCheckOperateKeyArr = [];
                this.allCheckDataKeyArr = [];
                this.operationFormObj = {};
                this.dataPermisFormObj = {};
                this.refreshProper = this.COMMON_FUNC.getUuidByParams(32);

                if (val && val.length > 0) {
                    let length = val.length;
                    let resouceId = val[length - 1];
                    if (resouceId && this.urlTypeOptionObj[resouceId]) {
                        let obj = this.urlTypeOptionObj[resouceId];
                        operatePermis = obj.operatePermisList || []; //操作权限
                        dataPermis = obj.dataPermisList || []; //数据权限
                        let paramSetting = {};
                        paramSetting["id"] = "id";
                        paramSetting["pId"] = "parentId"; //上级数据
                        paramSetting["children"] = this.defaultProps["children"]; // 设置children可配置
                        this.operationFormData = this.COMMON_FUNC.buildElTree(operatePermis, paramSetting);
                        this.dataPermisFormData = this.COMMON_FUNC.buildElTree(dataPermis, paramSetting);
                        // //判断是否全选
                        //默认选中

                        if (this.$refs.operatePermisRef) {
                            this.$refs.operatePermisRef.setCheckedNodes([]);
                        }
                        if (this.$refs.dataPermisRef) {
                            this.$refs.dataPermisRef.setCheckedNodes([]);
                        }
                    }
                }
                //置空全选
                vm.$nextTick(() => {
                    if (vm.$refs.operatePermisRef) {
                        vm.$refs.operatePermisRef.setCheckedNodes([]);
                    }
                    if (vm.$refs.dataPermisRef) {
                        vm.$refs.dataPermisRef.setCheckedNodes([]);
                    }
                });
            },
            // 表单关联组件start
            /**
             * 设置tab页图标
             * @param icon 图标
             */
            getmenuIcon(icon) {
                let vm = this;
                if(icon.startsWith("el-icon-")){
                    vm.crud.formData.tabIcon = icon;
                    vm.currentIcon = icon;
                }else{
                    vm.crud.formData.tabIcon = 'saspiconfont ' + icon;
                    vm.currentIcon = 'saspiconfont ' + icon;
                }

                vm.iconDialog = false;
            },
            /**
             * 清除tab页图标
             */
            clearIcon() {
                let vm = this;
                vm.crud.formData.tabIcon = '';
                vm.currentIcon = '';
            },
            /**
             * 保存工作流选项卡配置
             * @param setting 配置字符串
             */
            saveFlowTabSetting(setting) {
                let vm = this;
                if (vm.crud.formData.id) { // 修改直接保存数据
                    vm.axios.post(vm.api.menu.update, {"id": vm.crud.formData.id, "menuGzltabs": setting});
                }
                vm.crud.formData.menuGzltabs = setting;
                vm.flowTabDialog = false;
            },
            /**
             * 工作流预览
             */
            flowPreview() {
                if (!this.crud.formData.menuGzltabs || "{}" === this.crud.formData.menuGzltabs) { // 没有数据则设置为默认配置项
                    this.crud.formData.menuGzltabs = JSON.stringify(this.defaultGzltabs);
                }
                this.flowPreviewDialog = true;
            },
            /**
             * 选择form
             * @param data 表单数据
             */
            chooseForm(data) {
                let {id, formId, formName, listTitle} = data;
                let formData = this.crud.formData;
                this.$set(formData, 'urlName', formName);
                formData.formviewName = listTitle;
                formData.formviewId = id;
                formData.urlId = formId;
                formData.formTreeid = "";
                formData.formTreename = "";
                this.$set(formData, 'formviewShowtype', "列表视图");
                this.axios.post('/formConditionController/find', { //列表视图条件定义
                    'viewId': id
                }).then(res => {
                    this.conditionOption = [];
                    for (let {id, condintionName} of res.data) {
                        this.conditionOption.push({
                            value: id,
                            label: condintionName
                        })
                    }
                });
                this.chooseFormDialog = false;
            },
            /**
             * 选择工作流
             * @param data 工作流数据
             */
            selectWorkFlowForm(data) {
                let formData = this.crud.formData;
                let {id, flowName} = data;
                formData.urlId = id;
                this.$set(formData, 'urlName', flowName);
                this.chooseFlowFormDialog = false;
                this.axios.post('/flowDefineNodeController/find', {
                    'sort': 'NODE_TYPE_EXTEND',
                    'flowId': id
                }).then(res => {
                    let workFlowNodeData = res.data;
                    this.workFlowNodeOptions = [];
                    for (let {id, nodeName} of workFlowNodeData) {
                        this.workFlowNodeOptions.push({
                            value: id,
                            label: nodeName
                        })
                    }
                });
            },
            /**
             * 开始选择树
             */
            chooseTree() {
                if (!this.crud.formData.formviewId) {
                    this.$message("尚未选择表单，请先选择表单后再进行操作！");
                    return;
                }
                this.chooseTreeDialog = true;
            },
            /**
             * 确定选择树
             * @param data 树数据
             * @param value 格式化后的名称
             */
            determinTree(data, value) {
                let formData = this.crud.formData;
                this.$set(formData, 'formTreeid', data.id);
                this.$set(formData, 'formTreename', value);
                this.chooseTreeDialog = false;
            },
            /**
             * 选择统计报表
             * @param data 报表数据
             */
            selectStatisticalForm(data) {
                let {id, reportName} = data;
                let formData = this.crud.formData;
                this.$set(formData, 'urlId', id);
                this.$set(formData, 'urlName', reportName);
                this.chooseStatisticalFormDialog = false;
            },
            //表单关联组件end
            /**
             * crud修改方法后的回调
             * @param formData
             */
            updateLoadData(formData) {
                this.currentIcon = formData.tabIcon || "";
                if (formData.urlType == 'flow') {
                    this.axios.post('/flowDefineNodeController/find', {
                        'order': 'NODE_TYPE_EXTEND ASC',
                        'flowId': formData.urlId
                    }).then(res => {
                        let workFlowNodeData = res.data;
                        this.workFlowNodeOptions = [];
                        for (let {id, nodeName} of workFlowNodeData) {
                            this.workFlowNodeOptions.push({
                                value: id,
                                label: nodeName
                            })
                        }
                    });
                }
                if (formData.menuGzljd) {
                    formData["menuGzljd"] = formData.split(","); // 工作流节点赋值为数组
                }

                if ((formData.urlType || "").indexOf('form') > -1 && formData["formviewId"]) { // 自定义表单加载条件
                    this.axios.post('/formConditionController/find', {
                        'viewId': formData["formviewId"]
                    }).then(res => {
                        this.conditionOption = [];
                        for (let {id, condintionName} of res.data) {
                            this.conditionOption.push({
                                value: id,
                                label: condintionName
                            })
                        }
                    });
                }
            },
            /**
             * 删除成功后的操作，这里主要是为了更新menuOpts
             */
            afterRemoveSuccess() {
                //根据 sourceId 删除 和 deleteId删除
                this.axios.post(this.api.resourcesPower.deleteResourcesPower, {
                    rkeys: this.deleteIdArr.join(","),
                    resourceId: this.updateResourceId
                })

            },
            /**
             * 提交表单数据
             */
            submitForm() {
                let vm = this;
                vm.$refs[vm.crud.addFormRef].validate(async valid => {
                    if (!valid) {
                        return;
                    }
                    let loading = vm.$loading({
                        target: vm.$refs[vm.crud.addFormRef].$el,
                        lock: true,
                        text: '请稍候...',
                        spinner: 'el-icon-loading',
                        background: 'rgba(0, 0, 0, 0.6)'
                    });

                    let formData = JSON.parse(JSON.stringify(vm.crud.formData || {}));

                    let optType = "update";
                    if (!formData["id"]) {
                        optType = "add";
                    }
                    if (formData["urlType"] && typeof formData["urlType"] == "object") {
                        formData["urlType"] = JSON.stringify(formData["urlType"] || {});
                    }
                    //保存数据权限和操作权限
                    //计算所有选中的数据权限和操作权限
                    if (vm.$refs.operatePermisRef) {
                        //遍历所有选中节点,判断下级是否选中，如果下级选中了则判断下下级，如果找不到下级或者下级未被选中 则保存当前节点id
                        let checkeOpertionArr = vm.$refs.operatePermisRef.getCheckedKeys(); //全选的节点
                        //递归过滤 isHalfOperationKeyArr
                        let opertionKeyArr = [];
                        this.initSelectKey(this.operationFormData, checkeOpertionArr, opertionKeyArr);
                        formData["operatePermis"] = opertionKeyArr.join(","); //操作权限
                    }

                    if (vm.$refs.dataPermisRef) {
                        let checkDataArr = vm.$refs.dataPermisRef.getCheckedKeys(); //选中的数据权限
                        let dataKeyArr = [];
                        this.initSelectKey(this.dataPermisFormData, checkDataArr, dataKeyArr);
                        formData["dataPermis"] = dataKeyArr.join(","); //数据权限
                    }

                    // 设置viewId
                    formData["viewId"] = vm.viewObj.id;
                    //保存数据

                    delete formData["createTime"];
                    delete formData["updateTime"];
                    vm.axios.post(vm.api.complextab.url + "/" + optType, formData).then(res => {
                        vm.$message({
                            duration: 1500,
                            type: 'success',
                            message: res.data.operateMessage
                        });
                        if (res.data.operateSuccess) { // 操作成功，修改MenuOpts
                            let obj = res.data.operateObj;
                            // vm.updateMenuOpts();
                            //注册到资源池
                            // vm.registeredResource(res.data.operateObj);
                            //获取当前选中的操作权限
                            let optArr = []; //保存的操作权限
                            let dataArr = []; //保存的数据权限


                            //保存tab 标签
                            optArr.push({
                                "type": 'opt',
                                'powerCode': obj.id,
                                'powerKey': obj.id,
                                'powerName': obj.tabName,
                                'parentId': '-1',
                                'parentTree': '-1',
                            });
                            dataArr.push({
                                "type": 'data',
                                'powerCode': obj.id,
                                'powerKey': obj.id,
                                'powerName': obj.tabName,
                                'parentId': '-1',
                                'parentTree': '-1',
                            });
                            let resourceParam = {
                                rType: 'page', //url页面资源
                                rName: this.viewObj.viewName, //功能名称
                                rKey: this.viewObj.id, //唯一
                                externalAccess: '0',
                                noLoginRequired: '1',//默认不需要登录
                                passSwitch: '0',
                                rSource: 'cview', //资源类型 复合视图
                                rClass: '复合视图',
                                rClassId: '-1',
                                operatePermis: JSON.stringify(optArr), //操作权限
                                dataPermis: JSON.stringify(dataArr), //数据权限
                                rStatus: '1',
                                pPowerKey: obj.id,
                                operateKeys: formData["operatePermis"],
                                dataKeys: formData["dataPermis"]
                            };
                            this.axios.post(this.api.resources.saveOrUpdateRsources, resourceParam).then(res => {
                                //刷新资源池更新 sourceId
                                if (res.data && res.data.operateObj) {
                                    this.updateResourceId = (res.data.operateObj || {}).id;
                                }
                            });
                        }
                        vm.$refs[vm.crud.addFormRef].clearValidate();
                        vm.crud.search();
                        loading && loading.close();
                        vm.crud.dialogVisible = false;
                    });
                })
            },
            /**
             * 修改menuOpts
             */

            /**
             * 注册or保存到资源池
             */


            update(row) { //修改复合视图
                let vm = this;
                //修改 row,urlType
                if (row.urlType && typeof row.urlType == 'string') {
                    this.$set(row, 'urlType', JSON.parse(row.urlType));
                }
                //初始化数据权限和操作权限
                this.changeBindSource(row.urlType);
                vm.crud.update(row);
                this.$set(this.crud.formData, 'allOptAuth', true); //操作权限
                this.$set(this.crud.formData, 'allDataAuth', true); //数据权限
                //默认选中
                vm.$nextTick(() => {
                    let opeateKeyArr = (row.operatePermis || '').split(","); //权限id用逗号拼接
                    let dataKeyArr = (row.dataPermis || '').split(","); //权限id用逗号拼接
                    if (this.$refs.operatePermisRef) { //选中操作权限
                        this.$refs.operatePermisRef.setCheckedKeys(opeateKeyArr);
                        //获取半选
                        if (this.operationFormData.length == 0) {
                            this.$set(vm.crud.formData, 'allOptAuth', false); //操作权限
                        }
                        this.operationFormData.some(item => {
                            if (opeateKeyArr.indexOf(item.id) == '-1') {
                                this.$set(vm.crud.formData, 'allOptAuth', false); //操作权限
                                return true;
                            }
                        });
                    }
                    if (this.$refs.dataPermisRef) { //选中数据权限
                        this.$refs.dataPermisRef.setCheckedKeys(dataKeyArr);
                        //获取半选
                        if (this.dataPermisFormData.length == 0) {
                            this.$set(vm.crud.formData, 'allDataAuth', false); //操作权限
                        }
                        this.dataPermisFormData.some(item => {
                            if (dataKeyArr.indexOf(item.id) == '-1') {
                                this.$set(vm.crud.formData, 'allDataAuth', false); //操作权限
                                return true;
                            }
                        });
                    }
                    //初始化树选中
                    // let checkOperateKeyArr = [];
                    // let checkDataKeyArr = [];
                    // this.initTreeCheck(row.operatePermis || [],checkOperateKeyArr); //操作权限
                    // this.initTreeCheck(row.dataPermis || [],checkDataKeyArr); //数据权限
                    // if(this.$refs.operatePermisRef){ //选中操作权限
                    //     this.$refs.operatePermisRef.setCheckedKeys(checkOperateKeyArr);
                    // }
                    // if(this.$refs.dataPermisRef){//选中数据权限
                    //     this.$refs.dataPermisRef.setCheckedKeys(checkDataKeyArr);
                    // }
                    // //判断是否全选 当前获取当前选中的数据 checkOperateKeyArr 和树数据比较 operationFormData
                    // let  halfOperatArr = vm.$refs.operatePermisRef.getHalfCheckedNodes(); //获取操作半选
                    // let  halfDataArr = vm.$refs.dataPermisRef.getHalfCheckedNodes(); //获取操作半选
                    // this.isAllOptCheck(this.operationFormData,halfOperatArr,this.allCheckOperateKeyArr);
                    // this.isAllDataCheck(this.dataPermisFormData,halfDataArr,this.allCheckDataKeyArr);
                });
            },

            /**
             * 操作权限判断全选
             */
            isAllOptCheck(formTreeArr, halfArr, allCheckArr) {
                if (formTreeArr.length == 0 || halfArr.length > 0) {
                    this.$set(this.crud.formData, 'allOptAuth', false);
                } else {
                    formTreeArr.some(item => { //判断是否选中
                        if (allCheckArr.indexOf(item.key) > -1) {
                            formTreeArr = item["childrens"];
                            if (formTreeArr) {
                                this.isAllOptCheck(formTreeArr, halfArr, allCheckArr);
                            }
                        } else {
                            this.$set(this.crud.formData, 'allOptAuth', false);
                            return true; //终止
                        }
                    });
                }
            },

            /**
             * 数据权限判断全选
             */
            isAllDataCheck(formTreeArr, halfArr, allCheckArr) {
                if (formTreeArr.length == 0 || halfArr.length > 0) {
                    this.$set(this.crud.formData, 'allDataAuth', false);
                } else {
                    formTreeArr.some(item => { //判断是否选中
                        if (allCheckArr.indexOf(item.key) > -1) {
                            formTreeArr = item["childrens"];
                            if (formTreeArr) {
                                this.isAllDataCheck(formTreeArr, halfArr, allCheckArr);
                            }
                        } else {
                            this.$set(this.crud.formData, 'allDataAuth', false);
                            return true; //终止
                        }
                    });
                }
            },

            /**
             * 新增复合视图
             */
            add() {
                //清空数据权限和操作权限
                this.operationFormData = [];
                this.dataPermisFormData = [];
                this.$set(this.crud.formData, 'allOptAuth', false); //操作权限
                this.$set(this.crud.formData, 'allDataAuth', false); //数据权限
                this.$set(this.crud.formData, 'tabIcon', '');
                this.currentIcon = '';//清空图标
                this.crud.add();
            },

            /**
             * 删除复合视图
             */
            remove() {
                //删除事件
                this.deleteIdArr = [];
                let selection = this.$refs[this.crud.tableRef].selection || [];
                selection.forEach(item => {
                    this.deleteIdArr.push(item.id);
                });
                this.crud.remove();
            },

            /**
             * 保存数据权限和操作权限树
             */
            saveOptAndData(submitObj) {
                let vm = this;
                //计算所有选中的数据权限和操作权限
                let checkeOpertionArr = []; //全选操作权限
                let halfOperatArr = []; //半选操作权限
                let checkDataArr = [];
                let halfCheckArr = [];//半选数据权限
                if (vm.$refs.operatePermisRef) {
                    this.isHalfOperationKeyArr = [];
                    this.isAllOperationKeyArr = [];
                    checkeOpertionArr = vm.$refs.operatePermisRef.getCheckedNodes(); //全选
                    halfOperatArr = vm.$refs.operatePermisRef.getHalfCheckedNodes(); //获取半选
                    let keyOperateArr = vm.$refs.operatePermisRef.getCheckedKeys(); //获取当前完全勾选的节点

                    let copyCheckeOpertionArr = JSON.parse(JSON.stringify(checkeOpertionArr || []));
                    let copyHalfOperatArr = JSON.parse(JSON.stringify(halfOperatArr || []));
                    let copyKeyOperateArr = JSON.parse(JSON.stringify(keyOperateArr));

                    this.deleteAllCheckOpertion(copyCheckeOpertionArr, copyKeyOperateArr);
                    //循环半选的
                    this.disabelHalNoUseData(copyHalfOperatArr, copyKeyOperateArr);
                    let allOperateData = copyCheckeOpertionArr.concat(copyHalfOperatArr);
                    allOperateData = this.filterIsHalfOperation(allOperateData, this.isHalfOperationKeyArr, this.isAllOperationKeyArr);
                    submitObj["operatePermis"] = allOperateData;
                    //递归过滤 isHalfOperationKeyArr
                }

                if (vm.$refs.dataPermisRef) {
                    this.isHalfOperationKeyArr = []; //
                    this.isAllOperationKeyArr = [];
                    checkDataArr = vm.$refs.dataPermisRef.getCheckedNodes();
                    halfCheckArr = vm.$refs.dataPermisRef.getHalfCheckedNodes(); //获取半选
                    let keyDataArr = vm.$refs.operatePermisRef.getCheckedKeys(); //获取当前完全勾选的节点
                    let copyCheckDataArr = JSON.parse(JSON.stringify(checkDataArr || []));
                    let copyHalfCheckArr = JSON.parse(JSON.stringify(halfCheckArr || []));
                    let copyKeyDataArr = JSON.parse(JSON.stringify(keyDataArr));
                    this.deleteAllCheckOpertion(copyCheckDataArr, copyKeyDataArr);
                    this.disabelHalNoUseData(copyHalfCheckArr, copyKeyDataArr);
                    let allData = copyCheckDataArr.concat(copyHalfCheckArr);
                    allData = this.filterIsHalfOperation(allData, this.isHalfOperationKeyArr, this.isAllOperationKeyArr);
                    submitObj["dataPermis"] = allData;
                }
                //数据权限 和操作权限
                if (submitObj['operatePermis'] && typeof submitObj["operatePermis"] == "object") {
                    submitObj["operatePermis"] = JSON.stringify(submitObj["operatePermis"]);
                }
                if (submitObj['dataPermis'] && typeof submitObj["dataPermis"] == "object") {
                    submitObj["dataPermis"] = JSON.stringify(submitObj["dataPermis"]);
                }
            },


            /**
             *  删除已经子数据
             * @param allCheckArr
             * @param keyArr
             */
            deleteAllCheckOpertion(allArr, keyArr) {
                allArr.forEach(item => {
                    this.$set(item, 'enable', true); //默认节点可用
                    if (item["childrens"]) {
                        (item["childrens"] || []).forEach((child, index) => {
                            if (keyArr.indexOf(child.key) > -1) { //删除当前数据
                                this.isAllOperationKeyArr.push(child.key);
                            }
                            allArr = item["childrens"];
                            this.deleteAllCheckOpertion(allArr, keyArr);
                        })
                    }
                });
            },

            /**
             * 递归半选中无用数据
             * @param halfOperatArr
             * @param keyArr
             */
            disabelHalNoUseData(halfOperatArr, keyArr) {
                halfOperatArr.forEach(item => {
                    if (item["childrens"]) {
                        (item["childrens"] || []).forEach((child, index) => {
                            if (keyArr.indexOf(child.key) == -1) { //设置当前节点 isCheked：false
                                // this.$set(child,'enable',false); //设置节点为不可用状态
                                item["childrens"].splice(index, 1);
                                keyArr.splice(index, 1);
                            } else {
                                this.$set(child, 'enable', true);
                                ;//设置可编辑状态
                                this.isHalfOperationKeyArr.push(child.key);
                            }
                            halfOperatArr = item["childrens"];
                            this.disabelHalNoUseData(halfOperatArr, keyArr);
                        })
                    }
                });
            },

            /**
             * 过滤全选数据
             */
            filterIsHalfOperation(checkeOpertionArr, isHalfOperationKeyArr, isAllOperationKey) {
                checkeOpertionArr = checkeOpertionArr.filter(item => {
                    return isHalfOperationKeyArr.indexOf(item.key) == -1 && isAllOperationKey.indexOf(item.key) == -1;
                });

                return checkeOpertionArr;
            },

            /**
             * 操作权限全选
             */
            optChange(val) {
                //全选或取消全选
                if (val) {
                    //全部勾选
                    this.$refs.operatePermisRef.setCheckedNodes(this.operationFormData);
                } else {
                    //取消全部勾选
                    this.$refs.operatePermisRef.setCheckedNodes([]);
                }
            },

            /**
             * 数据权限全选
             */
            dataChange(val) {
                //全选或取消全选
                if (val) {
                    //全部勾选
                    this.$refs.dataPermisRef.setCheckedNodes(this.dataPermisFormData);
                } else {
                    //取消全部勾选
                    this.$refs.dataPermisRef.setCheckedNodes([]);
                }
            },

            /**
             * 获取parentId
             */
            setFormDataParentId(dataArr, parentId, allKeyArr) {
                dataArr.forEach(item => {
                    this.$set(item, 'pId', parentId);
                    this.$set(item, 'enable', true); //默认节点可用
                    let parentTree = parentId;
                    if (item.parentTree) {
                        parentTree = item.parentTree + "," + parentId;
                    }
                    this.$set(item, 'parentTree', parentTree);
                    allKeyArr.push(item['key']);
                    if (item["childrens"]) { //
                        dataArr = item["childrens"];
                        parentId = item["key"];
                        this.setFormDataParentId(dataArr, parentId, allKeyArr);
                    }
                });
            },

            /**
             * 初始化树选中
             */
            initTreeCheck(dataArr, keysArr) {
                (dataArr || []).forEach(item => {
                    if (!item["childrens"]) { //因为下级全部选中上级自动选中，所以不用考虑上级
                        // this.$refs.operatePermisRef.setCheckedKeys([item['key']]);
                        if (item['enable']) { //当前已选择
                            keysArr.push(item['key']);
                        }
                    }
                    if (item["childrens"]) {
                        this.initTreeCheck(item["childrens"], keysArr);
                    }
                })
            },

            /**
             * 格式化链接类型
             * @param urlType
             * @returns {string}
             */
            formatterUrlType(urlType) {
                let result = '';
                if (urlType) {
                    if (typeof urlType == 'string') {
                        let obj = JSON.parse(urlType);
                        result = this.optionObj[obj[0]];
                    } else {
                        result = this.optionObj[urlType[0]];
                    }
                }
                return result;
            },


            /**
             * 操作权限点击事件
             * @param data
             * @param checked
             */
            checkeOptChangeFnc(data, checked) {
                this.$set(this.crud.formData, 'allOptAuth', true); //操作权限
                let keysArr = [];
                if (this.$refs.operatePermisRef) {
                    keysArr = this.$refs.operatePermisRef.getCheckedKeys();
                }
                this.operationFormData.some(item => {
                    if (keysArr.indexOf(item.id) == '-1') {
                        this.$set(this.crud.formData, 'allOptAuth', false); //操作权限
                        return true;
                    }
                });
            },
            /**
             * 数据全选点击全选判断
             * @param data
             * @param checked
             */
            checkeDataChangeFnc(data, checked) {
                this.$set(this.crud.formData, 'allDataAuth', true); //数据权限
                //获取半选
                let keysArr = [];
                if (this.$refs.dataPermisRef) {
                    keysArr = this.$refs.dataPermisRef.getCheckedKeys();
                }
                this.dataPermisFormData.some(item => {
                    if (keysArr.indexOf(item.id) == '-1') {
                        this.$set(this.crud.formData, 'allDataAuth', false); //操作权限
                        return true;
                    }
                });

            },

            /**
             * 递归生成 树的 parentId 和 parentTree
             * @param treeArr
             */
            initParentIdAndParentTree(treeArr, pId) {
                (treeArr || []).forEach(item => {
                    this.$set(item, 'parentId', pId);
                    let parentTree = pId || "";
                    if (item.parentTree) {
                        parentTree = item.parentTree + "," + pId;
                    }
                    this.$set(item, 'parentTree', parentTree);
                    if (item.children) {
                        treeArr = item.children;
                        pId = item.id;
                        this.initParentIdAndParentTree(treeArr, pId);

                    }
                });

            },

            /**
             * 获取选中的
             */
            initSelectKey(treeArr, selectKeyArr, opertionKeyArr) {
                treeArr.forEach(item => {
                    if (!item.children||item.children.length==0) {
                        if (selectKeyArr.indexOf(item.id) > -1) {
                            opertionKeyArr.push(item.id);
                        }
                    } else {
                        treeArr = item["children"];
                        this.initSelectKey(treeArr, selectKeyArr, opertionKeyArr);
                    }
                });

            },

            /**
             * 操作权限
             * @param h
             * @param node
             * @param data
             * @param store
             * @returns {*}
             */
            renderOperateContent(h, { node, data, store }) {
                let type = "按钮";
                if(data.powerKey.indexOf("tree") > -1){
                    type = "树"
                }
                return (
                    <span >
                    <span>{node.label}</span>
                    <span class="custom-operate-tree-node">
                      ({type})
                    </span>
                  </span>);
            },
        }
    }
</script>

<style scoped lang="scss">
    .box-card-class {
        width: 350px;
        height: 350px;
        overflow-y: auto;
        padding-bottom: 10px;
    }

    .tree {
        overflow-y: auto;
        height: 220px;
    }

    .tree ::v-deep .el-tree {
        　　.el-tree-node__content {
            　　　　display: block !important;
        }

        　　.el-tree-node__children {
            　　　　overflow: visible !important;
        }
    }
    .tree ::v-deep.custom-operate-tree-node {
        margin-left: 10px;
        font-size: 11px;
        color: #409EFF;
    }
</style>
