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

    /**
     * 部件对象
     *
     * @type {*}
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    @ViewChild('${ctrl.getCodeName()}${srfclassname('${ctrl.getControlType()}')}', {static: false}) public ${ctrl.name}: any;

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

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

    /**
     * Api地址
     *
     * @type {string}
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    public url: string = '<#ibizinclude>../@MACRO/CONTROL/URL.ts.ftl</#ibizinclude>';

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

    /**
     * 详情模型集合
     *
     * @type {*}
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    public 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>
    };

    /**
     * 属性值规则
     *
     * @type {*}
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    public rules: any = {
        <#list ctrl.getAllPSDEFormDetails() as formdetail>
        <#if formdetail.getDetailType?? && formdetail.getDetailType() == 'FORMITEM'>
        ${formdetail.getName()}: {
            required: <#if formdetail.isAllowEmpty()>false<#else>true</#if>,
            message: '${formdetail.getCaption()} 值不能为空'
        },
        </#if>
        </#list>
    }

    /**
     * 获取表单模型
     *
     * @returns {*}
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    public getFormDetailModel(): any {
        return this.detailsModel;
    }

    /**
     * 重置表单项值
     *
     * @param {{ name: string, newVal: any, oldVal: any }} { name, newVal, oldVal }
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    public 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 {{ name: string, newVal: any, oldVal: any }} { name, newVal, oldVal }
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    public 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>
    }

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

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

    <#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}')}
	 */
    public ${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}')}
	 */
    public ${formdetail.getName()}_click($event: any): void {
        <#assign itemUpdate=formdetail.getPSDEFormItemUpdate()/>
        <#if formdetail.getParamPickupPSAppView()??>
        <#assign pickupview = formdetail.getParamPickupPSAppView()>
        const view: any = {
            viewname: '${srffilepath2(pickupview.getCodeName())}',
            title: '${pickupview.getTitle()}',
            height: ${pickupview.getHeight()?c},
            width: ${pickupview.getWidth()?c},
            <#if formdetail.getParamViewParamJO()??>
            paramjo: ${formdetail.getParamViewParamJO()},
            </#if>
        }
        const data: any = {
            srfparentdata: {
                srfparentkey: this.data.srfkey,
            }
        };
        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.$Notice.error({ title: '错误', desc: `操作失败,未能找到当前表单项${r'${key}'}，无法继续操作` });
                        return false;
                    }
                    value = this.data[key];
                }
                Object.assign(data.srfparentdata, { [name]: value });
                return true;
            });
        }
        this.$appmodal.openModal(view, data).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}')}
     */
    public 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>
    }

    /**
     * 生命周期（销毁）
     *
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    public ngOnDestroy(): void {
        if (this.dataChangEvent) {
            this.dataChangEvent.unsubscribe();
        }
    }

    /**
     * 加载
     *
     * @param {*} [opt={}]
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    public load(opt: any = {}): void {
        const arg: any = { ...opt };

        this.getAction(arg).then((response: any) => {
            const data = response.data;
            this.onFormLoad(data);
            this.loadEvent.emit(data);
            this.formState.next({ type: 'load', data: data });
        }).catch((response: any) => {
            const { data: _data } = response;
            this.$notice.error(_data.title, _data.message);
        });
    }

    /**
     * 加载草稿
     *
     * @param {*} [opt={}]
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    public loadDraft(opt: any = {}): void {
        const arg: any = { ...opt } ;

        this.getAction(arg).then((response: any) => {
            const data = response.data;
            this.resetDraftFormStates();
            this.onFormLoad(data);
            this.loadEvent.emit(data);
            this.formState.next({ type: 'load', data: data });
            setTimeout(() => {
                const form: any = this.${ctrl.name};
                if (form) {
                    form.fields.forEach((field: any) => {
                        field.validateMessage = "";
                        field.validateState = "";
                        field.validateStatus = false;
                    });
                }
            });
        }).catch((response: any) => {
            const { data: _data } = response;
            this.$notice.error(_data.title, _data.message);
        });
    }

    /**
     * 自动保存
     *
     * @param {*} [opt={}]
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    public autoSave(opt: any = {}): void {
        const arg: any = { ...opt };
        const data = this.getValues();
        Object.assign(arg, data);

        this.updateAction(arg).then((response: any) => {
            const data = response.data;
            this.onFormLoad(data);
            this.saveEvent.emit(data);
            this.formState.next({ type: 'save', data: data });
        }).catch((response: any) => {
            const { data: _data } = response;
            this.$notice.error(_data.title, _data.message);
        });
    }

    /**
     * 保存
     *
     * @param {*} [opt={}]
     * @param {boolean} [showResultInfo]
     * @returns {Promise<any>}
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    public async save(opt: any = {}, showResultInfo?: boolean): Promise<any> {
        showResultInfo = showResultInfo === undefined ? true : false;
        const arg: any = { ...opt };
        const data = this.getValues();
        Object.assign(arg, data);

        return new Promise((resolve: any, reject: any) => {
            this.updateAction(arg).then((response: any) => {
                const data = response.data;
                this.onFormLoad(data);
                this.saveEvent.emit(data);
                this.formState.next({ type: 'save', data: data });
                <#if ctrl.getFormFuncMode()?lower_case != 'wizardform'>
                if (showResultInfo) {
                    this.$notice.success('', (data.srfmajortext ? data.srfmajortext : '') + '&nbsp;保存成功！');
                }
                </#if>

                resolve(response);
            }).catch((response: any) => {
                const { data: _data } = response;
                this.$notice.error(_data.title, _data.message);
                reject(response);
            });
        })
    }
<#if ctrl.getControlType() == 'FORM'>

    /**
     * 工作流提交
     *
     * @param {*} [data={}]
     * @returns {Promise<any>}
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    public async wfstart(data: any = {}): Promise<any> {
        this.$notice.warning('', '暂不支持');
    }

</#if>

    /**
     * 表单项更新
     *
     * @param {string} mode 界面行为名称
     * @param {*} [data={}] 请求数据
     * @param {string[]} updateDetails 更新项
     * @param {boolean} [showloading] 是否显示加载状态
     * @returns {void}
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    public updateFormItems(mode: string, data: any = {}, updateDetails: string[], showloading?: boolean): void {
        this.$notice.warning('', '暂不支持');
    }

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

    /**
     * 生命周期
     *
     * @memberof SearchForm
     */
    ngOnInit(): void {
        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);
                }
            });
        }
    }

<#ibizinclude>
../@MACRO/CONTROL/CONTROL_BOTTOM.ts.ftl
</#ibizinclude>