import { Component } from 'vue-property-decorator';
import { VueLifeCycleProcessing, AppFormBase } from '@ibizstudio-ex/template-vue';
import { IPSAppDEView, IPSDEFormButton, IPSDEFormDRUIPart, IPSDEFormFormPart, IPSDEFormGroupPanel, IPSDEFormIFrame, IPSDEFormItem, IPSDEFormPage, IPSDEFormRawItem, IPSDEFormTabPage, IPSDEFormTabPanel } from '@ibizstudio-ex/runtime';
import './memo-form.less';
import { IPSDEFormDetail } from '@ibizstudio/api';



/**
 * 备忘录表单插件类
 *
 * @export
 * @class MemoForm
 * @extends {Vue}
 */
@Component({})
@VueLifeCycleProcessing()
export class MemoForm extends AppFormBase {
    memo: any;

    collapsed:boolean = false;

    created() {
      const collapsed = localStorage.getItem('mome-form-collapsed');
      if (collapsed) {
        this.collapsed = JSON.parse(collapsed);
      }
    }

    activated(): void {
      const collapsed = localStorage.getItem('mome-form-collapsed');
      if (collapsed) {
        this.collapsed = JSON.parse(collapsed);
      }
    }

    collapsedChange() {
      this.collapsed = !this.collapsed;
      localStorage.setItem('mome-form-collapsed', JSON.stringify(this.collapsed));
    }

    renderMemo() {
        if (!this.memo) {
            return null;
        }
        return <div class={{'form-memo-area':true}}>
            <div class={{'collapse-btn':true}} on-click={()=> this.collapsedChange()}>
                <i class='el-icon-caret-bottom'></i>
            </div>
            {this.memo}
        </div>
    }

    /**
     * @description 自动保存
     * @param {*} [opt={}]
     * @return {*}  {void}
     * @memberof MemoForm
     */
    autoSave(opt: any = {}): void {
      if (!this.formValidateStatus()) {
        return;
      }
      const arg: any = { ...opt };
      const data = this.getData();
      Object.assign(arg, data);
      Object.assign(arg, { srfmajortext: data[this.majorMessageItemName] });
      const action: any = Object.is(data.srfuf, '1') ? this.updateAction : this.createAction;
      if (!action) {
        this.$throw(`${this.controlInstance.codeName}` + (this.$t('app.formpage.notconfig.actionname') as string), 'autoSave');
        return;
      }
      let tempContext: any = JSON.parse(JSON.stringify(this.context));
      if (this.context.srfcallbacktype && this.context.srfcallbackid) {
        Object.assign(arg, { srfcallbacktype: this.context.srfcallbacktype, srfcallbackid: this.context.srfcallbackid });
      }
      const post: Promise<any> = this.service.add(action, tempContext, arg, this.showBusyIndicator);
      post.then((response: any) => {
          if (!response.status || response.status !== 200) {
            this.$throw(response, 'autoSave');
            return;
          }
          const data = response.data;
          this.onFormLoad(data, 'autoSave');
          this.ctrlEvent({
            controlname: this.controlInstance.name,
            action: 'save',
            data: data,
          });
          this.$nextTick(() => {
            this.formState.next({ type: 'save', action: 'autoSave', data: data });
          });
        })
        .catch((response: any) => {
          this.onControlResponse('autoSave', response);
          if (response && response.status && response.data) {
            this.$throw(response, 'autoSave', { dangerouslyUseHTMLString: true });
          } else {
            this.$throw(this.$t('app.commonwords.sysexception') as string, 'autoSave');
          }
        });
    }

    /**
     * 根据detailType绘制对应detail
     *
     * @param {*} modelJson
     * @param {number} index
     * @memberof AppFormBase
     */
    public renderByDetailType(modelJson: IPSDEFormDetail, index: number) {
        if (modelJson.getPSSysPFPlugin()) {
            const pluginInstance: any = this.PluginFactory.getPluginInstance(
                'CONTROLITEM',
                modelJson.getPSSysPFPlugin()?.pluginCode || '',
            );
            if (pluginInstance) {
                return pluginInstance.renderCtrlItem(this.$createElement, modelJson, this, null);
            }
        } else {
            switch (modelJson.detailType) {
                case 'FORMPAGE':
                    return this.renderFormPage(modelJson as IPSDEFormPage, index);
                case 'GROUPPANEL':
                    return this.renderGroupPanel(modelJson as IPSDEFormGroupPanel, index);
                case 'TABPAGE':
                    return this.renderTabPage(modelJson as IPSDEFormTabPage, index);
                case 'TABPANEL':
                    return this.renderTabPanel(modelJson as IPSDEFormTabPanel, index);
                case 'FORMITEM':
                    const editor = (modelJson as IPSDEFormItem).getPSEditor();
                    if (editor) {
                        if (editor.editorStyle === 'noteEditor' && editor.editorType.toLowerCase() === 'textarea') {
                            this.memo = this.renderFormItem(modelJson as IPSDEFormItem, index);
                            return null;
                        }
                    }
                    return this.renderFormItem(modelJson as IPSDEFormItem, index);
                case 'BUTTON':
                    return this.renderButton(modelJson as IPSDEFormButton, index);
                case 'DRUIPART':
                    return this.renderDruipart(modelJson as IPSDEFormDRUIPart, index);
                case 'RAWITEM':
                    return this.renderRawitem(modelJson as IPSDEFormRawItem, index);
                case 'IFRAME':
                    return this.renderIframe(modelJson as IPSDEFormIFrame, index);
                case 'FORMPART':
                    return this.renderFormPart(modelJson as IPSDEFormFormPart, index);
            }
        }
    }

    /**
     * 绘制内容
     *
     * @returns
     * @memberof AppFormBase
     */
    public render(): any {
        if (!this.controlIsLoaded) {
            return null;
        }
        const { controlClassNames } = this.renderOptions;
        const formId =
            this.controlInstance.getPSAppDataEntity()?.codeName?.toLowerCase() +
            this.controlInstance.codeName?.toLowerCase();
        const controlStyle = {
            width: this.controlInstance.width ? this.controlInstance.width + 'px' : '',
            height: this.controlInstance.height ? this.controlInstance.height + 'px' : ''
        };
        const viewType = (this.controlInstance.getParentPSModelObject() as IPSAppDEView).viewType;
        return (
            <i-form
                props={{ model: this.data }}
                class={{ ...controlClassNames, 'app-form': true, 'memo-form': true, 'memo-mode': this.memo, 'closed': this.collapsed }}
                ref={this.controlInstance.name}
                id={formId}
                style={controlStyle}
                on-on-validate={this.formItemValidate.bind(this)}
            >
                <input style='display:none;' />
                {this.showFormNavBar && this.groupAnchorDatas.length > 0 ? <app-anchor viewType={viewType} anchorDatas={this.groupAnchorDatas}></app-anchor> : null}
                <row>{this.renderFormContent()}</row>
                {this.renderMemo()}
            </i-form>
        );
    }

}
