import { DebouncedFunc } from "lodash";
import { RendererEnv } from "../../env";
import { RendererProps } from "../../factory";
import { TranslateFn } from "../../locale";
import {
  BaseSchema,
  SchemaApi,
  SchemaClassName,
  SchemaCollection,
  SchemaExpression,
  SchemaMessage,
  SchemaName,
  SchemaObject,
  SchemaTokenizeableString,
  SchemaTpl
} from '../../Schema';
import { ICRUDStore } from "../../store/crud";
import { Api, PlainObject } from "../../types";
import { ActionSchema } from "../Action";
import { CardSchema } from "../Card";
import { ListSchema } from "../List";
import { TableSchema } from "../Table";




// 不做处理的按钮类型
export const specialButtonType = ['rfid-action']


export interface CRUDBultinToolbar extends Omit<BaseSchema, 'type'> {
  type: CRUDBultinToolbarType;
  renderPagenation: () => void
}


export type CRUDBultinToolbarType =
  | 'columns-toggler'
  | 'columns-filter'
  | 'auto-width'
  | 'drag-toggler'
  | 'pagination'
  | 'paginator'
  | 'headerBulkActions'
  | 'footerBulkActions'
  | 'bulk-actions'
  | 'statistics'
  | 'switch-per-page'
  | 'load-more'
  | 'filter-toggler'
  | 'export-csv'
  | 'export-excel';


export interface CRUDBultinToolbar extends Omit<BaseSchema, 'type'> {
  type: CRUDBultinToolbarType;
}

export type CRUDToolbarChild = SchemaObject | CRUDBultinToolbar;

export type CRUDToolbarObject = {
  /**
   * 对齐方式
   */
  align?: 'left' | 'right';
};


export interface CRUDCommonSchema extends BaseSchema {
  /**
   *  指定为 CRUD 渲染器。
   */
  type: 'crud';

  /**
   * 指定内容区的展示模式。
   */
  mode?: 'table' | 'grid' | 'cards' | /* grid 的别名*/ 'list' | 'cross';

  /**
   * 初始化数据 API
   */
  api?: SchemaApi;
  /**
   * 顶部批量操作
   */
  headerBulkActions?: Array<ActionSchema>;
  /**
   * 底部批量操作
   */
  footerBulkActions?: Array<ActionSchema>;
  /**
   * 单条操作
   */
  itemActions?: Array<ActionSchema>;

  /**
   * 每页个数，默认为 10，如果不是请设置。
   *
   * @default 10
   */
  perPage?: number;

  /**
   * 可以默认给定初始参数如： {\"perPage\": 24}
   */
  defaultParams?: PlainObject;

  /**
   * 是否可通过拖拽排序
   */
  draggable?: boolean;

  /**
   * 是否可通过拖拽排序，通过表达式来配置
   */
  draggableOn?: SchemaExpression;

  name?: SchemaName;
  // 页脚
  footer: any;
  /**
   * 过滤器表单
   */
  filter?: any; // todo

  /**
   * 初始是否拉取
   * @deprecated 建议用 api 的 sendOn 代替。
   */
  initFetch?: boolean;

  /**
   * 初始是否拉取，用表达式来配置。
   * @deprecated 建议用 api 的 sendOn 代替。
   */
  initFetchOn?: SchemaExpression;

  /**
   * 配置内部 DOM 的 className
   */
  innerClassName?: SchemaClassName;

  /**
   * 设置自动刷新时间
   */
  interval?: number;

  /**
   * 设置用来确定位置的字段名，设置后新的顺序将被赋值到该字段中。
   */
  orderField?: string;

  /**
   * 设置分页页码字段名。
   * @default page
   */
  pageField?: string;

  /**
   * 设置分页一页显示的多少条数据的字段名。
   * @default perPage
   */
  perPageField?: string;

  /**
   * 快速编辑后用来批量保存的 API
   */
  quickSaveApi?: SchemaApi;

  /**
   * 快速编辑配置成及时保存时使用的 API
   */
  quickSaveItemApi?: SchemaApi;

  /**
   * 保存排序的 api
   */
  saveOrderApi?: SchemaApi;

  /**
   * 是否将过滤条件的参数同步到地址栏,默认为true
   * @default true
   */
  syncLocation?: boolean;
  // 页眉
  header: any;
  /**
   * 顶部工具栏
   */
  headerToolbar?: Array<
    (CRUDToolbarChild & CRUDToolbarObject) | CRUDBultinToolbarType
  >;

  /**
   * 底部工具栏
   */
  footerToolbar?: Array<
    (CRUDToolbarChild & CRUDToolbarObject) | CRUDBultinToolbarType
  >;

  /**
   * 每页显示多少个空间成员的配置如： [10, 20, 50, 100]。
   */
  perPageAvailable?: Array<number>;

  messages?: SchemaMessage;

  /**
   * 是否隐藏快速编辑的按钮。
   */
  hideQuickSaveBtn?: boolean;

  /**
   * 是否自动跳顶部，当切分页的时候。
   */
  autoJumpToTopOnPagerChange?: boolean;


  filterTogglable?: boolean;
  filterDefaultVisible?: boolean;

  /**
   * 是否将接口返回的内容自动同步到地址栏，前提是开启了同步地址栏。
   */
  syncResponse2Query?: boolean;

  /**
   * 分页的时候是否保留用户选择。
   */
  keepItemSelectionOnPageChange?: boolean;

  /**
   * 当配置 keepItemSelectionOnPageChange 时有用，用来配置已勾选项的文案。
   */
  labelTpl?: SchemaTpl;

  /**
   * 是否为前端单次加载模式，可以用来实现前端分页。
   */
  loadDataOnce?: boolean;

  /**
   * 在开启loadDataOnce时，filter时是否去重新请求api
   */
  loadDataOnceFetchOnFilter?: boolean;

  /**
   * 也可以直接从环境变量中读取，但是不太推荐。
   */
  source?: SchemaTokenizeableString;

  /**
   * 如果时内嵌模式，可以通过这个来配置默认的展开选项。
   */
  expandConfig?: {
    /**
     * 默认是展开第一个、所有、还是都不展开。
     */
    expand?: 'first' | 'all' | 'none';

    /**
     * 是否显示全部切换按钮
     */
    expandAll?: boolean;

    /**
     * 是否为手风琴模式
     */
    accordion?: boolean;
  };

  /**
   * 默认只有当分页数大于 1 是才显示，如果总是想显示请配置。
   */
  alwaysShowPagination?: boolean;

  /**
   * 开启查询区域，会根据列元素的searchable属性值，自动生成查询条件表单
   */
  autoGenerateFilter?: boolean;

  /**
   * 内容区域占满屏幕剩余空间
   */
  autoFillHeight?: boolean;

  /**
   * 无限加载
   */
  infinteLoad?: boolean;

  /**
   * 行勾选禁用表达式
   */
  itemCheckableOn?: string

  primaryField: string;
  // Jay
  // 保存列配置接口
  saveColApi?: SchemaApi;
  columnInfo?: Record<string, { index: number; hidden: number }>; // 列排序、隐藏配置

  // chencicsy
  setBorder?: boolean;
  preSortAble?: boolean;
  advancedFilter: any;
  tableLayout?: 'vertical' | 'horizontal';

  aggregate?: SchemaObject;
  /**
   * 配置高级查询可查询字段
   */

  advancedQueryFields?: string;

  /**
   * 高级查询弹窗类型
   * normal: 默认不弹窗且显示所有查询
   * popup-normal: 默认弹窗且显示所有查询
   * condition: 默认不弹窗且只显示条件查询
   * popup-condition: 默认弹窗且只显示条件查询
   */
  advancedMode?: 'normal' | 'popup-normal' | 'condition' | 'popup-condition'
  /**
  * 配置批量按钮全量数据获取数据
  */
  fullDataApi?: SchemaApi;
  /**
  * 为当前表单添加排序
  */
  showIndex?: boolean;
  //离线报文
  offlineSchema: {
    actions: Array<ActionSchema>,
    columns: any[],
    source: SchemaApi,
    offlinePageType: 'table' | 'detail',
    actionLabel?: {
      dataLabel?: string;
      codeLabel?: string;
    }
  };
  /**
   * 表格总结行位置
   * 0显示再表格最后一行，1显示在左下角底部工具栏位置，2都显示
   */
  affixRowPosition?: 0 | 1 | 2;
}

//  快速查询条件
export type filterTpl = {
  value?: string;
  label?: string;
  name?: string;
  labelName?: string;
  valuesAlia?: string;
  keyName?: string;
  advancedFilterIndex?: number
};

export type CRUDCardsSchema = CRUDCommonSchema & {
  mode: 'cards';
} & Omit<CardSchema, 'type'>;

export type CRUDListSchema = CRUDCommonSchema & {
  mode: 'list';
} & Omit<ListSchema, 'type'>;

export type CRUDTableSchema = CRUDCommonSchema & {
  mode?: 'table';
} & Omit<TableSchema, 'type'>;

export type CRUDSchema = CRUDCardsSchema | CRUDListSchema | CRUDTableSchema;

// 完整的类型定义
export interface CRUDProps extends RendererProps, Omit<CRUDCommonSchema, 'type' | 'className'> {
  store: ICRUDStore;
  aliasTitle: string;
  pickerMode?: boolean; // 选择模式，用做表单中的选择操作
  OnSelectedItems?: (items: any[]) => void;
  getTableInstance?: (tableInstance: any) => void;
  isStatic?: boolean;//是否是统计
}

export type TableMode = 'table' | 'grid' | 'cards' | /* grid 的别名*/ 'list' | 'cross';
export type PrintType = "html" | "label" | "bill" | "file" | 'report' | undefined;


export interface CRUDState {
  printType: PrintType,
  currentSelectedRow: number,
  flowModalVisible: boolean
  fingerModalVisible: boolean
  showColumnsFilter: boolean
  filterDrawerVisible: boolean
  useMobileUI: boolean,
  offlineMode: boolean,
  mobileFilterShow: boolean,
  hasFetch: boolean, // Jay 标记是否发送过请求
  ModalProps: any,
  filterData: obj,
  flowModalProps: obj,//流程数据传递下一层
  advancedFilterVisible: boolean,
  multipleDefault: string,
  defaultVisible: boolean,
  selectTmpShow: boolean,
  defaultList: any[]
  defaultTempKey: string,
  defaultTempValue: string
  foldColumns: Array<string>, //折叠的操作列
  filtercont: obj, //获取高级查询中的数据，上层获取不到储存到这里
  filterOptions: obj, //只是文字写入，将上层数据导入到高级查询数据中
  filtertpl: Array<filterTpl>, //高级查询展示在form中的内容
  filterExist: boolean,//在移动端判断筛选按钮是否高亮判断基础查询是否有默认值，仅首次加载有效
  filData: obj,//body查询
  transferSubmission: obj, //储存表单送签信息
  tableRotate: boolean, //移动端表格横屏模式
  offline: boolean,  //是否离线
  offlineColumns: Array<obj>,//离线表格的列集
  offlineData: Array<obj>,//离线数据集
  offlineFormShow: boolean,//离线表格
  currentRow: obj | null,//当前行数据
  position: { x: number, y: number },//扫码按钮位置
  offlineLoading: boolean,//离线loading
  offlineTemplist: Array<string>,//离线脏数据
  offlineProgress: number,//离线进度条
  offlineStatus: boolean,//离线上传下载状态
  openModle: {
    open?: boolean,
    width?: string,
    openModleBody?: any,
    linkTitle?: string,
    bodydata?: any
  },
  codeVisible: boolean;
  codeValue: string;
  advancedFilterAction: boolean;//控制移动端查询条件当中的按钮展示
  formSwitch: boolean;//头部展示开关按钮
  templateSwitch: boolean;//新增模板开关按钮
  toolActionSwitch: boolean;//工具栏按钮开关按钮
  staticExportShow: boolean;//二次加工工具导出面板显隐
  showFilterTimer: string | number | undefined
  staticExportRange: '0' | '1' | '2';//二次加工工具导出范围
  keepDataFormat: '0' | '1';
}





