<template>
    <div style="height: 100%;width: 100%;padding-top: 1px" v-if="loadSuccess" :class='formResourceViewMainClass'>
        <list-resource-view v-if="applyListView == 'list'"
                            :form-id="listObj.formId"
                            :list-view-id="listObj.listViewId"
                            :condition-id="listObj.conditionId"
                            :operate-authority="listObj.operateAuthority"
                            :rparam="listObj.rparam"
                            :equilibriumData="listObj.equilibriumData"
                            :form-out-param="listObj.formOutParam"
                            :sourceId="useSourceId"
        >
        </list-resource-view>

        <flow-resource-view v-else-if="applyListView == 'flow'" :single-flow-obj="flowObj" :sourceId="useSourceId"
                            :flow-next-operation="flowNextOperation" :formImpMethod="formImpMethod" :flowImpParamObj="flowImpParamObj">
        </flow-resource-view>

        <table-resource-view v-else-if="applyListView == 'table'" :table-obj="tableObj" :sourceId="useSourceId">
        </table-resource-view>
    </div>
</template>

<script>
    import axios from "axios/index";
    export default {
        name: "form-resource-view",
        components: {
            ListResourceView: () => import("./listResourceView"),
            TableResourceView: () => import("./tableResourceView"),
            flowResourceView: () => import("./flowResourceView")
        },
        props:{
            resourceId:{type:String}, // 资源Id
            sourceKey:{type:String}, // 共享的数据源ID，可以通过此数据源ID设置为实际使用的数据源ID
            loginUser:{type:Object,default:null}, // 登录用户
            loginDept:{type:Object,default:null}, // 登录用户组织部门信息
            dataPermissions:{type:String}, // 数据权限
            operations:{type:String}, // 操作权限
            formOutParam:{type:Object}, // 操作权限
            flowNextOperation:{type: Function,default:null} // 流程下一步时的参数回调事件
        },
        watch:{
            $route(){
                this.init();
            }
        },
        data(){
            return {
                formResourceId:this.$route.params.resourceId,
                formDataPermissions:this.$route.query.dataPermissions,
                formOperations:this.$route.query.operations,
                queryUserId:this.$route.query.userId,
                queryUserName:this.$route.query.userName,
                queryTenantId:this.$route.query.tenantId,
                queryDataId:this.$route.query.dataId,
                useResourceId:"",
                useSourceId:"",
                useLoginUser:null,
                applyListView:'list', // 是列表、流程还是表单
                listObj:{
                    formId:"",
                    conditionId:"",
                    operateAuthority:{},
                    listViewId:"",
                    rparam:"",
                    equilibriumData:{},
                    formOutParam:{}
                },
                flowObj:{},
                treeObj:{},
                tableObj:{
                    formOperate:"view",
                    tableViewId:"",
                    dataId:"",
                    formId:"",
                    operateAuthority:{},
                    formOutParam:{},
                },
                loadSuccess: false,
                formResourceViewMainClass: "",
                importModelId: "",
                flowImpParamObj: {
                    impUrl: this.api.plCommonmethod.importData,
                },
            }
        },
        created() {
            this.init();
            this.loadSkin();
        },
        methods:{
            formImpMethod(uploadFileObj) {
                let vm = this;
                if (!this.importModelId) {
                    this.$message("导入失败！模板未定义！");
                    return;
                }
                let formData = new FormData();
                formData.append("file", uploadFileObj.file);
                formData.append("modelId", this.importModelId);
                formData.append("sourceKey", this.flowImpParamObj.sourceKey);
                formData.append("user", JSON.stringify(this.CACHE_GLOBAL.getLoginUser()));
                //创建axios实例
                const axiosInstance = axios.create({
                    baseURL: vm.api.plCommonmethod.importData,
                    headers: {'Content-Type': 'multipart/form-data'},
                    transformRequest: [
                        function (data) {
                            return data;
                        }
                    ],
                });
                return new Promise((resolve, reject) => {
                    //上传文件
                    axiosInstance.post(vm.api.plCommonmethod.importData, formData).then((res) => {
                        resolve(res);
                    });
                });
            },
            loadSkin() {
               this.FORM_GLOBAL.getFormCss('1','PRIORITY ASC,UPDATE_TIME ASC',"0").then(result=>{
                   if(result.length>0){
                       (result || []).forEach(item => {
                           if (item.cssType === '0'){
                               if (!item.fileName) {
                                   return;
                               }
                               if (item.wholeClass) {
                                   this.formResourceViewMainClass += "page-render-class " + item.wholeClass;
                               }else {
                                   this.formResourceViewMainClass += "page-render-class";
                               }
                               let style = document.createElement('link');
                               style.type = "text/css";
                               style.href = window.FORM_RENDER_URL + "/uploadFile/customCss/" + item.id + "/" + item.fileName;
                               style.setAttribute("cus-css", "cusCss");
                               style.setAttribute("rel", "stylesheet");
                               document.head.appendChild(style);
                           }
                       })
                   }
               })
                    // console.log('预览表单res',res);
                    //cssType 0：自定义皮肤，1：系统皮肤
                    //applyType 0：表单渲染，1：管理系统

            },
            initRouterParams(){
                this.formResourceId = this.$route.params.resourceId;
                this.formDataPermissions = this.$route.query.dataPermissions;
                this.formOperations = this.$route.query.operations;
                this.queryUserId = this.$route.query.userId;
                this.queryUserName = this.$route.query.userName;
                this.queryTenantId = this.$route.query.tenantId;
                this.queryDataId = this.$route.query.dataId;
            },
            init(){
                this.loadSuccess = false;
                this.initRouterParams();
                // 先处理变量，这里可能是组件传递也可能是Url传递
                let useComp = true;
                if(this.resourceId){ // 使用组件
                    this.useResourceId = this.resourceId;
                    if(this.loginUser){
                        this.CACHE_GLOBAL.setLoginUser(this.loginUser);
                        if(this.loginUser.tenantId){
                            this.useSourceId = this.loginUser.tenantId;
                        }
                    }
                    if(this.sourceKey){
                        this.useSourceId = this.sourceKey;
                    }
                    if(this.loginDept){
                        this.CACHE_GLOBAL.setLoginDept(this.loginDept);
                    }

                }else{ // 使用url
                    useComp = false;
                    this.useResourceId = this.formResourceId;
                    let loginUser = {};
                    loginUser.id = this.queryUserId;
                    loginUser.userName = this.queryUserName;
                    loginUser.tenantId = this.queryTenantId;
                    if(this.queryTenantId){
                        this.useSourceId = this.queryTenantId;
                    }
                    this.CACHE_GLOBAL.setLoginUser(loginUser);
                }

                if(!this.useResourceId){
                    this.$message.error("资源id不能为空！");
                    return;
                }

                this.initData(); // 重新初始化数据
                this.FORM_RES_GLOBAL.getById(this.useResourceId).then(resource => {
                    if(!resource){
                        this.$message.error("资源id不正确,请检查！");
                        return;
                    }
                    resource = resource || {};
                    let formOutParam = {};
                    if(useComp){
                        formOutParam = this.formOutParam || {};
                    }else{
                        formOutParam = this.$route.query || {};
                    }
                    this.listObj["formOutParam"] = formOutParam;
                    this.tableObj["formOutParam"] = formOutParam;
                    this.FORM_GLOBAL.getPageInfo(resource.linkView,'create_time desc').then(res => {
                        let pageInfo = res[0] || {};
                        if(resource.registerType == '2'){
                            if(pageInfo.useFlow != '1'){
                                this.applyListView = '';
                                this.$message.error("页面已修改为非流程类型，当前流程资源已失效！");
                                return;
                            }
                            this.applyListView = 'flow';
                            this.analyseFlowData(resource,pageInfo);
                            this.getListTopButton();
                        }else if(resource.registerType == '0'){
                            this.applyListView = 'table';
                            this.analyseTableData(resource,pageInfo);
                            this.initParam('table',useComp); //在analyseListData方法执行后执行，确定是否要使用外部权限
                        }else if(pageInfo.pageType === 'list'){
                            this.applyListView = 'list';
                            this.analyseListData(resource,pageInfo);
                            this.initParam('list',useComp); //在analyseListData方法执行后执行，确定是否要使用外部权限
                        }else{
                            this.applyListView = 'table';
                            this.analyseTableData(resource,pageInfo);
                            this.initParam('table',useComp); //在analyseListData方法执行后执行，确定是否要使用外部权限
                        }
                    })
                })
            },
            /**
             * 初始化外部传入参数
             */
            initParam(type,useComp){
                if(useComp){
                    if(this.operations){
                        this.listObj.operateAuthority = Object.assign({},this.treeObj);
                        this.tableObj.operateAuthority = {};
                        this.operations.split(",").forEach(item => {
                            if(item){
                                this.listObj.operateAuthority[item] = true;
                                this.tableObj.operateAuthority[item] = true;
                            }
                        })
                    }
                    if(this.dataPermissions){
                        this.listObj["conditionId"] = this.dataPermissions;
                        this.tableObj["conditionId"] = this.dataPermissions;
                    }
                }else{
                    if(this.formOperations){
                        this.listObj.operateAuthority = Object.assign({},this.treeObj);
                        this.tableObj.operateAuthority = {};
                        this.formOperations.split(",").forEach(item => {
                            if(item){
                                this.listObj.operateAuthority[item] = true;
                                this.tableObj.operateAuthority[item] = true;
                            }
                        })
                    }
                    if(this.formDataPermissions){
                        this.listObj["conditionId"] = this.formDataPermissions;
                        this.tableObj["conditionId"] = this.formDataPermissions;
                    }
                }
            },
            analyseListData(resource,pageInfo){
                this.listObj["formId"] = resource.formId;
                this.listObj["listViewId"] = pageInfo.listViewId;
                this.listObj["conditionId"] = resource.dataPermission;
                (resource.operations || "").split(",").forEach(item => {
                    if(item){
                        this.listObj.operateAuthority[item] = true;
                    }
                })
                if(resource.linkTree){
                    this.listObj.operateAuthority[resource.linkTree + "_tree"] = true;
                    this.treeObj = {};
                    this.treeObj[resource.linkTree + "_tree"] = true;
                }

                this.loadSuccess = true;
            },

            analyseFlowData(resource,pageInfo){
                this.flowObj["formId"] = resource.formId;
                this.flowObj["flowId"] = pageInfo.flowId;
                this.flowObj["tableViewId"] = pageInfo.tableViewId;
                if (pageInfo.pageType === 'list') {
                    this.flowObj["listViewId"] = pageInfo.listViewId;
                    this.getSourceKey(resource.formId);
                }
                this.flowObj.operateArr = (resource.operations || "").split(",");
                this.flowObj.dataPermis = resource.dataPermission || "";
                this.loadSuccess = true;
            },
            analyseTableData(resource,pageInfo){
                this.tableObj["formId"] = resource.formId;
                this.tableObj["tableViewId"] = pageInfo.tableViewId;
                let condition = resource.dataPermission;
                this.showTableView(condition);
            },

            /**
             * 执行查询
             */
            showTableView(condition){
                if(!condition){
                    this.tableObj.dataId = "";
                    this.tableObj.formOperate = 'add';
                    if(this.formOperations === "none"){
                        this.tableObj.formOperate='none';
                    }
                    this.loadSuccess = true;
                    return;
                }
                this.spcpFormAxios.post(this.api.plCommonmethod.findByconditions,{tableViewId:this.tableObj.tableViewId
                    ,conditionId:condition,equilibriumData: JSON.stringify(this.tableObj.formOutParam),currentPage:0,rows:0}).then(tableRes =>{
                    if(tableRes && tableRes.data && tableRes.data.operateObj){
                        if((tableRes.data.operateObj || []).length > 0){
                            this.spcpFormAxios.post(this.api.plFormBase.getById,{id:this.tableObj.formId}).then(formBaseRes => {
                                let defineKey = formBaseRes.data.defineKey;
                                let dataObj =  tableRes.data.operateObj[0];
                                this.tableObj.dataId = dataObj["ID_"+defineKey] + ""; //赋值id
                                this.tableObj.formOperate = 'view';
                                if(this.formOperations=="none"){
                                  this.tableObj.formOperate='none';
                                }
                                if(this.queryDataId){
                                  this.tableObj.dataId = this.queryDataId;
                                }
                            })
                        }else{
                            this.tableObj.dataId = "";
                            this.tableObj.formOperate = 'add';
                        }
                        if(this.formOperations=="none"){
                          this.tableObj.formOperate='none';
                        }
                        this.loadSuccess = true;
                    }
                });
            },

            /**
             * 初始化数据
             */
            initData() {
                this.listObj = {
                    formId: "",
                    conditionId: "",
                    operateAuthority: {},
                    listViewId: "",
                    rparam: "",
                    equilibriumData: {},
                    formOutParam: {}
                };
                this.tableObj = {
                    formOperate: "",
                    tableViewId: "",
                    dataId: "",
                    formId: "",
                    formOutParam: {}
                };
            },
            getListTopButton() {
                this.spcpFormAxios.post(this.api.plListViewsButton.findButton,{
                    formId: this.flowObj.formId,
                    listViewId: this.flowObj.listViewId,
                    openMode: 'top'
                }).then(res => {
                    if (res && res.data.operateSuccess) {
                        let downloadModelObj = res.data.operateObj.find(item => item.buttonType === "downloadModel") || {};
                        // console.log('getListTopButton', res, downloadModelObj);
                        if (JSON.stringify(downloadModelObj) !== "{}") {
                            this.importModelId = downloadModelObj.param;
                            this.flowImpParamObj['downloadModel'] = true;
                            this.flowImpParamObj['downloadModelObj'] = downloadModelObj;
                        }
                    }
                });
            },
            getSourceKey(formId = '') {
                this.spcpFormAxios.post(this.api.plFormBase.getById,{
                    id: formId,
                }).then(res => {
                    if (res) {
                        this.flowImpParamObj['sourceKey'] = res.data.sourceKey;
                    }
                });
            },
        }
    }
</script>

<style scoped>

</style>
