<template>
    <el-tabs type="border-card" style="height: 100%" class="complex-tabs" v-model="activeName" @tab-click="tabClick" v-if="!isPrint">
        <el-tab-pane v-for="(item,index) in tagArrs" :key="index" :name="index + ''" v-if="tabSize>0 && (tagArrs.length == tabSize || tagArrs.length == tabSettingArrSize)">
            <span slot="label"><i :class="item.tabIcon"></i>{{item.tabName}}</span>
            <div class="p-tab-view">
                <pl-lazy v-if="setClickTab.has(index + '')  && refreshTab[index + '']">
                    <!--外部超链接-->
                    <ifm-link v-if="item.tabType == 'url' && (item.rangetUrl.indexOf('http://') > -1 || item.rangetUrl.indexOf('https://') > -1) "
                              :link-url="item.rangetUrl">
                    </ifm-link>
                    <!--内部也main链接超链接 -->
                    <keep-alive v-else-if="item.tabType == 'url' && item.rangetUrl.indexOf('http://') == -1 && item.rangetUrl.indexOf('https://') == -1 ">
                        <!--内部链接赋值操作权限和数据权限 -->
                        <component :is="activeIndex"
                                   :optArr="item.operatePermis"
                                   :dataArr="item.dataPermis"
                                   :isRefresh="isRefresh"
                                   :listOutParam="item.listOutParam ||{}"
                                   style="height: 100%" ></component>
                    </keep-alive>
                    <component v-else
                               :is="VIEW_COMPONENTS[item.tabType].complex"
                               :listOutParam="item.listOutParam ||{}"
                               :equilibriumData="item.equilibriumData || {}"
                               :parentFormData="parentFormData"
                               :isCompositeView="isCompositeView"
                               :compositeObj="compositeObj"
                               :refreshPreview="refreshPreview"
                               :refreshPage="refreshPage"
                               :compositeFormOperate="compositeFormOperate"
                               :setting-data="item"></component>

                </pl-lazy>
            </div>
        </el-tab-pane>
    </el-tabs>
    <div v-else>
        <div  v-for="(tagArrs,index) in tagPrintArr" :key="index" style="height: 100%">
            <el-tabs type="border-card" style="height: 100%" class="complex-tabs" v-model="printActiveName" @tab-click="tabClick">
                <el-tab-pane v-for="(item,index) in tagArrs" :key="index" :name="index + ''" v-if="tabSize>0 && tagArrs.length == 1">
                    <span slot="label"><i :class="item.tabIcon"></i>{{item.tabName}}</span>
                    <div class="p-tab-view">
                            <!--外部超链接-->
                            <ifm-link v-if="item.tabType == 'url' && (item.rangetUrl.indexOf('http://') > -1 || item.rangetUrl.indexOf('https://') > -1) "
                                      :link-url="item.rangetUrl">
                            </ifm-link>
                            <!--内部也main链接超链接 -->
                            <keep-alive v-else-if="item.tabType == 'url' && item.rangetUrl.indexOf('http://') == -1 && item.rangetUrl.indexOf('https://') == -1 ">
                                <!--内部链接赋值操作权限和数据权限 -->
                                <component :is="activeIndex"
                                           :optArr="item.operatePermis"
                                           :dataArr="item.dataPermis"
                                           :isRefresh="isRefresh"
                                           :listOutParam="item.listOutParam ||{}"
                                           style="height: 100%" ></component>
                            </keep-alive>
                            <component v-else
                                       :is="VIEW_COMPONENTS[item.tabType].complex"
                                       :listOutParam="item.listOutParam ||{}"
                                       :equilibriumData="item.equilibriumData || {}"
                                       :parentFormData="parentFormData"
                                       :isCompositeView="isCompositeView"
                                       :compositeObj="compositeObj"
                                       :refreshPreview="refreshPreview"
                                       :refreshPage="refreshPage"
                                       :compositeFormOperate="compositeFormOperate"
                                       :setting-data="item"></component>
                    </div>
                </el-tab-pane>
            </el-tabs>

        </div>
    </div>

</template>

<script>
    import IfmLink from "./ifmLink";

    //注：自定义功能 请放置在 views/framework 文件夹下。  后台配置自定义功能路径 例如 config/task/personalTask

    export default {
        name: "complex-view-rendering",
        props: {
            resourceId:{ //资源id
                type:String,
                default:''
            },
            operatePermis:{type :String, default:""}, //操作权限
            dataPermis:{type :String,default:""}, //数据权限
            id: {
                type: String,
                default: ""
            },
            menuId: {
                type: String,
                default: ""
            },
            isSup: {
                type: Boolean,
                default: false
            },
            listOutParam:{type:Object,default:() => {return {};}}, //外部传入参数
            tabSettingArr:{type:Array,required:false,default:() => {return [];}},//选择页签
            isCompositeView:{type: Boolean, default: false,required:false},//是否是复合视图组件
            equilibriumObj:{type:Object,default:() => {return {};}},
            parentFormData:{type:Object,default:() => {return {};}}, //父级表单对象
            equiliInfoObj:{type:Object,default:() => {return {};}},//用于监听值改变
            refreshUUId:{type:Object,default:()=>{return {};}},
            compositeObj:{type:Object,default:()=>{return {};}}, //用户监听刷新
            compositeFormOperate:{type:String,default:''}, //表单操作状态
        },
        components: {
            IfmLink
        },
        data() {
            return {
                tagArrs: [],
                activeName: '0',
                activeTabId:'', //当前选择的tabId
                operationJson: "",
                activeIndex:{},
                isRefresh:this.COMMON_FUNC.getUUID(),
                setClickTab: new Set(["0"]), // 当前已被点击的选项卡
                resourceObj:{}, //资源池对象
                viewId:"", //复合视图模块id
                operatePermisObj:{},//操作权限 Obj
                dataPermisObj:{}, //数据权限 Obj
                allRouterArr:this.$router.options.routes || [], //所有router配置
                activeUrl: '',//实际路径
                userType:'', //登录用户类型
                tabSize:0,//
                autoRefresh:false,
                refreshTab: {},
                tabSettingArrSize:0,//复合视图组件 tab个数
                refreshPreview:'', //刷新表格数据
                refreshPage:'', //刷新页面
                tagPrintArr:[],
                isPrint:false, //是否为打印 打印状态时候tag标签向下遍历
                printActiveName:'0',//打印时候每个标签页只有一个

            }
        },
        created() {
            let loginUser = this.CACHE_GLOBAL.getLoginUser() || {};
            this.RES_GLOBAL.getById(this.resourceId,loginUser.userType).then(res =>{
                this.resourceObj[res.id] = res;
                this.executShow();
            });
            if(this.isCompositeView){
                Object.keys(this.equiliInfoObj).forEach(key=>{
                    this.$watch(function () {
                        return this.equiliInfoObj[key];
                    },function () {
                        this.executShow().then(()=>{
                            let nowTab = this.tagArrs[this.activeName] || {};
                            if(nowTab.id != this.activeTabId){
                                //当前tab 还没有查询
                                this.tabClick({name:this.activeName});
                            }
                        });
                    } );
                });
            }
        },
        watch: {
            tabSettingArr(){
                let tabLength = this.tabSettingArr.length;
                if(tabLength <= Number(this.activeName) && tabLength > 0){
                    this.activeName = (tabLength - 1) + '';
                    this.activeTabId = (this.tabSettingArr[this.activeName] || {}).id || '';
                    this.tabClick({name:this.activeName});
                }
                this.executShow();//展示
            },

            resourceId(){
                this.executShow();//展示
            },
            activeName(){ //点击tab 标签跳转
                //执行跳转
                let obj = this.tagArrs[this.activeName] || {};
                let urlType = JSON.parse(obj.urlType || '[]');
                // if(urlType.length > 0 && urlType[0] == 'url'){
                if(urlType.length > 0 && urlType[0] == 'url' && (obj.rangetUrl || '').indexOf('http://') == -1 && (obj.rangetUrl || '').indexOf('https://') == -1 ){
                    let url = obj.rangetUrl || '';
                    this.isRefresh = this.COMMON_FUNC.getUUID();
                    this.activeUrl = '';
                    //递归遍历 router 路由 判断当前路由是否存在
                    let urlArr = url.split("/");
                    this.eachRouterSet(this.allRouterArr,urlArr,0);
                }
                // }
            },
            tagArrs(){
                if(this.tagArrs && this.tagArrs.length > 0){
                    //vue动态import组件
                    let obj = this.tagArrs[this.activeName] || {};
                    let urlType = JSON.parse(obj.urlType || '[]');
                    // if(urlType.length > 0 && urlType[0] == 'url'){
                    if(urlType.length > 0 && urlType[0] == 'url' && (obj.rangetUrl || '').indexOf('http://') == -1 && (obj.rangetUrl || '').indexOf('https://') == -1){
                        let url = obj.rangetUrl || '';
                        this.isRefresh = this.COMMON_FUNC.getUUID();
                        this.activeUrl = '';
                        //递归遍历 router 路由 判断当前路由是否存在
                        if(url){
                            let urlArr = url.split("/");
                            this.eachRouterSet(this.allRouterArr,urlArr,0);
                        }
                    }
                    // }
                }
            },
            isPrintParam:function (old,newd) {
                this.isPrint = !this.isPrint;
                //更新 tagPrintArr;
                if(this.isPrint){
                    //遍历 this.tagArrs 赋值
                    this.tagPrintArr = [];
                    this.tagArrs.forEach(item =>{
                        this.tagPrintArr.push([item]);
                    });
                }else {
                    this.executShow();//展示
                    this.tagPrintArr = [];
                }
            },
        },
        
        computed:{
            isPrintParam(){
                return this.$store.state.user.isPrintParam;
            }
        },


        methods: {
            /**
             * 遍历匹配路由
             * allRouterArr当前路由 arr，
             * urlArr 链接arr
             * index遍历层数
             */
            eachRouterSet(allRouterArr,urlArr,index){
                allRouterArr.forEach(item =>{
                    // if(urlArr[index + 1]){
                    if(urlArr[index + 1] && urlArr[index +1] == (item.name ? item.name : item.path)){
                        //当前匹配
                        //判断 urlArr是否存在下级
                        if(index+2 >= urlArr.length){ //则当前地址为我需要的实际地址
                            let componentString = item.component.toString();
                            let arr = componentString.split("\"");
                            this.activeUrl = arr[arr.length - 2] || '';
                            this.activeIndex = item.component;
                        }else if(item.children && item.children.length > 0) {
                            //如果存在下级
                            allRouterArr = item.children || [];
                            index = index + 1;
                            this.eachRouterSet(allRouterArr,urlArr,index);
                        }
                    }
                    // }
                })
            },

            /**
             * 复合视图展示
             */
            executShow(){
                return new Promise(resolve => {
                    if(this.resourceId && this.resourceObj[this.resourceId]){
                        //作为跳板,跳转到 compelxRednding 复合视图预览页面
                        let resourceObj = this.resourceObj[this.resourceId];
                        let url = resourceObj.ragentUrl || '';
                        //根据 resourceObj 获取
                        //查询相关选项卡
                        //获取数据权限
                        let operateKeysArr = (this.operatePermis || '').split(",");
                        let dataKeysArr = (this.dataPermis || '').split(",");
                        let operateArr = []; //数据权限
                        let dataArr = []; //操作权限
                        let alloperatePermisObj = {};
                        let allDataPermisObj = {};
                        (resourceObj.operatePermisList || []).forEach(item =>{
                            alloperatePermisObj[item.id] = item;
                            if(operateKeysArr.indexOf(item.id) > -1){
                                operateArr.push(item);
                            }
                        });
                        (resourceObj.dataPermisList || []).forEach(item =>{
                            allDataPermisObj[item.id] = item;
                            if(dataKeysArr.indexOf(item.id) > -1){
                                dataArr.push(item);
                            }
                        });
                        this.axios.post(this.api.complex.getById,{id:resourceObj.rkey}).then(complexRes => {
                            this.autoRefresh = (complexRes.data || {}).autoRefresh == "1";
                            this.axios.post(this.api.complextab.getTabsById,{ "viewId": resourceObj.rkey || '',
                                "order": "SORT ASC"}).then(async res =>{
                                if(res && res.data){
                                    this.tagPrintArr = [];

                                    this.tagArrs = [];
                                    this.tabSize = 0;
                                    (res.data || []).forEach(tab =>{
                                        this.$set(tab,'equilibriumData',{});
                                        //获取选项卡类型， 根据选项卡类型进行跳转（选项卡的操作权限和数据权限也要加上）
                                        if(tab.urlType){
                                            let urlTypeArr = JSON.parse(tab.urlType || '[]');
                                            //根据子页面的信息获取相关资源池中的信息
                                            let tabType = urlTypeArr[0];
                                            let tabResourceId = urlTypeArr[urlTypeArr.length -1];
                                            let tabResourceObj = {};
                                            let tabData = tab['dataPermis'];//数据权限
                                            //获取页面的注册地址
                                            this.RES_GLOBAL.getById(tabResourceId,this.userType).then(res =>{
                                                tabResourceObj = res;
                                                let rangetUrl = tabResourceObj.ragentUrl || ''; //资源地址
                                                this.$set(tab,'rangetUrl',rangetUrl); //赋值资源地址
                                                this.$set(tab,'tabType',tabType); //赋值标签项类型
                                                //判断操作权限和数据权限
                                                let operateKeyArr = [];
                                                let dataKeyArr = [];
                                                this.$set(tab,'operatePermis',operateKeyArr); //操作权限
                                                this.$set(tab,'dataPermis',dataKeyArr); //操作权限
                                                let hasOperate = false; //存在操作权限
                                                let hasData = false; //存在数据权限
                                                (operateArr || []).forEach(item =>{ //操作权限
                                                    // if(alloperatePermisObj[item['parentId']]){
                                                    if(alloperatePermisObj[item['parentId']] && alloperatePermisObj[item['parentId']].powerKey == tab.id){ //当前标签下的权限
                                                        hasOperate = true;
                                                        operateKeyArr.push(item.powerCode);
                                                    }
                                                    // }
                                                });
                                                if(hasOperate){ //如果存在操作权限
                                                    this.$set(tab,'operatePermis',operateKeyArr); //操作权限
                                                }
                                                (dataArr || []).forEach(item =>{ //数据权限
                                                    if(allDataPermisObj[item['parentId']] && allDataPermisObj[item['parentId']].powerKey  == tab.id){ //当前标签下的权限
                                                        hasData = true;
                                                        dataKeyArr.push(item.powerCode);
                                                    }
                                                });
                                                if(hasData){ //如果
                                                    this.$set(tab,'dataPermis',dataKeyArr); //操作权限
                                                }
                                                if(tab['tabType'] == 'form'){ //智能建表
                                                    //赋值条件定义
                                                    let formDefineKey = tabResourceObj.rclassId;
                                                    let listViewDefineKey = tabResourceObj.rkey;
                                                    this.FORM_GLOBAL.findListNewVersion({formDefineKey:formDefineKey,defineKey:listViewDefineKey}).then(res =>{
                                                        let resData = res.data ||{};
                                                        let listViewId = resData.id || ''; //表单视图的 definkeKey
                                                        let formId = resData.formId || ''; //表单id definkeKey
                                                        let conditionId = []; //数据权限
                                                        if(tab['operatePermis']){ //存在操作权限
                                                            let operateObj = {};
                                                            let operatePermisArr = [];
                                                            if(typeof  tab['operatePermis'] == "string"){
                                                                operatePermisArr = (tab['operatePermis'] || "").split(",");
                                                            }else{
                                                                operatePermisArr = tab['operatePermis']|| []
                                                            }
                                                            operatePermisArr .forEach(key =>{
                                                                operateObj[key] = true;
                                                            });
                                                            this.$set(tab,'operateAuthority',operateObj);
                                                        }

                                                        if(tabData){ //存在数据权限
                                                            let tabDataArr = [];
                                                            if(typeof tabData == 'string'){
                                                                tabDataArr = (tabData || "").split(",");
                                                            }else{
                                                                tabDataArr = tabData || [];
                                                            }

                                                            let tabRermis = tabResourceObj["dataPermisList"];//取出数据权限集合
                                                            let tabRermisArr = [];
                                                            tabDataArr.forEach(data =>{
                                                                tabRermis.forEach(item =>{//遍历数据权限集合
                                                                    if(data == item["id"]){ //数据权限跟
                                                                        tabRermisArr.unshift(item.powerKey);//数据权限powerKey
                                                                    }
                                                                })

                                                            })
                                                            conditionId = tabRermisArr || [];
                                                        }
                                                        this.$set(tab,'formId',formId);
                                                        this.$set(tab,'listViewId',listViewId);
                                                        //条件定义id
                                                        this.$set(tab,'conditionId',conditionId.join(","));
                                                        this.tabSize++;

                                                        resolve();
                                                    });
                                                }else if(tab['tabType'] == 'flow'){ //工作流
                                                    let flowId = tabResourceObj.rkey;
                                                    let resOptList = tabResourceObj.operatePermisList;
                                                    let optMap = {};
                                                    if(resOptList&&resOptList.length>0){
                                                        resOptList.forEach(item=>{
                                                            optMap[item.powerKey]=item.powerCode;
                                                        })
                                                    }
                                                    this.FLOW_GLOBAL.getFlowDefineById(flowId).then(flowObj =>{
                                                        this.$set(tab,'flowObj',flowObj);
                                                        if(tab['operatePermis']){ //存在操作权限
                                                            let operatePermisArr = [];
                                                            let operateRootArr = [];
                                                            if(typeof  tab['operatePermis'] == "string"){
                                                                operatePermisArr = (tab['operatePermis'] || "").split(",");
                                                            }else{
                                                                operatePermisArr = tab['operatePermis']|| []
                                                            }
                                                            operatePermisArr.forEach(operateKey =>{
                                                                if(optMap.hasOwnProperty(operateKey)){
                                                                    operateRootArr.push({"powerCode":optMap[operateKey]});
                                                                }
                                                            });
                                                            this.$set(tab,'operateRootArr',operateRootArr);
                                                        }
                                                        this.$set(tab,'flowId',flowId);
                                                        this.tabSize++;
                                                        resolve();
                                                    });
                                                }else {
                                                    this.tabSize++;
                                                }

                                            });
                                            //解析相关外部参数
                                            if(!tab.listOutParam){
                                                tab.listOutParam = Object.assign(this.listOutParam,{}); //外部
                                            }
                                            if(!tab.equilibriumData){
                                                this.$set(tab,'equilibriumData',{});
                                            }
                                            let equiliObj ={};
                                            Object.keys(this.equilibriumObj).forEach(tabKey =>{
                                                if(tabKey == tab.id){
                                                    (this.equilibriumObj[tabKey]||[]).forEach(item =>{
                                                        if(item.paramKey.indexOf("listoutCondition_") == -1){
                                                            this.$set(tab.listOutParam,item.paramKey,item.paramValue); //传入外部参数
                                                        }else {
                                                            let params = item.paramKey.split("listoutCondition_")[1];
                                                            this.$set(equiliObj,params,item.paramValue);
                                                        }
                                                    });
                                                }
                                            });
                                            if(equiliObj.hasOwnProperty('conditionId')){ //传入
                                                Object.assign(tab.equilibriumData,equiliObj);
                                                this.refreshPreview = this.COMMON_FUNC.getUuidByParams(32);
                                            }

                                            this.tagArrs.push(tab);
                                        }
                                    });
                                    if(this.isCompositeView){//是否是复合视图组件
                                        let arr = [];
                                        this.tabSettingArrSize = 0;
                                        (this.tabSettingArr || []).forEach(item=>{//遍历复合视图组件传的tab
                                            (this.tagArrs || []).forEach(data=>{//遍历查询tab
                                                if(item == data.id){
                                                    arr.push(data);
                                                    this.tabSettingArrSize ++;//tab计数
                                                }
                                            });
                                        });
                                        this.tagArrs = arr;
                                    }
                                }
                                this.tagArrs.forEach((item,index) => {
                                    this.$set(this.refreshTab,index + '',true);
                                })
                            });
                        });
                    }
                });
            },



            /**
             * 获取资源池对象
             */
            getResources(){
                return new Promise(resolve => {
                    this.RES_GLOBAL.getById(this.resourceId,this.userType).then(res =>{
                        resolve(res);
                    });
                });

            },


            /**
             * 点击选项卡panel时自动刷新选项卡内的数据
             * @param tab
             */
            tabClick(tab) {
                this.setClickTab.add(tab.name);
                this.activeTabId = (this.tagArrs[tab.name] || {}).id || '';
                if(this.autoRefresh){
                    this.refreshTab[tab.name] = false;
                    this.$nextTick(() => {
                        this.refreshTab[tab.name] = true;
                        if(!this.refreshTab[tab.name]){
                            this.$nextTick(() => {
                                this.refreshTab[tab.name] = true;
                            })
                        }
                    });
                }
            },


            /**
             * 判断obj对象是否为空
             * @param obj
             * @returns {boolean}
             */
            isEmptyObject(obj) {
                for (let key in obj){
                    if (obj.hasOwnProperty(key)) {
                        return false;//返回false，不为空对象
                    }
                }
                return true;//返回true，为空对象
            },


            /**
             * ajax 同步请求
             * @param url
             * @param params
             * @returns {Promise<any> | Promise}
             */
            ayncMethodUrl(url,params){
                let data = '';
                Object.keys(params || {}).forEach(key => {
                    data += "&" + key + "=" + params[key];
                });
                if(data){
                    data = data.substring(1);
                }
                const xmlhttp = new XMLHttpRequest();

                let result = null;
                xmlhttp.open("POST", url, false);
                xmlhttp.setRequestHeader("Authorization",localStorage["Authorization" + (window.projectSuffix || "")]||"");
                xmlhttp.setRequestHeader('Content-Type',
                    'application/x-www-form-urlencoded');
                xmlhttp.onreadystatechange = function () {
                    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                        // 同步请求成功
                        result = xmlhttp.responseText;
                    }
                };
                xmlhttp.send(data);

                return result;

            },

        }
    }
</script>

<style scoped>
    .complex-tabs /deep/ .el-tabs__content {
        height: calc(100% - 70px);
    }

    .p-tab-view /deep/  .el-container:first-child {
        height: 100%;
        /*max-height: 800px;*/
    }
    .p-tab-view /deep/  .el-table{
        /*min-height: 500px;*/
    }

    .complex-tabs /deep/ .el-tab-pane {
        height: 100%;
    }

    .complex-tab-pane {
        height: 100%;
    }

</style>
