<template>
    <flow-inst-view :flow-id="flowIds || flowObj.flowId" :loginUser="loginUser"
                    :operateArr="flowObj.operateArr" :dataPermis="flowObj.dataPermis"
                    :initFormInfo="initFormInfo" :saveFormInfo="saveFormInfo" :initMessageFunc="initMessageFunc"
                    :flow-next-operation="flowNextOperation" :getFormInfo="getFormInfo" :formImpMethod="formImpMethod"
                    :flowImpParamObj="flowImpParamObj" :downloadTemplate="downloadTemplate" :getFormDataByDataIds="getFormDataByDataIds"
                    :saveBatchDealFormData="saveBatchDealFormData" :formAboutInfoObj="formAboutInfoObj" :sysDataObj="sysDataObj" v-if="loadSysDataSuccess">
        <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 CacheGlobal from "../../assets/js/global/cacheGlobal";

    export default {
        name: "flow-resource-view",
        props:{
            singleFlowObj:{type:Object},
            flowObjByFlowId:{type:Object},
            sourceId:{type:String},
            flowNextOperation:{type: Function,default:null}, // 流程下一步时的参数回调事件
            initMessageFunc:{type: Function,default:null},
            formImpMethod:{type: Function,default:null},
            flowImpParamObj: {type: Object,default: () => ({})},
            isMultiFlow: {type: Boolean, default: false},
            flowIds: {type: String, default: ""},
        },
        watch: {
            onlyMultiFlowId() {
                if (this.flowIds.includes(",")) {
                    this.changeFlowData();
                }
            },
        },
        data() {
            return {
                loginUser:{},
                dataId:"",
                formOperate:"add",
                flowFieldStatus:{},
                formFieldObj:{},
                fieldDefaultVal:{},
                fieldDefaultValChangeNum:{},
                flowFieldDefaultFromForm:{},
                sysDataObj: {},
                loadSysDataSuccess: false,
                formAboutInfoObj: {},
                onlyMultiFlowId: "",
                flowObj: this.singleFlowObj,
            }
        },
        created() {
            this.init();
            this.getFieldInfo();
            this.getFormConfigInfo();
            this.getSysDataObjGiveFlow();
        },
        methods:{
            changeFlowData() {
                if (this.onlyMultiFlowId) {
                    this.flowObj = this.flowObjByFlowId[this.onlyMultiFlowId];
                }
            },

            init() {
                this.loginUser = this.CACHE_GLOBAL.getLoginUser() || {};
            },

            getFormConfigInfo() {
                return new Promise(resolve => {
                    this.FORM_GLOBAL.getControlConfig(this.flowObj.tableViewId).then((res) => {
                        this.formAboutInfoObj["formControlConfigArr"] = res;
                        resolve();
                    });
                });
            },

            getSysDataObjGiveFlow() {
                return new Promise(resolve => {
                    this.loadSysDataSuccess = true;
                    if(window.spcpDataObj && window.spcpDataObj[this.flowObj.sourceKey]){
                        this.sysDataObj = window.spcpDataObj[this.flowObj.sourceKey];
                        this.loadSysDataSuccess = true;
                        resolve();
                    }else{
                        if(!window.spcpDataObj){
                            window.spcpDataObj = {};
                        }
                        CacheGlobal.getDataToLocalForage(this.flowObj.sourceKey).then(datas => {
                            let sysDataObj = {};
                            datas.forEach(item => {
                                let data = {
                                    id: item.id,
                                    dataName: item.dataName,
                                }
                                sysDataObj[item.id] = data;
                            })
                            this.sysDataObj = sysDataObj;
                            window.spcpDataObj[this.flowObj.sourceKey] = sysDataObj;
                            this.loadSysDataSuccess = true;
                            resolve();
                        })
                    }
                })
            },

            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[key + "_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 && !this.flowIds.includes(",")){
                        resolve();
                        return;
                    }
                    this.FORM_GLOBAL.getFormFields(this.flowObj.formId).then(res => {
                        this.formFieldObj = {};
                        (res || []).forEach(item => {
                            this.formFieldObj[item.id] = item.phyfieldName;
                        });
                        this.formAboutInfoObj["formFieldObj"] = this.formFieldObj;
                        resolve();
                    });
                });
            },

            /**
             * 初始化表单信息
             */
            initFormInfo(type,dataId,fieldOperate,flowInstData){
                flowInstData = flowInstData || {};
                this.onlyMultiFlowId = flowInstData.flowId;
                return new Promise(resolve => {
                    this.formOperate = type;
                    this.dataId = dataId;
                    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.spcpFormAxios.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.spcpFormAxios.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.spcpFormAxios.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.spcpFormAxios.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);
                }
            },

            // 根据dataIds批量获取表单数据
            getFormDataByDataIds(formId, dataIds) {
                return new Promise(resolve => {
                    this.spcpFormAxios.post(this.api.plCommonmethod.getByIds, {
                        formId: formId || this.flowObj.formId || "",
                        dataIds
                    }).then(res => {
                        let obj = {};
                        if (res.data.operateSuccess) {
                            res.data.operateObj.forEach(item => {
                                obj[item.ID] = item;
                            });
                        }
                        resolve(obj);
                    });
                });
            },

            saveBatchDealFormData(formId, params) {
                return new Promise(resolve => {
                    this.spcpFormAxios.post(this.api.plCommonmethod.updateByIdBatchNew, {
                        formId: formId || this.flowObj.formId || "",
                        params
                    }).then(res => {
                        resolve(res.data);
                    });
                });
            },

            // 模版下载
            downloadTemplate() {
                let modelId = this.flowImpParamObj.downloadModelObj.param;
                if (!modelId) {
                    return this.$message.warning("模版Id为空！");
                }
                this.spcpFormAxios.post(this.api.baseUploadUrl + "viewFile", {"fkId": modelId + "_plFormTmpDefine_mbsc"}).then(response => {
                    // console.log('response',response);
                    let arrFile = response.data;
                    if (arrFile.length > 0) {
                        let downloadUrl = this.api.baseUploadUrl + "downloadFile?id=" + arrFile[0].id;
                        let link = document.createElement('a');
                        link.href = downloadUrl;
                        link.download = arrFile[0].fileName;
                        link.style.display = 'none';
                        document.body.appendChild(link);
                        link.click();
                        link.remove();
                    } else {
                        this.$message("下载模板异常！");
                    }
                });
            },
        }
    }
</script>

<style scoped>

</style>
