<#ibizinclude>
./CONTROL-BASE.template.ftl
</#ibizinclude>

<#assign import_block>
import { FormButtonModel, FormPageModel, FormItemModel, FormDRUIPartModel, FormPartModel, FormGroupPanelModel, FormIFrameModel, FormRowItemModel, FormTabPageModel, FormTabPanelModel, FormUserControlModel } from '@/model/form-detail';
import { debounceTime, distinctUntilChanged } from 'rxjs/operators';
</#assign>
<#ibizinclude>
../@MACRO/CONTROL/CONTROL_HEADER-BASE.vue.ftl
</#ibizinclude>

    /**
     * 工作流审批意见控件绑定值
     *
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    @Prop() srfwfmemo?: string;

    /**
     * 获取多项数据
     *
     * @returns {any[]}
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    public getDatas(): any[] {
        return [this.data];
    }

    /**
     * 获取单项树
     *
     * @returns {*}
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    public getData(): any {
        return this.data;
    }

    /**
     * 是否默认保存
     *
     * @type {boolean}
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    @Prop({ default: false }) protected autosave?: boolean;

    /**
     * 显示处理提示
     *
     * @type {boolean}
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    @Prop({ default: true }) protected showBusyIndicator!: boolean;

    /**
     * 部件行为--submit
     *
     * @type {string}
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    @Prop() protected WFSubmitAction!: string;
    
    /**
     * 部件行为--start
     *
     * @type {string}
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    @Prop() protected WFStartAction!: string;
    
    /**
     * 部件行为--update
     *
     * @type {string}
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    @Prop() protected updateAction!: string;
    
    /**
     * 部件行为--remove
     *
     * @type {string}
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    @Prop() protected removeAction!: string;
    
    /**
     * 部件行为--loaddraft
     *
     * @type {string}
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    @Prop() protected loaddraftAction!: string;
    
    /**
     * 部件行为--load
     *
     * @type {string}
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    @Prop() protected loadAction!: string;
    
    /**
     * 部件行为--create
     *
     * @type {string}
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    @Prop() protected createAction!: string;

    /**
     * 部件行为--create
     *
     * @type {string}
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    @Prop() protected searchAction!: string;

    /**
     * 视图标识
     *
     * @type {string}
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    @Prop() protected viewtag!: string;

    /**
     * 表单状态
     *
     * @type {Subject<any>}
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    protected formState: Subject<any> = new Subject();

    /**
     * 忽略表单项值变化
     *
     * @type {boolean}
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    protected ignorefieldvaluechange: boolean = false;

    /**
     * 数据变化
     *
     * @private
     * @type {Subject<any>}
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    private dataChang: Subject<any> = new Subject();

    /**
     * 视图状态事件
     *
     * @private
     * @type {(Subscription | undefined)}
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    private dataChangEvent: Subscription | undefined;

    /**
     * 原始数据
     *
     * @private
     * @type {*}
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    private oldData: any = {};

    /**
     * 表单数据对象
     *
     * @type {*}
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    protected data: any = {
        <#list ctrl.getPSDEFormItems() as item>
        ${item.getName()}: null,
        </#list>
        <#if appde??>${appde.getCodeName()?lower_case}: null,</#if>
    };

    /**
      * 当前执行的行为逻辑
      *
      * @type {string}
      * @memberof ${srfclassname('${ctrl.codeName}')}
      */
    protected currentAction: string = "";

    /**
      * 关系界面计数器
      *
      * @type {number}
      * @memberof ${srfclassname('${ctrl.codeName}')}
      */
    protected drcounter: number = 0;

    /**
      * 表单保存回调存储对象
      *
      * @type {any}
      * @memberof ${srfclassname('${ctrl.codeName}')}
      */
    protected saveState:any ;

    /**
     * 属性值规则
     *
     * @type {*}
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    protected rules: any = {
        <#list ctrl.getAllPSDEFormDetails() as formdetail>
        <#if formdetail.getDetailType?? && formdetail.getDetailType() == 'FORMITEM'>
        ${formdetail.getName()}: [
            { type: '<#assign datatype=srfjavatype(formdetail.getStdDataType())><#if datatype=='BigInteger' || datatype=='Integer' || datatype=='Double' || datatype=='Decimal' || datatype=='Float' || datatype=='BigDecimal'>number<#else>string</#if>', message: '${formdetail.getCaption()} 值必须为<#if datatype=='BigInteger' || datatype=='Integer' || datatype=='Double' || datatype=='Decimal' || datatype=='Float' || datatype=='BigDecimal'>数值<#else>字符串</#if>类型', trigger: 'change' },
            { type: '<#assign datatype=srfjavatype(formdetail.getStdDataType())><#if datatype=='BigInteger' || datatype=='Integer' || datatype=='Double' || datatype=='Decimal' || datatype=='Float' || datatype=='BigDecimal'>number<#else>string</#if>', message: '${formdetail.getCaption()} 值必须为<#if datatype=='BigInteger' || datatype=='Integer' || datatype=='Double' || datatype=='Decimal' || datatype=='Float' || datatype=='BigDecimal'>数值<#else>字符串</#if>类型', trigger: 'blur' },
            { required: <#if formdetail.isAllowEmpty()>false<#else>true</#if>, type: '<#assign datatype=srfjavatype(formdetail.getStdDataType())><#if datatype=='BigInteger' || datatype=='Integer' || datatype=='Double' || datatype=='Decimal' || datatype=='Float' || datatype=='BigDecimal'>number<#else>string</#if>', message: '${formdetail.getCaption()} 值不能为空', trigger: 'change' },
            { required: <#if formdetail.isAllowEmpty()>false<#else>true</#if>, type: '<#assign datatype=srfjavatype(formdetail.getStdDataType())><#if datatype=='BigInteger' || datatype=='Integer' || datatype=='Double' || datatype=='Decimal' || datatype=='Float' || datatype=='BigDecimal'>number<#else>string</#if>', message: '${formdetail.getCaption()} 值不能为空', trigger: 'blur' },
             <#if formdetail.getEditorType?? && formdetail.getEditorType()?? &&  formdetail.isAllowEmpty?? && formdetail.isAllowEmpty()??>
            <#if  formdetail.getEditorType() == 'CHECKBOX' &&  !formdetail.isAllowEmpty()>
            { validator: (rule:any, value:any, callback:any) => { 
                if(rule.required && value != 1){
                   return false;
                }else{
                   return true;
                }
              }, message: '${formdetail.getCaption()} 必须填写', trigger: 'change' ,required:true}
            </#if>
            </#if>
          <#if ctrl.getPSDEFormItemVRs()??>
            <#list ctrl.getPSDEFormItemVRs() as fideValueRule>
            <#if fideValueRule.getPSDEFormItemName() == formdetail.getName()>
              <#if fideValueRule.getPSSysValueRule()??>
                <#assign  valueRule = fideValueRule.getPSSysValueRule()/>
                <#if valueRule.getRuleType?? && valueRule.getRuleType()??>
                  <#if valueRule.getRuleType() == "REG">
            { <#if valueRule.getRegExCode?? && valueRule.getRegExCode()??>pattern: /${valueRule.getRegExCode()}/</#if><#if valueRule.getRuleInfo?? &&  valueRule.getRuleInfo()??>, message: '${valueRule.getRuleInfo()}'</#if>, trigger: 'change' },
                  <#elseif valueRule.getRuleType() == "SCRIPT">
            { <#if valueRule.getScriptCode?? && valueRule.getScriptCode()??>validator: (rule:any, value:any, callback:any) => { ${valueRule.getScriptCode()} }</#if><#if valueRule.getRuleInfo?? &&  valueRule.getRuleInfo()??>, message: '${valueRule.getRuleInfo()}'</#if>, trigger: 'change' },
                  </#if>
                </#if>
              </#if>
            </#if>            
            </#list>
          </#if>
        ],
        </#if>
        </#list>
    }

    /**
     * 详情模型集合
     *
     * @type {*}
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    protected detailsModel: any = {
        <#list ctrl.getAllPSDEFormDetails() as formdetail>
        ${formdetail.name}: ${P.getPartCode(formdetail, 'DETAIL_MODEL').code}, 
        </#list>
        <#if !ctrl.isNoTabHeader()>
        ${ctrl.name}: new FormTabPanelModel({ caption: '${ctrl.name}', detailType: 'TABPANEL', name: '${ctrl.name}', visible: true, isShowCaption: true, form: this, tabPages: [<#list ctrl.getPSDEFormPages() as formmenber><#if formmenber_index gt 0>, </#if>{ name: '${formmenber.name}', index: ${formmenber_index}, visible: <#if formmenber.getPSDEFDGroupLogic('PANELVISIBLE')??>false<#else>true</#if> }</#list>] }),
        </#if>
    };

    <#list ctrl.getPSDEFormItems() as item>
    /**
     * 监控表单属性 ${item.getName()} 值
     *
     * @param {*} newVal
     * @param {*} oldVal
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    @Watch('data.${item.getName()}')
    on${srfclassname('${item.getName()}')}Change(newVal: any, oldVal: any) {
        this.formDataChange({ name: '${item.getName()}', newVal: newVal, oldVal: oldVal });
        <#if item.getEditorType?? && item.getEditorType()?? &&  item.isAllowEmpty?? && item.isAllowEmpty()??>
        <#if  item.getEditorType() == 'CHECKBOX' &&  !item.isAllowEmpty()>
        if(newVal !== null){
            this.formDataChange({ name: '${item.getName()}', newVal: newVal, oldVal: oldVal });
        }else{
            this.data.${item.getName()} = oldVal;
        }
        </#if>
        </#if>
    }

    </#list>

    /**
     * 重置表单项值
     *
     * @private
     * @param {{ name: string, newVal: any, oldVal: any }} { name, newVal, oldVal }
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    private resetFormData({ name, newVal, oldVal }: { name: string, newVal: any, oldVal: any }): void {
        <#list ctrl.getPSDEFormItems() as item>
        <#if item.getResetItemName?? && item.getResetItemName()??>
        if (Object.is(name, '${item.getResetItemName()}')) {
            this.onFormItemValueChange({ name: '${item.getName()}', value: null });
            <#if item.getValueItemName()?? && item.getValueItemName() != ''>
            this.onFormItemValueChange({ name: '${item.getValueItemName()}', value: null });
            </#if>
        }
        </#if>
        </#list>
    }

    /**
      * 置空对象
      *
      * @param {any[]} args
      * @memberof EditForm
      */
    protected ResetData(_datas:any){
        if(Object.keys(_datas).length >0){
            Object.keys(_datas).forEach((name: string) => {
                if (this.data.hasOwnProperty(name)) {
                    this.data[name] = null;
                }
            });
        }
    }

    /**
     * 表单逻辑
     *
     * @private
     * @param {{ name: string, newVal: any, oldVal: any }} { name, newVal, oldVal }
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    private formLogic({ name, newVal, oldVal }: { name: string, newVal: any, oldVal: any }): void {
        <#if P.getPartCode(item,'FORM_LOGIC').code?length gt 0>
        ${P.getPartCode(item,'FORM_LOGIC').code}
        </#if>
        <#if ctrl.getPSDEFormItems()??>
        <#list ctrl.getPSDEFormItems() as formitem>
        <#if formitem.getPSDEFormItemUpdate()??>
        <#assign itemUpdate=formitem.getPSDEFormItemUpdate()/>

        if (Object.is(name, '${formitem.name}')) {
            const details: string[] = [<#list itemUpdate.getPSDEFIUpdateDetails() as detail><#if detail_index gt 0>, </#if>'${detail.getPSDEFormDetailName()?lower_case}'</#list>];
            this.updateFormItems('${itemUpdate.codeName}', this.data, details, ${itemUpdate.isShowBusyIndicator()?c});
        }
        </#if>
        </#list>
        </#if>
    }

    /**
     * 表单值变化
     *
     * @private
     * @param {{ name: string, newVal: any, oldVal: any }} { name, newVal, oldVal }
     * @returns {void}
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    private formDataChange({ name, newVal, oldVal }: { name: string, newVal: any, oldVal: any }): void {
        if (this.ignorefieldvaluechange) {
            return;
        }
        this.resetFormData({ name: name, newVal: newVal, oldVal: oldVal });
        this.formLogic({ name: name, newVal: newVal, oldVal: oldVal });
        this.dataChang.next(JSON.stringify(this.data));
    }

    /**
     * 表单加载完成
     *
     * @private
     * @param {*} [data={}]
     * @param {string} [action]
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    private onFormLoad(data: any = {},action:string): void {
        this.setFormEnableCond(data);
        this.fillForm(data,action);
        <#if ctrl.getControlType() == 'FORM'>
        this.oldData = {};
        Object.assign(this.oldData, JSON.parse(JSON.stringify(this.data)));
        this.$store.commit('viewaction/setViewDataChange', { viewtag: this.viewtag, viewdatachange: false });
        </#if>
        this.formLogic({ name: '', newVal: null, oldVal: null });
    }

    /**
     * 值填充
     *
     * @param {*} [_datas={}]
     * @param {string} [action]
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    protected fillForm(_datas: any = {},action:string): void {
        this.ignorefieldvaluechange = true;
        Object.keys(_datas).forEach((name: string) => {
            if (this.data.hasOwnProperty(name)) {
                this.data[name] = _datas[name];
            }
        });
        if(Object.is(action,'loadDraft')){
            this.createDefault();
        }
        this.$nextTick(function () {
            this.ignorefieldvaluechange = false;
        })
    }

    /**
     * 设置表单项是否启用
     *
     * @protected
     * @param {*} data
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    protected setFormEnableCond(data: any): void {
        Object.values(this.detailsModel).forEach((detail: any) => {
            if (!Object.is(detail.detailType, 'FORMITEM')) {
                return;
            }
            const formItem: FormItemModel = detail;
            formItem.setEnableCond(data.srfuf);
        });
    }

    /**
     * 重置草稿表单状态
     *
     * @private
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    private resetDraftFormStates(): void {
        const form: any = this.$refs.${ctrl.name};
        if (form) {
            // form.resetValidation();
        }
    }

    /**
     * 重置校验结果
     *
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    protected resetValidates(): void {
        Object.values(this.detailsModel).forEach((detail: any) => {
            if (!Object.is(detail.detailType, 'FORMITEM')) {
                return;
            }
            const formItem: FormItemModel = detail;
            formItem.setError('');
        });
    }

    /**
     * 填充校验结果 (后台)
     *
     * @param {any[]} fieldErrors
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    protected fillValidates(fieldErrors: any[]): void {
        fieldErrors.forEach((error: any) => {
            const formItem: FormItemModel = this.detailsModel[error.field];
            if (!formItem) {
                return;
            }
            this.$nextTick(() => {
                formItem.setError(error.message);
            });
        });
    }

    /**
     * 表单校验状态
     *
     * @returns {boolean} 
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    protected formValidateStatus(): boolean {
        const refArr: Array<string> = [<#list ctrl.getPSDEFormItems() as formItem><#if formItem.getEditorType?? && formItem.getEditorType() != 'HIDDEN'>'${formItem.getName()}_item', </#if></#list>];
        let falg = true;
        refArr.forEach((item: any) => {
            if (this.$refs[item] && (this.$refs[item] as any).validateRules && !(this.$refs[item] as any).validateRules()) {
                falg = false;
            }
        });
        return falg;
    }

    /**
     * 获取全部值
     *
     * @returns {*}
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    protected getValues(): any {
        return this.data;
    }

    /**
     * 表单项值变更
     *
     * @param {{ name: string, value: any }} $event
     * @returns {void}
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    protected onFormItemValueChange($event: { name: string, value: any }): void {
        if (!$event) {
            return;
        }
        if (!$event.name || Object.is($event.name, '') || !this.data.hasOwnProperty($event.name)) {
            return;
        }
        this.data[$event.name] = $event.value;
    }

    /**
     * 设置数据项值
     *
     * @param {string} name
     * @param {*} value
     * @returns {void}
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    protected setDataItemValue(name: string, value: any): void {
        if (!name || Object.is(name, '') || !this.data.hasOwnProperty(name)) {
            return;
        }
        if (Object.is(this.data[name], value)) {
            return;
        }
        this.data[name] = value;
    }

    <#list ctrl.getAllPSDEFormDetails() as formdetail>
    <#if formdetail.getDetailType?? && formdetail.getDetailType() == 'BUTTON'>
    <#if formdetail.getActionType?? && formdetail.getActionType()??>
    <#if formdetail.getActionType() == 'UIACTION'>

	/**
	 * 表单 ${formdetail.getCaption()} 事件
	 *
	 * @memberof @memberof ${srfclassname('${ctrl.codeName}')}
	 */
    protected ${formdetail.getName()}_click($event: any): void {
        <#if formdetail.getPSUIAction?? && formdetail.getPSUIAction()??>
        <#assign uiaction = formdetail.getPSUIAction()>
        this.${ctrl.name}_${formdetail.getName()}_click(null, null, $event);
        </#if>

    }
    </#if>
    <#if formdetail.getActionType() == 'FIUPDATE'>

	/**
	 * 表单 ${formdetail.getCaption()} 事件
	 *
	 * @memberof @memberof ${srfclassname('${ctrl.codeName}')}
	 */
    protected ${formdetail.getName()}_click($event: any): void {
    <#assign itemUpdate=formdetail.getPSDEFormItemUpdate()/>
    <#if formdetail.getParamPickupPSAppView()??>
        <#assign dataview = formdetail.getParamPickupPSAppView()>
        <#--  BEGIN:是否应用实体视图  -->
        <#if dataview.isPSDEView()>
        const deResParameters: any[] = [
            <#--  BEGIN:存在父关系路径  -->
            <#if dataview.getPSAppDERSPathCount() gt 0>
            <#list dataview.getPSAppDERSPath(dataview.getPSAppDERSPathCount() - 1) as deRSPath>
            <#assign majorPSAppDataEntity = deRSPath.getMajorPSAppDataEntity()/>
            { pathName: '${srfpluralize(majorPSAppDataEntity.codeName)?lower_case}', parameterName: '${majorPSAppDataEntity.getCodeName()?lower_case}' },
            </#list>
            </#if>
            <#--  END:存在父关系路径  -->
        ];
        <#else>
        const deResParameters: any[] = [];
        </#if>
        <#--  END:是否应用实体视图  -->
        <#--  BEGIN:是否应用实体视图  -->
        <#if dataview.isPSDEView()>
        <#assign appDataEntity = dataview.getPSAppDataEntity()/>
        const parameters: any[] = [
            { pathName: '${srfpluralize(appDataEntity.codeName)?lower_case}', parameterName: '${appDataEntity.getCodeName()?lower_case}' },
        ];
        <#else>
        const parameters: any[] = [];
        </#if>
        <#--  END:是否应用实体视图  -->
        const view: any = {
            viewname: '${srffilepath2(dataview.getCodeName())}',
            title: '${dataview.getTitle()}',
            height: ${dataview.getHeight()?c},
            width: ${dataview.getWidth()?c},
            <#if formdetail.getParamViewParamJO()??>
            paramjo: ${formdetail.getParamViewParamJO()},
            </#if>
        }
        const data: any = {};
        if(view.paramjo) {
            Object.keys(view.paramjo).every((name: string) => {
                if (!name) {
                    return true;
                }
                let value: string = view.paramjo[name];
                if (value && value.startsWith('%') && value.endsWith('%')) {
                    const key: string = value.substring(1, value.length - 1);
                    if (!this.data.hasOwnProperty(key)) {
                        this.$notify({ type: 'danger', message: '操作失败,未能找到当前表单项${r'${key}'},无法继续操作' });
                        return false;
                    }
                    value = this.data[key];
                }
                Object.assign(data, { [name]: value });
                return true;
            });
        }
        let container: Subject<any> = this.$appmodal.openModal(view, this.context,data);
        container.subscribe((result: any) => {
            if (result && Object.is(result.ret, 'OK') && result.datas && Array.isArray(result.datas)) {
                const arg: any = { ...JSON.parse(JSON.stringify(this.data)) } ;
                Object.assign(arg, { srfactionparam: result.datas });
                const details: string[] = [<#list itemUpdate.getPSDEFIUpdateDetails() as detail><#if detail_index gt 0>, </#if>'${detail.getPSDEFormDetailName()?lower_case}'</#list>];
                this.updateFormItems('${itemUpdate.codeName}', arg, details, ${itemUpdate.isShowBusyIndicator()?c});
            }
        });
    <#else>
        const details: string[] = [<#list itemUpdate.getPSDEFIUpdateDetails() as detail><#if detail_index gt 0>, </#if>'${detail.getPSDEFormDetailName()?lower_case}'</#list>];
        this.updateFormItems('${itemUpdate.codeName}', this.data, details, ${itemUpdate.isShowBusyIndicator()?c});
    </#if>
    }
    </#if>
    </#if>
    </#if>
    </#list>


    /**
     * 分组界面行为事件
     *
     * @param {*} $event
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    protected groupUIActionClick($event: any): void {
        if (!$event) {
            return;
        }
        const item:any = $event.item;
        <#list ctrl.getAllPSDEFormDetails() as formdetail>
        <#if formdetail.getDetailType?? && formdetail.getDetailType() == 'GROUPPANEL'>
        <#if formdetail.getPSUIActionGroup()??>
        <#list formdetail.getPSUIActionGroup().getPSUIActionGroupDetails() as uadetails>
        if (Object.is(item.name, '${formdetail.getName()}_${uadetails.getName()}')) {
            this.${ctrl.name}_${formdetail.getName()}_${uadetails.getName()}_click(null, null, $event.event);
        }
        </#list>
        </#if>
        </#if>
        </#list>
    }

    /**
     * Vue声明周期(处理组件的输入属性)
     *
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    protected created(): void {
        this.afterCreated();
    }

    /**
     * 执行created后的逻辑
     *
     *  @memberof ${srfclassname('${ctrl.codeName}')}
     */    
    protected afterCreated(){
        if (this.viewState) {
            this.viewStateEvent = this.viewState.subscribe(({ tag, action, data }) => {
                if (!Object.is(tag, this.name)) {
                    return;
                }
                if (Object.is('autoload', action)) {
                    this.autoLoad(data);
                }
                if (Object.is('load', action)) {
                    this.load(data);
                }
                if (Object.is('loaddraft', action)) {
                    this.loadDraft(data);
                }
                if (Object.is('save', action)) {
                    this.save(data,data.showResultInfo);
                }
                if (Object.is('remove', action)) {
                    this.remove(data);
                }
                if (Object.is('saveandexit', action)) {
                    this.saveAndExit(data);
                }
                if (Object.is('saveandnew', action)) {
                    this.saveAndNew(data);
                }
                if (Object.is('removeandexit', action)) {
                    this.removeAndExit(data);
                }
                if (Object.is('refresh', action)) {
                    this.refresh(data);
                }
            });
        }
        this.dataChang
            .pipe(
                debounceTime(300),
                distinctUntilChanged()
            ).subscribe((data: any) => {
                if (this.autosave) {
                    this.autoSave();
                }
                <#if ctrl.getControlType() == 'FORM'>
                const state = !Object.is(JSON.stringify(this.oldData), JSON.stringify(this.data)) ? true : false;
                this.$store.commit('viewaction/setViewDataChange', { viewtag: this.viewtag, viewdatachange: state });
                </#if>
                <#if ctrl.getControlType() == 'SEARCHFORM' && ctrl.isEnableAutoSearch()>
                this.$emit('load', this.data);
                </#if>
            });
    }

    /**
     * vue 生命周期
     *
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    protected destroyed() {
        this.afterDestroy();
    }

    /**
     * 执行destroyed后的逻辑
     *
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    protected afterDestroy() {
        if (this.viewStateEvent) {
            this.viewStateEvent.unsubscribe();
        }
        if (this.dataChangEvent) {
            this.dataChangEvent.unsubscribe();
        }
        <#if destroyed_block??>
        ${destroyed_block}
        </#if>      
    }

    /**
     * 拷贝内容
     *
     * @param {*} [arg={}]
     * @memberof @memberof ${srfclassname('${ctrl.codeName}')}
     */
    protected copy(arg: any = {}): void {
        this.loadDraft(arg);
    }

    /**
     * 部件刷新
     *
     * @param {any[]} args
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    protected refresh(args: any[]): void {
        let arg: any = {};
        Object.assign(arg,args[0]);
        if (this.data.srfkey && !Object.is(this.data.srfkey, '')) {
            Object.assign(arg, { srfkey: this.data.srfkey });
            this.load(arg);
            return;
        }
        if (this.data.srfkeys && !Object.is(this.data.srfkeys, '')) {
            Object.assign(arg, { srfkey: this.data.srfkeys });
            this.load(arg);
            return;
        }
    }


    /**
     * 自动加载
     *
     * @param {*} [arg={}]
     * @returns {void}
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    protected autoLoad(arg: any = {}): void {
        if (arg.srfkey && !Object.is(arg.srfkey, '')) {
            Object.assign(arg, { srfkey: arg.srfkey });
            this.load(arg);
            return;
        }
        if (arg.srfkeys && !Object.is(arg.srfkeys, '')) {
            Object.assign(arg, { srfkey: arg.srfkeys });
            this.load(arg);
            return;
        }
        this.loadDraft(arg);
    }

    /**
     * 加载
     *
     * @private
     * @param {*} [opt={}]
     * @returns {Promise<any>}
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    private async load(opt: any = {}): Promise<any> {
        if (!this.loadAction) {
            this.$notice.error(this.viewName+this.$t('app.view')+this.$t('app.ctrl.form')+'loadAction'+ this.$t('app.notConfig'));
            return Promise.reject();
        }
        const arg: any = { ...opt };
        Object.assign(arg, this.viewparams);
        const response: any = await this.service.get(this.loadAction, { ...this.context }, arg, this.showBusyIndicator);
        if (response && response.status === 200) {
            const data = response.data;
            this.onFormLoad(data, 'load');
            this.$emit('load', data);
            this.$nextTick(() => {
                this.formState.next({ type: 'load', data: data });
            });
        } else if (response && response.status !== 401) {
            const { error: _data } = response;
            this.$notice.error(_data.message);
        }
        return response;
    }

    /**
     * 加载草稿
     *
     * @param {*} [opt={}]
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    protected async loadDraft(opt: any = {}): Promise<any> {
        if (!this.loaddraftAction) {
            this.$notice.error(this.viewName+this.$t('app.view')+this.$t('app.ctrl.form')+'loaddraftAction'+ this.$t('app.notConfig'));
            return Promise.reject();
        }
        const arg: any = { ...opt } ;
        Object.assign(arg, this.viewparams);
        const response: any = await this.service.loadDraft(this.loaddraftAction, { ...this.context }, arg, this.showBusyIndicator);
        if (response && response.status === 200) {
            const data = response.data;
            <#if appde??>
            if(data.${appde.getCodeName()?lower_case}){
                Object.assign(this.context, { ${appde.getCodeName()?lower_case}: data.${appde.getCodeName()?lower_case} });
            }
            </#if>
            this.resetDraftFormStates();
            this.onFormLoad(data, 'loadDraft');
            this.$emit('load', data);
            this.$nextTick(() => {
                this.formState.next({ type: 'load', data: data });
            });
        } else if (response && response.status !== 401) {
            const { error: _data } = response;
            this.$notice.error(_data.message);
        }
        return response;
    }

    /**
     * 自动保存
     *
     * @protected
     * @param {*} [opt={}]
     * @returns {Promise<any>}
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    protected async autoSave(opt: any = {}): Promise<any> {
        if (!this.formValidateStatus()) {
            return Promise.reject();
        }
        const arg: any = { ...opt };
        const data = this.getValues();
        Object.assign(arg, data);
        const action: any = Object.is(data.srfuf, '1') ? this.updateAction : this.createAction;
        if (!action) {
            let actionName: any = Object.is(data.srfuf, '1') ? "updateAction" : "createAction";
            this.$notice.error(this.viewName+this.$t('app.view')+this.$t('app.ctrl.form')+actionName+ this.$t('app.notConfig'));
            return Promise.reject();
        }
        Object.assign(arg, this.viewparams);
        const response: any = await this.service.add(action, { ...this.context }, arg, this.showBusyIndicator);
        if (response.status && response.status === 200) {
            const data = response.data;
            this.onFormLoad(data,'autoSave');
            this.$emit('save', data);
            <#if ctrl.getControlType() == 'FORM'>
            this.$store.dispatch('viewaction/datasaved', { viewtag: this.viewtag });
            </#if>
            this.$nextTick(() => {
                this.formState.next({ type: 'save', data: data });
            });
        } else if (response.status && response.status !== 401) {
            const { error: _data } = response;
            if (Object.is(_data.status, 'BAD_REQUEST') && _data.parameters && _data.parameters.fieldErrors) {
                this.resetValidates();
                this.fillValidates(_data.parameters.fieldErrors)
            }
            this.$notice.error(_data.message);
        }
        return response;
    }

    /**
     * 保存
     *
     * @protected
     * @param {*} [opt={}]
     * @param {boolean} [showResultInfo]
     * @param {boolean} [isStateNext=true] 是否下发通知
     * @returns {Promise<any>}
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    protected async save(opt: any = {}, showResultInfo?: boolean, isStateNext: boolean = true): Promise<any> {
        showResultInfo = showResultInfo === undefined ? true : false;
        opt.saveEmit = opt.saveEmit === undefined ? true : false;
        if (!this.formValidateStatus()) {
            this.$notice.error('值规则校验异常');
            return Promise.reject();
        }
        const arg: any = { ...opt };
        const data = this.getValues();
        Object.assign(arg, data);
        if (isStateNext) {
            <#assign drcounter = 0>
            <#list ctrl.getAllPSDEFormDetails() as formdetail>
            <#if formdetail.getDetailType() == "DRUIPART">
                <#assign drcounter = drcounter + 1>
            </#if>
            </#list>
            this.drcounter = ${drcounter};
            if (this.drcounter !== 0) {
                this.formState.next({ type: 'beforesave', data: arg });//先通知关系界面保存
                this.saveState = Promise.resolve();
                return Promise.reject();
            }
        }
        const action: any = Object.is(data.srfuf, '1') ? this.updateAction : this.createAction;
        if (!action) {
            let actionName: any = Object.is(data.srfuf, '1') ? "updateAction" : "createAction";
            this.$notice.error(this.viewName+this.$t('app.view')+this.$t('app.ctrl.form')+actionName+ this.$t('app.notConfig'));
            return Promise.reject();
        }
        Object.assign(arg, this.viewparams);
        let response: any = null;
        if (Object.is(data.srfuf, '1')) {
            response = await this.service.update(action, { ...this.context }, arg, this.showBusyIndicator);
        } else {
            response = await this.service.add(action, { ...this.context }, arg, this.showBusyIndicator);
        }
        if (response && response.status === 200) {
            const data = response.data;
            this.onFormLoad(data, 'save');
            if(!opt.saveEmit){
                this.$emit('save', data);
            }                
            <#if ctrl.getControlType() == 'FORM'>
            this.$store.dispatch('viewaction/datasaved', { viewtag: this.viewtag });
            </#if>
            this.$nextTick(() => {
                this.formState.next({ type: 'save', data: data });
            });
            <#if ctrl.getFormFuncMode()?lower_case != 'wizardform'>
            if (showResultInfo) {
                this.$notice.success((data.srfmajortext ? data.srfmajortext : '') + '&nbsp;'+ this.$t('app.message.savedSuccess'));
            }
            </#if>
        } else if (response && response.status !== 401) {
            const { error: _data } = response;
            if (Object.is(_data.status, 'BAD_REQUEST') && _data.parameters && _data.parameters.fieldErrors) {
                this.resetValidates();
                this.fillValidates(_data.parameters.fieldErrors)
            }
            this.$notice.error(_data.message);
        }
        return response;
    }

    /**
     * 删除
     *
     * @private
     * @param {Array<any>} [opt=[]]
     * @param {boolean} [showResultInfo]
     * @returns {Promise<any>}
     * @memberof ${srfclassname('${ctrl.name}')}
     */
    private async remove(opt: Array<any> = [], showResultInfo?: boolean): Promise<any> {
        if (!this.removeAction) {
            this.$notice.error(this.viewName+this.$t('app.view')+this.$t('app.ctrl.form')+'removeAction'+ this.$t('app.notConfig'));
            return Promise.reject();
        }
        const arg: any = opt[0];
        const _this: any = this;
        Object.assign(arg, this.viewparams);
        const response: any = await this.service.delete(_this.removeAction, { ...this.context }, arg, showResultInfo);
        if (response && response.status === 200) {
            const data = response.data;
            this.$emit('remove', data);
            this.formState.next({ type: 'remove', data: data });
            this.data.ismodify = false;
            this.$notice.success((data.srfmajortext ? data.srfmajortext : '') + '&nbsp;'+ this.$t('app.message.deleteSccess'));
        } else if (response && response.status !== 401) {
            const { error: _data } = response;
            this.$notice.error(_data.message);
        }
        return response;
    }
<#if ctrl.getControlType() == 'FORM'>

    /**
     * 工作流启动
     *
     * @protected
     * @param {*} data
     * @returns {Promise<any>}
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    protected async wfstart(data: any): Promise<any> {
        const _this: any = this;
        const arg: any = { ...data };
        Object.assign(arg, this.viewparams);
        let response: any = await this.service.wfstart(_this.WFStartAction, { ...this.context }, arg, this.showBusyIndicator);
        if (response && response.status === 200) {
            this.$notice.success('工作流启动成功');
        } else if (response && response.status !== 401) {
            this.$notice.error('工作流启动失败, ' + response.error.message);
        }
        return response;
    }

    /**
     * 工作流提交
     *
     * @protected
     * @param {*} data
     * @param {*} linkItem
     * @param {*} datas
     * @returns {Promise<any>}
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    protected async wfsubmit(data: any, linkItem: any, datas: any): Promise<any> {
        const arg: any = { ...data };
        Object.assign(arg, this.viewparams, linkItem);
        // 强制补充srfwfmemo
        if (this.srfwfmemo) {
            Object.assign(datas, { srfwfmemo: this.srfwfmemo });
        }
        const response: any = await this.service.wfsubmit(this.currentAction, { ...this.context }, datas, this.showBusyIndicator, arg);
        if (response && response.status === 200) {
            this.$notice.success('工作流提交成功');
        } else if (response && response.status !== 401) {
            this.$notice.error('工作流提交失败, ' + response.error.message);
            return response;
        }
    }
</#if>

    /**
     * 表单项更新
     *
     * @protected
     * @param {string} mode 界面行为名称
     * @param {*} [data={}] 请求数据
     * @param {string[]} updateDetails 更新项
     * @param {boolean} [showloading] 是否显示加载状态
     * @returns {Promise<any>}
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    protected async updateFormItems(mode: string, data: any = {}, updateDetails: string[], showloading?: boolean): Promise<any> {
        if (!mode || (mode && Object.is(mode, ''))) {
            return Promise.reject();
        }
        const arg: any = { ...data };
        Object.assign(arg, this.viewparams);
        const response: any = await this.service.frontLogic(mode, { ...this.context }, arg, showloading);
        if (response && response.status === 200) {
            const data = response.data;
            const _data: any = {};
            updateDetails.forEach((name: string) => {
                if (!data.hasOwnProperty(name)) {
                    return;
                }
                Object.assign(_data, { [name]: data[name] });
            });
            this.setFormEnableCond(_data);
            this.fillForm(_data, 'updateFormItem');
            this.formLogic({ name: '', newVal: null, oldVal: null });
            this.dataChang.next(JSON.stringify(this.data));
            this.$nextTick(() => {
                this.formState.next({ type: 'updateformitem', ufimode: arg.srfufimode, data: _data });
            });
        } else if (response && response.status !== 401) {
            const { error: _data } = response;
            if (Object.is(_data.status, 'BAD_REQUEST') && _data.parameters && _data.parameters.fieldErrors) {
                this.resetValidates();
                this.fillValidates(_data.parameters.fieldErrors)
            }
            this.$notice.error(_data.message);
        }
        return response;
    }

    /**
     * 回车事件
     *
     * @param {*} $event
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    protected onEnter($event: any): void {
        <#if ctrl.getControlType() == 'SEARCHFORM' && !ctrl.isEnableAutoSearch()>
        this.$emit('load', this.data);
        </#if>
    }

    /**
     * 保存并退出
     *
     * @protected
     * @param {any[]} data
     * @returns {Promise<any>}
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    protected async saveAndExit(data: any[]): Promise<any> {
        const arg: any = { ...data[0] };
        this.currentAction = 'saveAndExit';
        const response: any = await this.save([arg]);
        if (response && response.status === 200) {
            this.closeView([{ ...response.data }]);
        }
        return response;
    }

    /**
     * 保存并新建
     *
     * @protected
     * @param {any[]} data
     * @returns {Promise<any>}
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    protected async saveAndNew(data: any[]): Promise<any> {
        let arg: any = { ...data[0] };
        this.currentAction = 'saveAndNew';
        const response: any = await this.save([arg]);
        if (response && response.status === 200) {
            this.ResetData(response.data);
            this.loadDraft({});
        }
        return response;
    }

    /**
     * 删除并退出
     *
     * @protected
     * @param {any[]} data
     * @returns {Promise<any>}
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    protected async removeAndExit(data: any[]): Promise<any> {
        let arg: any = { ...data[0] };
        const response: any = await this.remove([arg]);
        if (response && response.status === 200) {
            this.closeView([{ ...response.data }]);
        }
        return response;
    }

    /**
    * 关系界面数据保存完成
    *
    * @param {any} $event
    * @memberof ${srfclassname('${ctrl.codeName}')}
    */
    protected drdatasaved($event:any){
        let _this = this;
        this.drcounter--;
        if(this.drcounter > 0){
            return;
        }
        this.save({}, undefined, false).then((res) =>{
            //this.saveState(res);
            if(Object.is(_this.currentAction, "saveAndNew")){
                _this.ResetData(res);
                _this.loadDraft({});
            }else if(Object.is(_this.currentAction, "saveAndExit")){
                if(res){
                    _this.closeView(res.data);
                }
            }
        });
    }

    /**
     * 新建默认值
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    public createDefault(){                    
        <#list ctrl.getAllPSDEFormDetails() as formdetail><#t>
        <#if formdetail.getCreateDV?? && formdetail.getCreateDV()??><#t>
        <#if !(formdetail.getCreateDV() == '')><#t>
        if (this.data.hasOwnProperty('${formdetail.getCodeName()?lower_case}')) {
        <#-- 网页请求 -->
        <#if formdetail.getCreateDVT() == 'CONTEXT'>
            this.data['${formdetail.getCodeName()?lower_case}'] = this.viewparams['${formdetail.getCreateDV()}'];
        <#else>
        <#-- 默认值 -->
            this.data['${formdetail.getCodeName()?lower_case}'] = '${formdetail.getCreateDV()}';
        </#if>
        }
        </#if>
        </#if>
        </#list>
    }

<#--  搜索表单:Begin  -->
<#if ctrl.getControlType() == 'SEARCHFORM'>
    <#if ctrl.getSearchButtonStyle() == 'DEFAULT'>

    /**
     * 搜索
     *
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    protected onSearch() {
        this.$emit('load', this.data);
    }

    /**
     * 重置
     *
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    protected onReset() {
        this.loadDraft();
    }
    </#if>
    <#if ctrl.getSearchButtonStyle() == 'SEARCHONLY'>

    /**
     * 搜索
     *
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    protected onSearch() {
        this.$emit('load', this.data);
    }



    </#if>
</#if>
    
<#ibizinclude>
../@MACRO/CONTROL/CONTROL_BOTTOM-BASE.vue.ftl
</#ibizinclude>

<#ibizinclude>
../@MACRO/CONTROL/CONTROL-BASE.style.ftl
</#ibizinclude>