/**
 * 通用类型定义
 * 
 * 功能介绍：
 *    为 API 提供了一些通用结构定义。
 * 
 * Author: imengyu
 * Date: 2025/12/27
 * 
 * Copyright (c) 2021 imengyu.top. Licensed under the MIT License. 
 * See License.txt in the project root for license information.
 */

import { DataModel, type KeyValue } from '@imengyu/js-request-transform';

/**
 * 通用分页返回结构定义
 */
export class CommonArrayResult<T extends DataModel> extends DataModel {
  /**
   * 数据
   */
  items: T[] = [];
  /**
   * 系统中一共有多少条数据
   */
  total = 0;

  constructor() {
    super(CommonArrayResult);
  }

  fromData(data: KeyValue[] | undefined | null, total: number|undefined, dataModel: new () => T): this {
    this.items = data?.map((item) => new dataModel().fromServerSide(item) as T) || [];
    this.total = total || this.items.length;
    return this;
  }
}

/**
 * 通用下拉框返回结构定义
 */
export class CommonListResult extends DataModel {
  /**
   * 数据
   */
  items: {
    text: string;
    value: number;
    raw: KeyValue;
  }[] = [];
  
  constructor() {
    super(CommonListResult);
  }

  fromData(data: KeyValue[] | undefined | null): this {
    this.items = data?.map((item) => ({
      text: item.label as string,
      value: item.value as number,
      raw: item,
    })) || [];
    return this;
  }
}
/**
 * 通用分页返回结构定义
 */
export class CommonPageResult<T extends DataModel> extends DataModel {
  /**
   * 当前页数据
   */
  items: T[] = [];
  /**
   * 当前页码
   */
  pageIndex = 0;
  /**
   * 当前页的大小
   */
  pageSize = 0;
  /**
   * 系统中一共有多少条数据
   */
  allCount = 0;
  /**
   * 系统中一共有多少页
   */
  allPage = 0;
  /**
   * 指示当前页是不是空的
   */
  empty = true;

  constructor() {
    super(CommonPageResult);
  }

  fromData(
    data: {
      allCount?: number,
      allPage?: number,
      items?: KeyValue[] | undefined | null,
    }, 
    page: number,
    size: number,
    dataModel: new () => T
  ): this {
    const listFromServer = data.items as unknown as Array<unknown>;
    const list = new Array<T>();
    if(listFromServer instanceof Array) {
      let index = 1;
      listFromServer.forEach((i) => {
        const ii = new dataModel().fromServerSide(i as KeyValue); 
        ii.index = index++;
        list.push(ii as T);
      });
    }

    this.items = list;
    this.pageIndex = page;
    this.pageSize = size;
    this.allCount = data.allCount as number;
    this.allPage = data.allPage as number;
    this.empty = list.length == 0;

    return this;
  }
}

/**
 * 加载状态
 */
export type LoadStatus = 'notload'|'success'|'failed'|'loading' ;