import { MainControl, TabExpPanelControlState, TabExpPanelControlProps, IParam } from '@core';
import { IAppCounterService } from '@core/interface';

/**
 * @description 分页导航部件
 * @export
 * @class TabExpPanelControl
 * @extends {MainControl}
 */
export class TabExpPanelControl extends MainControl {

  /**
   * @description 部件状态
   * @type {TabExpPanelControlState}
   * @memberof TabExpPanelControl
   */
  public declare state: TabExpPanelControlState;

  /**
   * 分页导航部件输出参数
   *
   * @type {TabExpPanelControlProps}
   * @memberof TabExpPanelControl
   */
  public declare props: TabExpPanelControlProps;

  /**
   * @memberof TabExpPanelControl
   */
  public setState() {
    super.setState();
    this.state.tabPosition = toRef(this.props, 'tabPosition') as any;
    this.state.activePanel = this.props.defaultActivePanel;
  }

  /**
   * 使用计数器模块
   *
   * @return {*} 
   * @memberof TabExpPanelControl
   */
  public useCounterService() {
    const { appCounterRefs, context, viewParams } = this.state;
    const { counterServices } = toRefs(this.state);
    if (appCounterRefs && appCounterRefs.length) {
      counterServices.value = [];
      appCounterRefs.forEach((counterRef: IParam) => {
        const _counterService = App.getCounterService(counterRef, context, viewParams);
        _counterService.execute().then(() => {
          counterServices.value.push(_counterService);
        });
      });
    }
    onUnmounted(() => {
      if (counterServices && counterServices.value && counterServices.value.length) {
        counterServices.value.forEach((service: IAppCounterService) => {
          service.destory();
        });
      }
    });

    //  获取计数器数据
    const getCounterData = (viewPanelCounterName?: string): number => {
      if (viewPanelCounterName) {
        const viewPanelCounter = this.state[viewPanelCounterName];
        if (!viewPanelCounter) {
          return 0;
        }
        const service: IAppCounterService = counterServices.value.find((_service: IAppCounterService) => _service.id === viewPanelCounter.id);
        if (service && service.data && service.data[viewPanelCounter.counterId]) {
          return service.data[viewPanelCounter.counterId];
        }
      }
      return 0;
    }
    return getCounterData;
  }

  /**
   * @description 安装部件所有功能模块的方法
   * @param {TabExpPanelControlProps} props 
   * @param {Function} [emit]
   * @return {*}
   * @memberof TabExpPanelControl [emit] 事件
   */
  public moduleInstall() {
    const superParams = super.moduleInstall();
    return {
      ...superParams
    };
  }

}