import { IPSDESearchForm, IPSSearchBar, IPSAppDEMultiDataView, IPSAppCodeList, IPSCodeItem, IPSAppDEField } from '@ibizstudio-ex/runtime';
import { CodeListServiceBase, throttle, LogUtil, ModelTool, Util, MDViewInterface } from '@ibizstudio-ex/runtime';
import { VNode } from 'vue';
import { AppLayoutService } from '../app-service';
import { AppGlobalService } from '../app-service/logic-service/app-global-action-service';
import { MainViewBase } from './mainview-base';

/**
 * 多数据视图基类
 *
 * @export
 * @class MDViewBase
 * @extends {MainViewBase}
 * @implements {MDViewInterface}
 */
export class MDViewBase extends MainViewBase implements MDViewInterface {
  /**
   * 多数据部件是否单选
   *
   * @type {boolean}
   * @memberof MDViewBase
   */
  isSingleSelect!: boolean;

  /**
   * 代码表服务对象
   *
   * @type {CodeListService}
   * @memberof MDViewBase
   */
  codeListService!: CodeListServiceBase;

  /**
   * 快速搜索值
   *
   * @type {string}
   * @memberof MDViewBase
   */
  query: string = '';

  /**
   * 是否展开搜索表单（接收参数）
   *
   * @type {boolean}
   * @memberof MDViewBase
   */
  expandSearchForm: boolean = false;

  /**
   * 实际是否展开搜索表单
   *
   * @type {boolean}
   * @memberof MDViewBase
   */
  isExpandSearchForm: boolean = false;

  /**
   * 是否启用快速分组
   *
   * @memberof MDViewBase
   */
  isEnableQuickGroup!: boolean;

  /**
   * 快速分组数据对象
   *
   * @memberof MDViewBase
   */
  quickGroupData: any;

  /**
   * 快速分组是否有抛值
   *
   * @memberof MDViewBase
   */
  isEmitQuickGroupValue: boolean = false;

  /**
   * 快速分组模型数据
   *
   * @memberof MDViewBase
   */
  quickGroupModel: Array<any> = [];

  /**
   * 快速分组代码表
   *
   * @type {boolean}
   * @memberof MDViewBase
   */
  quickGroupCodeList: any = null;

  /**
   * 搜索表单实例
   *
   * @type {IBizSearchFormModel}
   * @memberof MDViewBase
   */
  searchFormInstance!: IPSDESearchForm;

  /**
   * 快速搜索表单实例
   *
   * @type {IBizSearchFormModel}
   * @memberof MDViewBase
   */
  quickSearchFormInstance!: IPSDESearchForm;

  /**
   * 搜索栏实例
   *
   * @type {IBizSearchBarModel}
   * @memberof MDViewBase
   */
  searchBarInstance!: IPSSearchBar;

  /**
   * 可搜索字段名称
   *
   * @type {(string)}
   * @memberof MDViewBase
   */
  placeholder: string = '';

  /**
   * 搜索栏显示
   *
   * @type {boolean}
   * @memberof MDViewBase
   */
  visible: boolean = false;

  /**
   * popover层级
   *
   * @type {number}
   * @memberof MDViewBase
   */
  zIndex: number = 0;

  /**
   * 唯一标识
   *
   * @type {string}
   * @memberof MDViewBase
   */
  uuid: string = Util.createUUID();

  /**
   * 加载快速分组模型
   *
   * @memberof MDViewBase
   */
  async loadQuickGroupModel() {
    try {
      await this.quickGroupCodeList?.fill?.();
      if (!(this.quickGroupCodeList && this.quickGroupCodeList.codeName)) {
        return;
      }
      let res: any = await this.codeListService.getDataItems({
        tag: this.quickGroupCodeList.codeName,
        type: this.quickGroupCodeList.codeListType,
        data: this.quickGroupCodeList,
        context: this.context,
      });
      this.quickGroupModel = this.handleDynamicData(JSON.parse(JSON.stringify(res)));
    } catch (error) {
      LogUtil.log(`----${this.quickGroupCodeList.codeName}----${this.$t('app.commonwords.codenotexist')}`);
    }
  }

  /**
   * 处理快速分组模型动态数据部分(%xxx%)
   *
   * @memberof MDViewBase
   */
  handleDynamicData(inputArray: Array<any>) {
    if (inputArray.length > 0) {
      const defaultSelect: any = this.getQuickGroupDefaultSelect();
      if (defaultSelect) {
        let select = inputArray.find((item: any) => {
          return item.value === defaultSelect.value;
        });
        if (select) select.default = true;
      }
      inputArray.forEach((item: any) => {
        if (item.data && Object.keys(item.data).length > 0) {
          Object.keys(item.data).forEach((name: any) => {
            let value: any = item.data[name];
            if (value && typeof value == 'string' && value.startsWith('%') && value.endsWith('%')) {
              const key = value.substring(1, value.length - 1).toLowerCase();
              if (this.context[key]) {
                value = this.context[key];
              } else if (this.viewparams[key]) {
                value = this.viewparams[key];
              }
            }
            item.data[name] = value;
          });
        }
      });
    }
    return inputArray;
  }

  /**
   * 获取快速分组默认选中项
   *
   * @memberof MDViewBase
   */
  getQuickGroupDefaultSelect() {
    let defaultSelect: any = null;
    const codeItems: Array<IPSCodeItem> = (this.quickGroupCodeList as IPSAppCodeList).getPSCodeItems() || [];
    if (codeItems.length > 0) {
      for (const item of codeItems) {
        const childItems = item.getPSCodeItems?.() || [];
        if (childItems.length > 0) {
          defaultSelect = childItems.find((_item: any) => {
            return _item.default;
          });
        }
        if (item.default || defaultSelect) {
          defaultSelect = item;
          break;
        }
      }
    }
    return defaultSelect;
  }

  /**
   * 快速分组值变化
   *
   * @param {*} $event 事件源
   * @memberof MDViewBase
   */
  quickGroupValueChange($event: any) {
    if ($event) {
      this.quickGroupData = $event.data;
      if (this.isEmitQuickGroupValue) {
        this.onSearch($event);
      }
    }
    this.isEmitQuickGroupValue = true;
  }

  /**
   * 快速搜索
   *
   * @param {*} $event
   * @memberof MDViewBase
   */
  onSearch($event: any): void {}

  /**
   * 快速搜索栏数据对象
   *
   * @memberof MDViewBase
   */
  quickFormData: any;

  /**
   * 初始化日历视图实例
   *
   * @param opts
   * @memberof MDViewBase
   */
  async viewModelInit() {
    await super.viewModelInit();
    this.searchFormInstance = ModelTool.findPSControlByName('searchform', this.viewInstance.getPSControls() || []) as IPSDESearchForm;
    this.quickSearchFormInstance = ModelTool.findPSControlByName('quicksearchform', this.viewInstance.getPSControls() || []) as IPSDESearchForm;
    this.searchBarInstance = ModelTool.findPSControlByType('SEARCHBAR', this.viewInstance.getPSControls() || []) as IPSSearchBar;
    this.isEnableQuickGroup = this.viewInstance?.enableQuickGroup;
    this.quickGroupCodeList = (this.viewInstance as IPSAppDEMultiDataView)?.getQuickGroupPSCodeList?.();
    let _this: any = this;
    if (this.isEnableQuickGroup) {
      this.codeListService = new CodeListServiceBase({ $store: _this.$store });
      await this.loadQuickGroupModel();
    }
  }

  /**
   *  多数据视图初始化
   *
   * @memberof MDViewBase
   */
  viewInit() {
    super.viewInit();
    // 初始化属性值
    this.query = '';
    this.expandSearchForm = this.viewInstance?.expandSearchForm ? true : false;
    this.initQuickSearchPlaceholder();
  }

  /**
   * 视图挂载
   *
   * @memberof MDViewBase
   */
  viewMounted() {
    super.viewMounted();
    this.handleDefaultExpandSearchForm();
    this.initPopoverZIndex();
    //点击搜索表单区域外
    this.onSearchFormClickOutSide = this.onSearchFormClickOutSide.bind(this);
    this.keyDown = this.keyDown.bind(this);
    window.addEventListener('click', this.onSearchFormClickOutSide);
    window.addEventListener('keydown', this.keyDown);
  }

  /**
   * 视图销毁
   *
   * @memberof MDViewBase
   */
  viewDestroyed() {
    super.viewDestroyed();
    window.removeEventListener('click', this.onSearchFormClickOutSide);
    window.removeEventListener('keydown', this.keyDown);
    const searchFormPopover: any = this.$el.querySelector(`.search-from-popover-${this.uuid}`);
    if (searchFormPopover) {
      this.$store.commit('downZIndex');
    }
  }

  /**
   * 初始化气泡打开层数
   *
   * @memberof MDViewBase
   */
  initPopoverZIndex() {
    const searchFormPopover: any = this.$el.querySelector(`.search-from-popover-${this.uuid}`);
    if (searchFormPopover) {
      this.$store.commit('upZIndex');
      this.zIndex = this.$store.getters.getZIndex();
    }
  }

  /**
   * 显示气泡
   *
   * @memberof MDViewBase
   */
  showPopover() {
    setTimeout(() => {
      const searchForm: any = document.body.getElementsByClassName(`search-from-popover-${this.uuid}`)[0];
      if (searchForm) {
        searchForm.style.zIndex = this.zIndex;
      }
    });
  }

  /**
   * 点击外部区域关闭搜索表单
   *
   * @param {*} $event
   * @memberof MDViewBase
   */
  onSearchFormClickOutSide($event: any) {
    const searchForm = document.body.querySelector(`.search-from-popover-${this.uuid} .app-search-form`);
    if (searchForm) {
      const modal = document.body.getElementsByClassName('app-modal')[0];
      if (!modal && $event.target?.className.indexOf('ivu-icon-ios-funnel') == -1) {
        this.visible = false;
      }
    }
  }

  /**
   * 监听按键事件ESC
   *
   * @memberof MDViewBase
   */
  keyDown($event: any) {
    const searchForm = document.body.querySelector(`.search-from-popover-${this.uuid} .app-search-form`);
    if (searchForm && ($event.keyCode == 27 || $event.keyCode == 96)) {
      this.visible = false;
    }
  }

  /**
   * 处理默认展开搜索表单
   *
   * @memberof MDViewBase
   */
  handleDefaultExpandSearchForm() {
    //  默认展开搜索表单
    if (this.expandSearchForm) {
      //  搜索表单以弹框展示
      if (this.viewInstance?.viewStyle == 'DEFAULT' && this.viewInstance?.enableQuickSearch) {
        this.$nextTick(() => {
          const element = (this.$refs['filterButton'] as any)?.$el;
          if (element) {
            (element as HTMLElement).click();
          }
        });
      } else {
        this.isExpandSearchForm = this.expandSearchForm;
      }
    }
  }

  /**
   *  初始化快速搜索栏空白填充内容
   *
   * @memberof MDViewBase
   */
  initQuickSearchPlaceholder() {
    const quickSearchFields: Array<IPSAppDEField> = (this.viewInstance as IPSAppDEMultiDataView).getPSAppDataEntity()?.getQuickSearchPSAppDEFields() || [];
    if (quickSearchFields.length > 0) {
      quickSearchFields.forEach((field: IPSAppDEField, index: number) => {
        const _field: IPSAppDEField | null | undefined = (this.viewInstance as IPSAppDEMultiDataView).getPSAppDataEntity()?.findPSAppDEField(field.codeName);
        if (_field) {
          this.placeholder += this.$tl(_field.getLNPSLanguageRes()?.lanResTag, _field.logicName) + (index === quickSearchFields.length - 1 ? '' : ', ');
        }
      });
    }
  }

  /**
   * 快速搜索栏值变化
   *
   * @memberof MDViewBase
   */
  quickFormValueChange($event: any) {
    this.quickFormData = $event;
    this.onSearch($event);
  }

  /**
   * 视图实例
   *
   * @memberof MDViewBase
   */
  declare viewInstance: any;

  /**
   * 渲染快速分组
   *
   * @memberof MDViewBase
   */
  renderQuickGroup() {
    if (!this.viewInstance?.enableQuickGroup) {
      return;
    }
    let counterService: any;
    if (this.viewInstance?.getPSAppCounterRef?.()?.id) {
      counterService = Util.findElementByField(this.counterServiceArray, 'id', this.viewInstance?.getPSAppCounterRef?.()?.id)?.service;
    }
    return (
      <div class='quick-group-container' slot='quickGroupSearch'>
        <app-quick-group items={this.quickGroupModel} on-valuechange={this.quickGroupValueChange.bind(this)} counterService={counterService}></app-quick-group>
      </div>
    );
  }

  /**
   * 渲染快速搜索
   *
   * @memberof MDViewBase
   */
  renderQuickSearch() {
    if (!this.viewInstance?.enableQuickSearch) {
      return;
    }
    if (this.viewInstance?.viewStyle == 'DEFAULT') {
      return this.renderDefaultQuickSearch();
    } else {
      return this.renderStyle2QuickSearch();
    }
  }

  /**
   * 渲染快速搜索(DEFAULT)
   *
   * @return {*}
   * @memberof MDViewBase
   */
  renderDefaultQuickSearch() {
    const barFilters: Array<any> = this.searchBarInstance?.getPSSearchBarFilters() || [];
    const searchformItem: Array<any> = this.searchFormInstance?.getPSDEFormItems() || [];
    let enableFilter = (this.viewInstance?.enableFilter === true && barFilters.length > 0) || searchformItem.length > 0;
    const popoverClass: string = this.searchFormInstance ? 'searchform-popover' : this.searchBarInstance ? 'searchbar-popover' : '';
    return (
      <template slot='quickSearch'>
        <i-input
          class={{ 'app-quick-search': true, 'width-filter': enableFilter }}
          style='max-width: 400px;margin-top:4px;padding-left: 24px'
          search
          on-on-search={($event: any) => this.onSearch($event)}
          v-model={this.query}
          placeholder={this.placeholder}
        />
        {
          <el-popover
            placement='bottom'
            popper-class={`${popoverClass} search-from-popover-${this.uuid}`}
            trigger='manual'
            visible-arrow={false}
            on-show={() => this.showPopover()}
            on-hide={() => (this.isExpandSearchForm = !this.isExpandSearchForm)}
            v-model={this.visible}
          >
            <i-button
              slot='reference'
              ref='filterButton'
              class={{ filter: true, 'is-expand': this.isExpandSearchForm, 'hidden-searchbtn': !enableFilter }}
              icon='ios-funnel'
              on-click={(e: any) => {
                setTimeout(() => {
                  this.visible = !this.visible;
                  if (!this.isExpandSearchForm) {
                    throttle(() => (AppGlobalService.getInstance() as any).executeGlobalAction('ToggleFilter', undefined, undefined, undefined, e, undefined, this, undefined), [], this);
                  }
                });
              }}
            />
            {popoverClass && popoverClass != '' ? (popoverClass == 'searchform-popover' ? this.renderSearchForm() : this.renderSearchBar()) : null}
          </el-popover>
        }
      </template>
    );
  }

  /**
   * 渲染快速搜索(STYLE2)
   *
   * @return {*}
   * @memberof MDViewBase
   */
  renderStyle2QuickSearch() {
    return (
      <i-input
        slot='quickSearch'
        className='app-quick-search'
        style='max-width: 400px;margin-top:6px;padding-left: 24px'
        search
        enter-button
        on-on-search={($event: any) => this.onSearch($event)}
        v-model={this.query}
        placeholder={this.placeholder}
      />
    );
  }

  /**
   * 计算目标部件所需参数
   *
   * @param {string} [controlType]
   * @returns
   * @memberof GridViewBase
   */
  computeTargetCtrlData(controlInstance: any) {
    const { targetCtrlName, targetCtrlParam, targetCtrlEvent } = super.computeTargetCtrlData(controlInstance);
    if (controlInstance.controlType == 'SEARCHFORM') {
      Object.assign(targetCtrlParam.dynamicProps, {
        isExpandSearchForm: this.isExpandSearchForm,
      });
    }
    Object.assign(targetCtrlParam.staticProps, {
      mDCtrlActiveMode: this.viewInstance.mDCtrlActiveMode,
    });
    return { targetCtrlName: targetCtrlName, targetCtrlParam: targetCtrlParam, targetCtrlEvent: targetCtrlEvent };
  }

  /**
   * 渲染搜索表单
   *
   * @memberof MDViewBase
   */
  renderSearchForm() {
    if (!this.searchFormInstance) {
      return;
    }
    let { targetCtrlName, targetCtrlParam, targetCtrlEvent } = this.computeTargetCtrlData(this.searchFormInstance);
    if (this.viewInstance?.viewStyle == 'DEFAULT' && this.viewInstance?.enableQuickSearch) {
      return this.$createElement(targetCtrlName, { props: targetCtrlParam, ref: this.searchFormInstance?.name, on: targetCtrlEvent });
    } else {
      return this.$createElement(targetCtrlName, { slot: 'searchForm', props: targetCtrlParam, ref: this.searchFormInstance?.name, on: targetCtrlEvent });
    }
  }

  /**
   * 渲染快速搜索表单
   *
   * @memberof MDViewBase
   */
  renderQuickSearchForm() {
    if (!this.quickSearchFormInstance) {
      return;
    }
    let { targetCtrlName, targetCtrlParam, targetCtrlEvent } = this.computeTargetCtrlData(this.quickSearchFormInstance);
    return this.$createElement(targetCtrlName, { slot: 'quickSearchForm', props: targetCtrlParam, ref: this.quickSearchFormInstance?.name, on: targetCtrlEvent });
  }

  /**
   * 渲染搜索栏
   *
   * @memberof MDViewBase
   */
  renderSearchBar() {
    if (!this.searchBarInstance) {
      return;
    }
    let { targetCtrlName, targetCtrlParam, targetCtrlEvent } = this.computeTargetCtrlData(this.searchBarInstance);
    Object.assign(targetCtrlParam.dynamicProps, {
      isExpandSearchForm: this.isExpandSearchForm,
    });
    if (this.viewInstance?.viewStyle == 'DEFAULT' && this.viewInstance?.enableQuickSearch) {
      return this.$createElement(targetCtrlName, { props: targetCtrlParam, ref: this.searchBarInstance?.name, on: targetCtrlEvent });
    } else {
      return this.$createElement(targetCtrlName, { slot: 'searchBar', props: targetCtrlParam, ref: this.searchBarInstance?.name, on: targetCtrlEvent });
    }
  }

  render(h: any): VNode | null {
    if (!this.viewIsLoaded) {
      return null;
    }
    const targetViewLayoutComponent: any = AppLayoutService.getLayoutComponent(`${this.viewInstance?.viewType}-${this.viewInstance?.viewStyle}`);
    return h(
      targetViewLayoutComponent,
      {
        props: { viewInstance: this.viewInstance, model: this.model, modelService: this.modelService, viewparams: this.viewparams, context: this.context },
      },
      [
        this.renderTopMessage(),
        this.renderToolBar(),
        this.renderQuickGroup(),
        this.renderQuickSearch(),
        this.renderBodyMessage(),
        !(this.viewInstance?.viewStyle == 'DEFAULT' && this.viewInstance?.enableQuickSearch) ? [this.renderSearchForm(), this.renderSearchBar()] : null,
        this.renderMainContent(),
        this.renderBottomMessage(),
      ],
    );
  }

  /**
   * 部件事件
   * @param ctrl 部件
   * @param action  行为
   * @param data 数据
   *
   * @memberof MDViewBase
   */
  onCtrlEvent(controlname: string, action: string, data: any) {
    super.onCtrlEvent(controlname, action, data);
    if (Object.is(controlname, 'quicksearchform') && Object.is(action, 'valuechange')) {
      this.quickFormValueChange(data);
    }
  }
}
