import { Component, Prop } from 'vue-property-decorator';
import { VueLifeCycleProcessing, EditorBase } from '@ibizstudio-ex/template-vue';
import { IPSAppCodeList, IPSAppDEView, IPSAppView, IPSCodeListEditor, IPSDEFormItem, IPSPicker, IPSPickerEditor } from '@ibizstudio-ex/runtime';
import { AppModelService, GetModelService, ModelTool, Util } from '@ibizstudio-ex/runtime';
import AppEmbedPicker from './components/app-embed-picker/app-embed-picker.vue';

/**
 * 上传实体名称嵌入视图插件类
 *
 * @export
 * @class UpdateEntitynamePicker
 * @extends {EditorBase}
 */
@Component({
  components: {
    AppEmbedPicker,
  },
})
@VueLifeCycleProcessing()
export class UpdateEntitynamePicker extends EditorBase {
  /**
   * 是否忽略表单项值变化
   *
   * @type {boolean}
   * @memberof AppDefaultEditor
   */
  @Prop() public ignorefieldvaluechange?: any;

  /**
   * 代码表对象
   *
   * @type {IPSAppCodeList}
   * @memberof DataPickerEditor
   */
  public codeList?: IPSAppCodeList | null;

  /**
   * 模型服务
   *
   * @type {AppModelService}
   * @memberof DataPickerEditor
   */
  public modelService!: AppModelService;

  /**
   * 编辑器初始化
   *
   * @memberof DataPickerEditor
   */
  public async initEditor() {
    await super.initEditor();
    await this.initModelService();
    // 加载链接视图和选择视图
    const pickupAppView: IPSAppView | null = (this.editorInstance as IPSPickerEditor)?.getPickupPSAppView?.();
    const linkAppView: IPSAppView | null = (this.editorInstance as IPSPicker)?.getLinkPSAppView?.();
    await (pickupAppView as any)?.fill(true);
    await (linkAppView as any)?.fill(true);

    this.codeList = (this.editorInstance as IPSCodeListEditor)?.getPSAppCodeList?.();
    const { placeHolder } = this.editorInstance;
    this.customProps.deMajorField = ModelTool.getEditorMajorName(this.editorInstance);
    this.customProps.deKeyField = ModelTool.getEditorKeyName(this.editorInstance);
    this.customProps.emptyText = placeHolder;
    this.customProps.viewModelData = pickupAppView || undefined;
    this.customProps.refreshitems = (this.editorInstance.getParentPSModelObject() as IPSDEFormItem).getResetItemNames();
  }

  /**
   * 初始化选择视图相关参数
   *
   * @memberof DataPickerEditor
   */
  public initPickupViewParams() {
    const pickupAppView = (this.editorInstance as IPSPickerEditor).getPickupPSAppView();
    if (pickupAppView) {
      const view: any = {
        viewname: 'app-view-shell',
        title: this.$tl(pickupAppView.getCapPSLanguageRes()?.lanResTag, pickupAppView.title),
        width: pickupAppView?.width,
        height: pickupAppView?.height,
        placement: pickupAppView?.openMode,
        isRedirectView: pickupAppView.hasOwnProperty('redirectView') ? pickupAppView.redirectView : false,
        viewpath: pickupAppView?.modelPath,
      };
      this.customProps.pickupView = view;
    }
  }

  /**
   * 初始化模型服务
   *
   * @memberof DataPickerEditor
   */
  public async initModelService() {
    this.modelService = await GetModelService(this.context);
  }

  /**
   * 初始化链接视图相关参数
   *
   * @memberof DataPickerEditor
   */
  public async initLinkViewParams() {
    const linkAppView = (this.editorInstance as IPSPicker).getLinkPSAppView();
    await linkAppView?.fill(true);
    if (linkAppView) {
      const view: any = {
        viewname: 'app-view-shell',
        title: this.$tl(linkAppView.getCapPSLanguageRes()?.lanResTag, linkAppView.title),
        width: linkAppView?.width,
        height: linkAppView?.height,
        placement: linkAppView?.openMode,
        deResParameters: Util.formatAppDERSPath(this.context, (linkAppView as IPSAppDEView).getPSAppDERSPaths()),
        isRedirectView: linkAppView.redirectView,
        viewpath: linkAppView?.modelPath,
      };
      Object.defineProperty(view, 'viewModel', { enumerable: false, writable: true, value: linkAppView });
      if (linkAppView?.getPSAppDataEntity()) {
        Object.assign(view, {
          parameters: [
            { pathName: Util.srfpluralize(linkAppView.getPSAppDataEntity()?.codeName || '').toLowerCase(), parameterName: linkAppView.getPSAppDataEntity()?.codeName.toLowerCase() },
            { pathName: 'views', parameterName: (linkAppView as IPSAppDEView).getPSDEViewCodeName()?.toLowerCase() },
          ],
        });
      } else {
        Object.assign(view, {
          parameters: [{ pathName: 'views', parameterName: linkAppView.codeName.toLowerCase() }],
        });
      }
      this.customProps.linkview = view;
    }
  }

  /**
   * 初始化AC相关参数
   *
   * @memberof DataPickerEditor
   */
  public initAcParams() {
    this.customProps.acParams = ModelTool.getAcParams(this.editorInstance);
    this.customProps.sort = ModelTool.getAcSort(this.editorInstance);
  }

  /**
   * 绘制嵌入视图
   *
   * @memberof DataPickerEditor
   */
  public renderEmbedPicker() {
    return this.$createElement(this.editorComponentName, {
      props: {
        name: this.editorInstance.name,
        value: this.value,
        disabled: this.disabled,
        ignorefieldvaluechange: this.ignorefieldvaluechange,
        data: JSON.stringify(this.contextData),
        context: this.context,
        viewparams: this.viewparams,
        valueItem: this.parentItem?.valueItemName || '',
        ...this.customProps,
      },
      on: { formitemvaluechange: this.editorChange },
      style: this.customStyle,
    });
  }

  /**
   * 默认绘制
   *
   * @memberof DataPickerEditor
   */
  public renderDefault() {
    return this.$createElement(AppEmbedPicker, {
      props: {
        parentCodeName: this.parentItem?.codeName,
        name: this.editorInstance.name,
        value: this.value,
        disabled: this.disabled,
        data: this.contextData,
        context: this.context,
        viewparams: this.viewparams,
        service: this.service,
        pickUpData: this.editorInstance.editorParams?.['pickupdata'] ? this.editorInstance.editorParams?.['pickupdata'] : null,
        valueItem: this.parentItem?.valueItemName || '',
        ...this.customProps,
      },
      on: { formitemvaluechange: this.editorChange },
      style: this.customStyle,
    });
  }

  /**
   * 数据选择插件（地图定位）
   *
   * @memberof DataPickerEditor
   */
  public renderMapPosition() {
    return this.$createElement(this.editorComponentName, {
      props: {
        name: this.editorInstance.name,
        value: this.value,
        disabled: this.disabled,
        data: this.contextData,
        context: this.context,
        viewparams: this.viewparams,
        ...this.customProps,
      },
      on: {
        change: (value: any) => {
          this.editorChange({ name: this.editorInstance.name, value: value });
        },
        itemChange: (val1: any, val2: any) => {
          this.editorChange(val1);
          this.editorChange(val2);
        },
      },
    });
  }

  /**
   * 单位选择器
   *
   * @memberof DataPickerEditor
   */
  public renderOrgSelect() {
    const params: any = this.initSelectPickerParams();
    Object.assign(params, {
      filter: this.editorInstance.editorParams?.['filter'] ? this.editorInstance.editorParams['filter'] : 'srforgid',
    });
    return this.$createElement(this.editorComponentName, {
      props: params,
      on: {
        'select-change': this.editorChange.bind(this),
      },
    });
  }

  /**
   * 部门人员选择器
   *
   * @memberof DataPickerEditor
   */
  public renderDepartmentPersonnel() {
    const params: any = this.initSelectPickerParams();
    Object.assign(params, {
      filter: this.editorInstance.editorParams?.['filter'] ? this.editorInstance.editorParams['filter'] : 'srfpdept',
    });
    if (this.editorInstance.editorParams?.['treeurl']) {
      Object.assign(params, {
        treeurl: this.editorInstance.editorParams['treeurl'],
      });
    }
    return this.$createElement(this.editorComponentName, {
      props: params,
      on: {
        formitemvaluechange: this.editorChange.bind(this),
      },
    });
  }

  /**
   * 单位人员选择器
   *
   * @memberof DataPickerEditor
   */
  public renderGroupSelect() {
    const params: any = this.initSelectPickerParams();
    Object.assign(params, {
      filter: this.editorInstance.editorParams?.['filter'] ? this.editorInstance.editorParams['filter'] : 'srforgid',
    });
    if (this.editorInstance.editorParams?.['treeurl']) {
      Object.assign(params, {
        treeurl: this.editorInstance.editorParams['treeurl'],
      });
    }
    if (this.editorInstance.editorParams?.['editorMode']) {
      Object.assign(params, {
        editorMode: this.editorInstance.editorParams['editorMode'],
      });
    }
    return this.$createElement(this.editorComponentName, {
      props: params,
      on: {
        formitemvaluechange: this.editorChange.bind(this),
      },
    });
  }

  /**
   * 部门选择器
   *
   * @memberof DataPickerEditor
   */
  public renderDepartmentSelect() {
    const params: any = this.initSelectPickerParams();
    Object.assign(params, {
      filter: this.editorInstance.editorParams?.['filter'] ? this.editorInstance.editorParams['filter'] : 'srforgid',
    });
    return this.$createElement(this.editorComponentName, {
      props: params,
      on: {
        'select-change': this.editorChange.bind(this),
      },
    });
  }

  /**
   * 单多选列表框
   *
   * @memberof DataPickerEditor
   */
  public renderCommonMicrocom() {
    const params: any = this.initSelectPickerParams();
    Object.is(params, {
      viewparams: this.viewparams,
    });
    return this.$createElement(this.editorComponentName, {
      props: params,
      on: {
        formitemvaluechange: this.editorChange.bind(this),
      },
    });
  }

  /**
   * 组织部门人员微服务组件参数处理
   *
   * @memberof DataPickerEditor
   */
  public initSelectPickerParams() {
    const params: any = {
      name: this.editorInstance.name,
      value: this.value,
      valueitem: this.parentItem?.valueItemName || '',
      multiple: this.editorInstance.editorParams?.['multiple'] ? JSON.parse(this.editorInstance.editorParams['multiple'] as string) : false,
      url: this.editorInstance.editorParams?.['url'],
      filter: this.editorInstance.editorParams?.['filter'],
      requestMode: this.editorInstance.editorParams?.['requestMode']?.toLowerCase(),
      fillMap: this.editorInstance.editorParams?.['fillMap']
        ? eval('(' + this.editorInstance.editorParams['fillMap'] + ')')
        : { id: this.parentItem?.valueItemName || '', label: this.editorInstance.name },
      disabled: this.disabled,
      data: this.contextData,
      context: this.context,
      style: this.customStyle,
      localParam: this.customProps.localParam,
      localContext: this.customProps.localContext,
    };
    if (this.codeList) {
      Object.assign(params, {
        tag: this.codeList.codeName,
        codelistType: this.codeList.codeListType,
        renderMode: this.codeList.orMode,
        valueSeparator: this.codeList.valueSeparator,
        textSeparator: this.codeList.textSeparator,
      });
    }
    return params;
  }

  /**
   * 绘制内容
   *
   * @returns {*}
   * @memberof DataPickerEditor
   */
  public render(): any {
    if (!this.editorIsLoaded) {
      return null;
    }
    return this.renderDefault();
  }
}
