<!--自定义单表表单-->
<template>
    <el-container style="height: 100%;width: 100%;position: relative">
        <el-button type="primary" size="mini" v-if="formOperate == 'view'" 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"
                           is-sign-form
                           v-if="isShow"
                           :tableview-id="tableViewId"
                           :data-id="dataId"
                           :form-operate="formOperate"
                           :form-id="formId">
        </table-form-render>
    </el-container>
</template>

<script>

    import TableFormRender from "../popup/formRender/tableFormRender";
    export default {
        name: "singleFormResRouter",
        components: {TableFormRender},
        props:{
            loginUser:{type:Object,default:null}, // 登录用户
            loginDept:{type:Object,default:null}, // 登录用户组织部门信息
        },
        data(){
            return {
                resourceId:this.$route.params.resourceId,
                menuId:"",
                operatePermis:"",
                dataPermis:"",
                dataId:"",
                formOperate:"add", //操作方式
                tableViewId:"", //表单视图id
                formId:'', //表单视图id
                cacheLoginUser:{}, //当前登录用户
                nameObj:{'add':"保存","view":"修改","update":"保存"},
                resourceObj:{} ,//资源池信息
                formType:'', //表单类型 singForm
                menuObj:{},
                operateAuthority:{}, //操作权限
                isShow:false,
                optUpdateShow:false,//是否有更新权限
            }
        },
        watch:{
            '$route.params.resourceId' (to, from) {
                this.getResources();
            }
        },

       async created(){
           if(this.loginUser){
               this.CACHE_GLOBAL.setLoginUser(this.loginUser);
           }
           if(this.loginDept){
               this.CACHE_GLOBAL.setLoginDept(this.loginDept);
           }
            this.getResources();
        },

        async mounted(){

        },
        methods:{
           async executShow(){ //展示
                let vm = this;
                // 获取资源池信息
                //资源池id
                vm.isShow = false;
                this.cacheLoginUser = this.CACHE_GLOBAL.getLoginUser(); //获取当前用户
                let resourceObj = this.resourceObj;
                if(resourceObj){ //
                    let tViewDefineKey = resourceObj.rkey || ''; //列表 definkeKey
                    let formDefineKey = resourceObj.rclassId || ''; //列表deifineKey
                    //根据 formDefineKey 查询 最新的的
                    this.operateAuthority = {};
                    let conditionArr = [];
                    let optArr = [];
                    this.axios.post(vm.api.plTableviews.findNewVersion,{formDefineKey:formDefineKey,defineKey:tViewDefineKey}).then(res =>{
                        if(res && res.data){
                            this.tableViewId = res.data.id || ''; //表单视图的 id
                            this.formId = res.data.formId || ''; // formId
                            //操作权限
                            if(resourceObj.dataPermisList){
                                resourceObj.dataPermisList .forEach(dataPermis=>{
                                    conditionArr.push(dataPermis.powerKey)
                                })
                            }
                            if(resourceObj.operatePermisList){
                                resourceObj.operatePermisList.forEach(optPermis=>{
                                    optArr.push(optPermis.powerKey)
                                })
                            }
                            vm.showTableView(conditionArr);
                            vm.showOptView(optArr);
                        }
                    });

                   //  let res =  await this.axios.post(this.api.plTableviews.findNewVersion,{formDefineKey:formDefineKey,defineKey:tViewDefineKey});
                   //  if(res && res.data && res.data.operateObj){
                   //      this.tableViewId = res.data.operateObj.id || ''; //表单视图的 id
                   //      this.formId = res.data.operateObj.formId || ''; // formId
                   //  }
                   // //查询当前 dataId
                   // let linkTableSql = "WHERE 1=1 AND CREATED = " +"'"+ vm.loginUser.id + "'"; //单表默认查询条件为 创建者 = 当前登录用户id
                   // let tableRes = await this.axios.post(this.api.plCommonmethod.findByFormId,{formId:this.formId,linkTableSql:linkTableSql,order:"UPDATE_TIME DESC",currentPage:0,rows:0});
                   // if(tableRes && tableRes.data && tableRes.data.operateObj){
                   //     if((tableRes.data.operateObj || []).length > 0){
                   //         let dataObj =  tableRes.data.operateObj[0];
                   //         vm.dataId = dataObj["ID"] + ""; //赋值id
                   //         vm.formOperate = 'view';
                   //
                   //     }else{
                   //         vm.dataId = "";
                   //         vm.formOperate = 'add';
                   //     }
                   //     await vm.loadData();
                   //     vm.isShow = true;
                   // }

                }
            },

            /**
             * 执行查询
             */
            showTableView(conditionArr){
                this.axios.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;
                }
            },

            /**
             * 获取资源池对象 (自定义表单表单对象)
             */
            getResources(){
                return new Promise(resolve => {
                    this.RES_GLOBAL.getById(this.resourceId).then(resData => {
                        this.resourceObj = resData; //当前资源池
                        this.executShow();
                    });
                })
                // let res = await this.axios.post(this.api.resources.findResources,{'id': this.resourceId});
                // if(res.data && res.data.operateObj){
                // }
            },


            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 = this.$refs.singleRef.optFormData || {};
                let optType = "add";
                if(contentForm.ID){
                    optType = "update";
                }
                let formDataRef = this.$refs.singleRef;
                formDataRef.$refs.tableFormRef.validate(validate => {
                    if (!validate) {
                        return;
                    }
                    let saveMessage = "保存成功！";
                    if(!this.cacheLoginUser){
                        this.cacheLoginUser = {};
                    }
                    formDataRef.saveData(this.cacheLoginUser.id||"",saveMessage,'','').then(async res=> {
                        if(res){
                            await this.executShow(); //重新
                            this.formOperate = 'view';
                        }
                    });
                });

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

<style scoped>
    .one-button,.two-button{
        position: absolute;top: 25px;right: 20px;z-index: 100;
    }
    .two-button{
        right: 80px;
    }
</style>
