<!--自定义单表表单-->
<template>
    <el-container  class="single-form">
        <el-button type="primary" size="mini" v-if="formOperate == 'view' && optUpdateShow" class="one-button" @click="execEvent">
            {{nameObj[formOperate]}}
        </el-button>
        <el-button type="primary" size="mini" v-if="formOperate != 'view'" class="two-button" @click="execEvent">
            {{nameObj[formOperate]}}
        </el-button>
        <el-button type="primary" v-if="formOperate != 'view'" size="mini" class="one-button" @click="cancel">
            取消
        </el-button>

        <table-form-render ref="singleRef" style="height: auto;overflow-y: auto;"
                           v-if="isShow"
                           :tableview-id="tableViewId"
                           :data-id="dataId"
                           is-edit-data
                           is-sign-form
                           :form-operate="formOperate"
                           :form-id="formId">
        </table-form-render>
    </el-container>
</template>

<script>
    export default {
        name: "singleFormMenuRouter",
        components: {
            TableFormRender: () => import("../popup/formRender/tableFormRender")
        },
        props: {
            cresourceId: { //资源id
                type: String,
                default: ''
            },
            cmenuId:{//菜单id
                type: String,
                default: ''
            },
            isCloudView:{
                type: Boolean,
                default: false
            },
            loginUser:{type:Object,default:null}, // 登录用户
            loginDept:{type:Object,default:null}, // 登录用户组织部门信息
        },
        data(){
            return {
                resourceId:this.$route.params.resourceId,
                menuId:this.$route.query.menuId,
                operatePermis:"",
                dataPermis:"",
                dataId:"",
                formOperate:"add", //操作方式
                tableViewId:"", //表单视图id
                formId:'', //表单视图id
                cacheLoginUser:{}, //当前登录用户
                nameObj:{'add':"保存","view":"修改","update":"保存"},
                resourceObj:{} ,//资源池信息
                formType:'', //表单类型 singForm
                menuObj:{},
                isShow:false,
                optUpdateShow:false,
            }
        },
        watch:{
            /*'$route.params.resourceId' (to, from) {
                this.getResources().then(() => { //获取资源池
                    this.executShow();
                });
            }*/
        },
        async created(){
            if(!this.resourceId){
                this.resourceId = this.cresourceId;
            }
            if((!this.menuId) || (this.menuId == "0")){
                this.menuId = this.cmenuId;
            }
            if(this.loginUser){
                this.CACHE_GLOBAL.setLoginUser(this.loginUser);
            }
            if(this.loginDept){
                this.CACHE_GLOBAL.setLoginDept(this.loginDept);
            }
            this.getResources().then(()=>{
                this.executShow();//展示
            });
        },
        async mounted(){

        },
        methods:{
            /**
             * 获取资源池对象 (自定义表单表单对象)
             */
            getResources(){
                return new Promise(resolve => {
                    let vm = this;
                    vm.RES_GLOBAL.getById(vm.resourceId).then(resData => {
                        vm.resourceObj = resData; //当前资源池
                        if(window.menuIdToMenuObj){
                            vm.menuObj = window.menuIdToMenuObj[vm.menuId];
                        }else{
                            //新窗口打开时查询菜单信息
                            vm.spcpFormAxios.post(vm.api.menu.getById,{id:vm.menuId}).then(function (res) {
                                if(res && res.data){
                                    vm.menuObj = res.data;
                                }
                            });
                        }
                        resolve();
                    });
                });

                // let res = await this.spcpFormAxios.post(this.api.resources.findResources,{'id': this.resourceId});
                // if(res.data && res.data.operateObj){
                // }
            },

            async executShow(){ //展示
                let vm = this;
                // 获取资源池信息
                //资源池id
                vm.isShow = false;
                vm.cacheLoginUser = vm.CACHE_GLOBAL.getLoginUser(); //获取当前用户
                let resourceObj = vm.resourceObj;
                let resourceIdsData = [];
                let resourceIdsOpt = [];
                if(vm.menuObj.dataPermis){
                    resourceIdsData = vm.menuObj.dataPermis.split(",")
                }
                if(vm.menuObj.operatePermis){
                    resourceIdsOpt = vm.menuObj.operatePermis.split(",")
                }

                let conditionArr = [];
                let optArr = [];
                if(resourceObj){ //判断表单类型
                    let tViewDefineKey = resourceObj.rkey || ''; //列表 definkeKey
                    let formDefineKey = resourceObj.rclassId || ''; //列表deifineKey
                    //根据 formDefineKey 查询 最新的的
                    let res = await vm.spcpFormAxios.post(vm.api.plTableviews.findNewVersion,{formDefineKey:formDefineKey,defineKey:tViewDefineKey});
                    if(res && res.data) {
                        vm.tableViewId = res.data.id || ''; //表单视图的 definkeKey
                        vm.formId = res.data.formId || ''; //表单id definkeKey
                    }else{
                        this.$message.error("表单资源不存在！");
                        return;
                    }
                }
                //获得菜单权限中选中的条件id
                if(vm.cacheLoginUser.userType == 'sup' || this.isCloudView) { //开发者
                    if(resourceObj.dataPermisList){
                        resourceObj.dataPermisList .forEach(dataPermis=>{
                            resourceIdsData.forEach(resid=>{
                                if(dataPermis.id == resid) {
                                    conditionArr.push(dataPermis.powerKey)
                                }
                            })
                        })
                    }
                    if(resourceObj.operatePermisList){
                        resourceObj.operatePermisList.forEach(optPermis=>{
                            resourceIdsOpt.forEach(resid=>{
                                if(optPermis.id == resid) {
                                    optArr.push(optPermis.powerKey)
                                }
                            })
                        })
                    }
                    //查询当前 dataId
                    // let linkTableSql = "WHERE 1=1 AND CREATED = " +"'"+ vm.loginUser.id + "'"; //单表默认查询条件为 创建者 = 当前登录用户id
                    // let tableRes = await this.spcpFormAxios.post(this.api.plCommonmethod.findByFormId,{formId:this.formId,linkTableSql:linkTableSql,order:"UPDATE_TIME DESC",currentPage:0,rows:0});
                    vm.showTableView(conditionArr);
                    vm.showOptView(optArr);
                }else { //走角色权限
                    vm.RES_GLOBAL.getUserOwnMenuOpt().then(datas =>{
                        if(datas){
                            let dataPowerArr = [];
                            let dataOptArr = [];
                            (datas || []).forEach(item =>{
                                if(this.menuId == item.menuId){
                                    if(item.dataPower){
                                        dataPowerArr.push(item.dataPower);
                                    }
                                    if(item.optPower){
                                        dataOptArr.push(item.optPower);
                                    }
                                }
                            });
                            let dataPowerSet = new Set(dataPowerArr);
                            let dataOptSet = new Set(dataOptArr);
                            dataPowerArr = Array.from(dataPowerSet);
                            dataOptArr = Array.from(dataOptSet);
                            let dataPowerKeyArr = [];
                            let dataOptKeyArr = [];
                            let dataPermisList = ((vm.menuObj || {}).dataPermis || '').split(",");//菜单数据权限
                            let operatePermisList = ((vm.menuObj || {}).operatePermis || '').split(",");//菜单操作权限

                            (resourceObj.dataPermisList || []).forEach(item =>{ //数据权限
                                if((dataPowerArr || []).indexOf(item.id) > -1 && dataPermisList.indexOf(item.id) > -1){
                                    dataPowerKeyArr.push(item.powerKey); //数据权限 arr
                                }
                            });
                            (resourceObj.operatePermisList || []).forEach(item =>{ //操作权限
                                if((dataOptArr || []).indexOf(item.id) > -1 && operatePermisList.indexOf(item.id) > -1){
                                    dataOptKeyArr.push(item.powerKey); //操作权限 arr
                                }
                            });
                            vm.showTableView(dataPowerKeyArr);
                            vm.showOptView(dataOptKeyArr);
                        }
                    });
                }
            },

            /**
             * 执行查询
             */
            showTableView(conditionArr){
                this.spcpFormAxios.post(this.api.plCommonmethod.findByconditions,{tableViewId:this.tableViewId,conditionId:conditionArr.join(","),currentPage:0,rows:0}).then(tableRes =>{
                    if(tableRes && tableRes.data && tableRes.data.operateObj){
                        if((tableRes.data.operateObj || []).length > 0){
                            let dataObj =  tableRes.data.operateObj[0];
                            this.dataId = dataObj["ID_"+this.formId] + ""; //赋值id
                            this.formOperate = 'view';
                        }else{
                            this.dataId = "";
                            this.formOperate = 'add';
                        }
                        this.isShow = true;
                        this.loadData();
                    }
                });
            },

            /**
             * 执行操作权限
             */
            showOptView(dataOptKeyArr){
                if(dataOptKeyArr &&  dataOptKeyArr.indexOf("update")>-1){
                    this.optUpdateShow=true;
                }
            },

            loadData(){
                this.$refs["singleRef"] && this.$refs["singleRef"].loadData();
            },
            /**
             * 修改保存
             */
            execEvent(){
                let vm = this;
                switch (this.formOperate){
                    case "add":
                    case "update":
                        vm.save();
                        break;
                    case "view":
                        vm.update();
                        break;
                    default:
                        break;
                }
            },
            /**
             * 取消
             */
            cancel(){
                this.formOperate = 'view';
                this.loadData();
            },
            save(){
                let vm = this;
                let contentForm = vm.$refs.singleRef.optFormData || {};
                let optType = "add";
                if(contentForm.ID){
                    optType = "update";
                }
                let formDataRef = vm.$refs.singleRef;
                formDataRef.$refs.tableFormRef.validate(validate => {
                    if (!validate) {
                        formDataRef.validateFail();
                        return;
                    }
                    let saveMessage = "保存成功！";
                    if(!vm.cacheLoginUser){
                        vm.cacheLoginUser = {};
                    }
                    formDataRef.saveData(vm.cacheLoginUser.id||"",saveMessage,'','').then(async res=> {
                        if(res){
                            await vm.executShow(); //重新
                            vm.formOperate = 'view';
                        }
                    });
                });
            },

            update(){
                this.formOperate = "update";
                this.$refs["singleRef"] && this.$refs["singleRef"].initData();
            }
        }
    }
</script>

<style scoped lang="scss">
    .single-form{
        height: 100%;
        width: 100%;
        position: relative;
        overflow-y: auto;
    }
    // 滚动条的宽度
    .single-form form::-webkit-scrollbar {
        width: 0;
        height: 0;
    }
    .one-button,.two-button{
        position: absolute;top: 25px;right: 20px;z-index: 100;
    }
    .two-button{
        right: 80px;
    }
</style>
