import { IActionParam, MainControl } from '@core';
import { IParam } from '@core/interface';
import { PickupViewPanelControlProps } from './pickup-view-panel-control-prop';
import { PickupViewPanelControlState } from './pickup-view-panel-control-state';

/**
 * @description 选择视图面板部件
 * @export
 * @class PickupViewPanelControl
 * @extends {MainControl}
 */
export class PickupViewPanelControl extends MainControl {

  /**
   * @description 部件状态
   * @type {FormControlState}
   * @memberof PickupViewPanelControl
   */
  public declare state: PickupViewPanelControlState;

  /**
   * 部件事件
   *
   * @param {IActionParam} actionParam
   * @memberof PickupViewPanelControl
   */
  public onViewEvent(actionParam: IActionParam) {
    const { tag, action, data } = actionParam;
    const { controlName } = this.state;
    if (Object.is("selectionChange", action)) {
      this.handleSelectionChange(data);
    }
    if (Object.is("viewLoad", action)) {
      this.handleViewLoad(data);
    }
  }

  /**
   * 处理数据变化
   *
   * @private
   * @param {IParam[]} items
   * @return {*} 
   * @memberof PickupViewPanelControl
   */
  private handleSelectionChange(items: IParam[]) {
    if (items && items.length) {
      const { appDeKeyFieldName, appDeMajorFieldName } = this.state;
      const _items: IParam[] = [];
      items.forEach((item: IParam) => {
        _items.push({
          srfkey: item.srfkey ? item.srfkey : item[appDeKeyFieldName.toLowerCase()],
          srfmajortext: item.srfmajortext ? item.srfmajortext : item[appDeMajorFieldName.toLowerCase()]
        });
      });
      this.emit("onCtrlEvent", { tag: this.props.name, action: 'selectionChange', data: _items });
      return;
    }
    this.emit("onCtrlEvent", { tag: this.props.name, action: 'selectionChange', data: [] });
  }

  /**
   * 处理视图加载完成事件
   *
   * @private
   * @param {IParam[]} [data=[]]
   * @memberof PickupViewPanelControl
   */
  private handleViewLoad(data: IParam[] = []) {
    const { items } = toRefs(this.state);
    const { appDeKeyFieldName, appDeMajorFieldName } = this.state;
    const _items: IParam[] = [];
    data.forEach((item: any) => {
      _items.push({
        srfkey: item.srfkey ? item.srfkey : item[appDeKeyFieldName.toLowerCase()],
        srfmajortext: item.srfmajortext ? item.srfmajortext : item[appDeMajorFieldName.toLowerCase()]
      });
    });
    items.value = [..._items];
  }

  /**
   * @description 安装部件所有功能模块的方法
   * @return {*} 
   * @memberof PickupViewPanelControl
   */
  public moduleInstall() {
    const superParams = super.moduleInstall();
    return {
      ...superParams,
      onViewEvent: this.onViewEvent.bind(this)
    };
  }
}