<template>
    <flow-inst-view :flow-id="flowObj.flowId" :loginUser="loginUser"
                    :operateArr="flowObj.operateArr" :dataPermis="flowObj.dataPermis"
                    :initFormInfo="initFormInfo" :saveFormInfo="saveFormInfo" :initMessageFunc="initMessageFunc"
                    :flow-next-operation="flowNextOperation" :getFormInfo="getFormInfo">
        <template slot="formInfo">
            <table-form-render ref="tableRef"
                               is-sign-form
                               is-edit-data
                               useLoadSelf
                               :tableview-id="flowObj.tableViewId"
                               :data-id="dataId"
                               :sourceId="sourceId"
                               isFlow
                               :flowFieldStatus="flowFieldStatus"
                               :flowFieldDefault="fieldDefaultVal"
                               :flowFieldDefaultChangeNum="fieldDefaultValChangeNum"
                               :flowFieldDefaultFromForm="flowFieldDefaultFromForm"
                               :form-operate="formOperate"
                               :form-id="flowObj.formId">
            </table-form-render>
        </template>
    </flow-inst-view>
</template>

<script>
    import Vue from "vue";
    import {Replace} from "sasp-base";
    import SaspFlowRender from 'sasp-flow-render';
    if(!Vue.prototype.USE_SASP_FLOW){
        Vue.use(SaspFlowRender,{
            // router,
            axios: Vue.prototype.axios,
            SERVICE_URL: window.FLOW_URL,
            ADMIN_URL: window.ADMIN_URL
        })
    }

    export default {
        name: "flow-resource-view",
        props:{
            flowObj:{type:Object},
            sourceId:{type:String},
            flowNextOperation:{type: Function,default:null}, // 流程下一步时的参数回调事件
            initMessageFunc:{type: Function,default:null}
        },
        data(){
            return {
                loginUser:{},
                dataId:"",
                formOperate:"add",
                flowFieldStatus:{},
                formFieldObj:{},
                fieldDefaultVal:{},
                fieldDefaultValChangeNum:{},
                flowFieldDefaultFromForm:{},
            }
        },
        created() {
            this.init();
            this.getFieldInfo();
        },
        methods:{
            init(){
                this.loginUser = this.CACHE_GLOBAL.getLoginUser() || {};
            },

            getFormInfo(){
                let optFormData = {};
                if(this.$refs.tableRef){
                    optFormData = this.$refs.tableRef.optFormData;
                }
                return optFormData;
            },

            /**
             * 保存表单信息
             */
            saveFormInfo(type){
                return new Promise(resolve => {
                    if(type == 'draft'){
                        let validate = this.$refs.tableRef.validateDraft();
                        if(!validate){
                            return;
                        }
                    }
                    this.$refs.tableRef.saveData().then(res => {
                        if(!res){
                            resolve(false);
                            return;
                        }
                        if(!res.formDataObj.flowSaveSuccess){
                            this.$message({
                                type:"warning",
                                message:"保存失败！"
                            });
                            resolve(false);
                            return;
                        }
                        let flowParams = res.formDataObj;
                        let fieldSysDataObj = this.$refs.tableRef.fieldSysDataObj;
                        this.getFieldInfo().then(() => {
                            let obj = {};
                            Object.keys(flowParams).forEach(key => {
                                let paramKey = this.formFieldObj[key] || key;
                                if(fieldSysDataObj[key]){ // 替换元数据
                                    let value = flowParams[key];
                                    obj[paramKey] = flowParams[key] || "";
                                    if(value){
                                        let valueKeyArr = [value];
                                        if(value.indexOf(",") > -1){
                                            valueKeyArr = value.split(",");
                                        }
                                        let valueArr = [];
                                        valueKeyArr.forEach(item => {
                                            valueArr.push(fieldSysDataObj[key][item]);
                                        })
                                        obj[paramKey + "_SASP_SYS_DATA"] = valueArr.join(",");
                                        obj[key + "_SASP_SYS_DATA"] = valueArr.join(",");
                                        obj[paramKey + "_SASP_SYS_DATA_ID"] = valueKeyArr.join(",");
                                        obj[paramKey] = valueArr.join(",");
                                        obj[key] = valueArr.join(",");
                                    }
                                }else{
                                    obj[paramKey] = flowParams[key];
                                    obj[key] = flowParams[key];
                                }
                            })
                            resolve(obj);
                        })
                    })
                })
            },

            /**
             * 获取字段信息
             */
            getFieldInfo(){
                return new Promise(resolve => {
                    if(Object.keys(this.formFieldObj).length > 0){
                        resolve();
                        return;
                    }
                    this.axios.post(this.api.plFormField.find,{formId:this.flowObj.formId}).then(res => {
                        this.formFieldObj = {};
                        (res.data || []).forEach(item => {
                            this.formFieldObj[item.id] = item.phyfieldName;
                        })
                        resolve();
                    })
                })
            },

            /**
             * 初始化表单信息
             */
            initFormInfo(type,dataId,fieldOperate,flowInstData){
                return new Promise(resolve => {
                    this.formOperate = type;
                    this.dataId = dataId;
                    flowInstData = flowInstData || {};
                    this.getFieldDefaultVal(fieldOperate,flowInstData.flowStatus).then(() => {
                        this.$nextTick(() => {
                            this.$refs.tableRef.loadData().then(() => {
                                resolve();
                            })
                        })
                    })
                })
            },

            getFieldDefaultVal(fieldOperate,flowStatus){
                return new Promise(resolve => {
                    this.flowFieldStatus = {};
                    this.fieldDefaultVal = {}; //初始化可编辑状态和默认值
                    let orgChargeField = [];
                    let supervisorField = [];
                    // let levels = "";
                    Object.keys(fieldOperate).forEach(field => {
                        let fieldObj = fieldOperate[field];
                        if(flowStatus!='4'){
                            if (fieldObj.edit == "1") {//可编辑
                                this.flowFieldStatus[field] = "edit";
                            } else if (fieldObj.hide == "1") {//不可见
                                this.flowFieldStatus[field] = "hide";
                            }
                        }
                        let defaultValType = fieldObj.defaultValType;
                        let defaultVal = fieldObj.defaultVal;
                        let dateTimeType = fieldObj.dateTimeType;
                        if (defaultVal) {
                            if (defaultValType == "sysData") {
                                this.fieldDefaultVal[field] = defaultVal[defaultVal.length - 1];
                            } else if (defaultValType == "formInfo"){
                                this.fieldDefaultVal[field] = "&&," + defaultVal + ",&&";
                            } else if (defaultValType == "diyVal" || (defaultValType == "dateTime" && dateTimeType == "diyTime")) {
                                this.fieldDefaultVal[field] = defaultVal;
                            } else {
                                if (defaultVal.indexOf("LOGINUSER") > -1) {
                                    this.fieldDefaultVal[field] = Replace.def(this.loginUser, defaultVal);
                                } else {
                                    this.fieldDefaultVal[field] = Replace.def(this.userDept, defaultVal);
                                }
                            }
                        }
                        //时间
                        if(defaultValType == "dateTime" && dateTimeType == "sysTime"){
                            let time = "";
                            let dateTimeFormat = fieldObj.dateTimeFormat || "yyyy-MM-dd";
                            let specialDate = fieldObj.specialDate;
                            let specialOpt = fieldObj.specialOpt;
                            let specialVal = fieldObj.specialVal;
                            if(specialDate && specialOpt && specialVal){
                                time = this.DATE_UTIL.timeConversion(new Date(),dateTimeFormat,specialDate,specialOpt,specialVal);
                            }else{
                                time = this.DATE_UTIL.formaterDateOrTime(new Date(),dateTimeFormat);
                            }
                            this.fieldDefaultVal[field] = time;
                        }

                        if(defaultValType == "dateTime" && dateTimeType == "formField"){
                            this.flowFieldDefaultFromForm[field] = fieldObj;
                        }


                        //处理人上级
                        let dealerLeaderType = fieldObj.dealerLeaderType;
                        if(dealerLeaderType){
                            if(dealerLeaderType == "1"){
                                orgChargeField.push(field);
                            }else{
                                supervisorField.push({field:field,level:fieldObj.leaderLevel})
                                // levels += "," + fieldObj.leaderLevel;
                            }
                        }
                        this.fieldDefaultValChangeNum[field] = fieldObj.changeNum;
                    });
                    this.getDefaultUser(orgChargeField,supervisorField,resolve);
                })
            },

            getDefaultUser(orgChargeField,supervisorField,resolve){
                if(orgChargeField.length > 0 && supervisorField.length > 0){
                    this.axios.post(window.FLOW_URL + "/plFlowInterfaceController/getDeptSupervisor",
                        {loginUserId:this.loginUser.id}).then(res => {
                        if(res && res.data){
                            let userId = (res.data[0] || {}).id;
                            orgChargeField.forEach(fieldId => {
                                this.fieldDefaultVal[fieldId] = userId || "";
                            });
                        }

                        this.axios.post(window.FLOW_URL + "/plFlowInterfaceController/getSupervisor",
                            {loginUserId:this.loginUser.id}).then(res => {
                            if(res && res.data){
                                let userIdMap = res.data || {};
                                supervisorField.forEach(item => {
                                    this.fieldDefaultVal[item.field] = userIdMap[item.level] || "";
                                });
                                resolve(true);
                            }
                        });
                    });
                }else if(orgChargeField.length > 0){
                    this.axios.post(window.FLOW_URL + "/plFlowInterfaceController/getSupervisor",
                        {loginUserId:this.loginUser.id}).then(res => {
                        if (res && res.data) {
                            let userId = (res.data[0] || {}).id;
                            orgChargeField.forEach(fieldId => {
                                this.fieldDefaultVal[fieldId] = userId || "";
                            });
                            resolve(true);
                        }
                    });
                }else if(supervisorField.length > 0){
                    this.axios.post(window.FLOW_URL + "/plFlowInterfaceController/getSupervisor",
                        {loginUserId:this.loginUser.id}).then(res => {
                        if(res && res.data){
                            let userIdMap = res.data || {};
                            supervisorField.forEach(item => {
                                this.fieldDefaultVal[item.field] = userIdMap[item.level] || "";
                            });
                            resolve(true);
                        }
                    });
                }else{
                    resolve(true);
                }
            },
        }
    }
</script>

<style scoped>

</style>
