import KFIcon from '@/components/KFIcon';
import { CommonTabKeys } from '@/enums';
import AddModelModal from '@/pages/Dataset/components/AddModelModal';
import { openAntdModal } from '@/utils/modal';
import { to } from '@/utils/promise';
import { modalConfirm } from '@/utils/ui';
import { useNavigate } from '@umijs/max';
import { App, Button, Input, Pagination, PaginationProps } from 'antd';
import { Ref, forwardRef, useEffect, useImperativeHandle, useState } from 'react';
import { CategoryData, ResourceData, ResourceType, resourceConfig } from '../../config';
import AddDatasetModal from '../AddDatasetModal';
import ResourceItem from '../Resourcetem';
import styles from './index.less';

export type ResourceListRef = {
  reset: () => void;
};

type ResourceListProps = {
  resourceType: ResourceType;
  dataType?: number;
  dataTag?: number;
  isPublic: boolean;
  typeList: CategoryData[];
  tagList: CategoryData[];
  initialSearchText?: string;
  initialPagination?: PaginationProps;
  setCacheState: (state?: any) => void;
};

function ResourceList(
  {
    resourceType,
    dataType,
    dataTag,
    typeList,
    tagList,
    isPublic,
    initialSearchText,
    initialPagination,
    setCacheState,
  }: ResourceListProps,
  ref: Ref<ResourceListRef>,
) {
  const navigate = useNavigate();
  const [dataList, setDataList] = useState<ResourceData[]>([]);
  const [total, setTotal] = useState(0);
  const [pagination, setPagination] = useState<PaginationProps>(
    initialPagination ?? {
      current: 1,
      pageSize: 20,
    },
  );
  const [searchText, setSearchText] = useState(initialSearchText);
  const [inputText, setInputText] = useState(initialSearchText);
  const { message } = App.useApp();
  const config = resourceConfig[resourceType];

  useEffect(() => {
    getDataList();
  }, [resourceType, dataType, dataTag, pagination, searchText, isPublic]);

  useImperativeHandle(
    ref,
    () => {
      return {
        reset: () => {
          setPagination({
            current: 1,
            pageSize: 20,
          });
          setSearchText('');
          setInputText('');
          setDataList([]);
        },
      };
    },
    [],
  );

  // 获取数据请求
  const getDataList = async () => {
    const params = {
      page: pagination.current! - 1,
      size: pagination.pageSize,
      [config.typeParamKey]: dataType,
      [config.tagParamKey]: dataTag,
      available_range: isPublic ? 1 : 0,
      name: searchText !== '' ? searchText : undefined,
    };
    const request = config.getList;
    const [res] = await to(request(params));
    if (res && res.data && res.data.content) {
      setDataList(res.data.content);
      setTotal(res.data.totalElements);
    }
  };

  // 删除请求
  const deleteRecord = async (id: number) => {
    const request = config.deleteRecord;
    const [res] = await to(request(id));
    if (res) {
      getDataList();
      message.success('删除成功');
    }
  };

  // 搜索
  const handleSearch = (value: string) => {
    setSearchText(value);
  };

  // 删除
  const handleRemove = (record: ResourceData) => {
    modalConfirm({
      title: config.deleteModalTitle,
      onOk: () => {
        deleteRecord(record.id);
      },
    });
  };

  // 跳转
  const handleClick = (record: ResourceData) => {
    setCacheState({
      activeTab: isPublic ? CommonTabKeys.Public : CommonTabKeys.Private,
      pagination,
      searchText,
      activeType: dataType,
      activeTag: dataTag,
    });
    const prefix = config.prefix;
    navigate(`/dataset/${prefix}/${record.id}`);
  };

  // 分页切换
  const handlePageChange: PaginationProps['onChange'] = (page, pageSize) => {
    setPagination({
      current: page,
      pageSize: pageSize,
    });
  };

  // 新建弹框
  const showModal = () => {
    const Modal = resourceType === ResourceType.Dataset ? AddDatasetModal : AddModelModal;
    const { close } = openAntdModal(Modal, {
      typeList: typeList,
      tagList: tagList,
      onOk: () => {
        getDataList();
        close();
      },
    });
  };

  return (
    <div className={styles['resource-list']}>
      <div className={styles['resource-list__header']}>
        <span>数据总数：{total}个</span>
        <div>
          <Input.Search
            placeholder="按数据名称筛选"
            allowClear
            onSearch={handleSearch}
            style={{
              width: 300,
            }}
            onChange={(e) => setInputText(e.target.value)}
            value={inputText}
          />
          {!isPublic && (
            <Button
              type="default"
              style={{ marginLeft: '20px' }}
              onClick={showModal}
              icon={<KFIcon type="icon-xinjian2" />}
            >
              {config.addBtnTitle}
            </Button>
          )}
        </div>
      </div>
      <div className={styles['resource-list__content']}>
        {dataList?.map((item) => (
          <ResourceItem
            item={item}
            key={item.id}
            isPublic={isPublic}
            onRemove={handleRemove}
            onClick={handleClick}
          ></ResourceItem>
        ))}
      </div>
      <Pagination
        total={total}
        showSizeChanger
        defaultPageSize={20}
        pageSizeOptions={[20, 40, 60, 80, 100]}
        showQuickJumper
        onChange={handlePageChange}
        {...pagination}
      />
    </div>
  );
}

export default forwardRef(ResourceList);
