/*
 * @Author: 赵伟
 * @Date: 2024-04-16 13:58:08
 * @Description: 镜像列表
 */
import KFIcon from '@/components/KFIcon';
import { CommonTabKeys } from '@/enums';
import { useCacheState } from '@/hooks/useCacheState';
import { deleteMirrorReq, getMirrorListReq } from '@/services/mirror';
import themes from '@/styles/theme.less';
import { to } from '@/utils/promise';
import SessionStorage from '@/utils/sessionStorage';
import tableCellRender, { TableCellValueType } from '@/utils/table';
import { modalConfirm } from '@/utils/ui';
import { useNavigate } from '@umijs/max';
import {
  App,
  Button,
  ConfigProvider,
  Input,
  Table,
  Tabs,
  type TablePaginationConfig,
  type TableProps,
  type TabsProps,
} from 'antd';
import { type SearchProps } from 'antd/es/input';
import classNames from 'classnames';
import { useCallback, useEffect, useState } from 'react';
import styles from './index.less';

const mirrorTabItems = [
  {
    key: CommonTabKeys.Public,
    label: '公共镜像',
    icon: <KFIcon type="icon-gonggongjingxiang" />,
  },
  {
    key: CommonTabKeys.Private,
    label: '个人镜像',
    icon: <KFIcon type="icon-zidingyijingxiang" />,
  },
];

export type MirrorData = {
  id: number;
  name: string;
  description: string;
  create_time: string;
};

function MirrorList() {
  const navigate = useNavigate();
  const [cacheState, setCacheState] = useCacheState();
  const [activeTab, setActiveTab] = useState<string>(cacheState?.activeTab ?? CommonTabKeys.Public);
  const [searchText, setSearchText] = useState(cacheState?.searchText);
  const [inputText, setInputText] = useState(cacheState?.searchText);
  const [tableData, setTableData] = useState<MirrorData[]>([]);
  const [total, setTotal] = useState(0);
  const [pagination, setPagination] = useState<TablePaginationConfig>(
    cacheState?.pagination ?? {
      current: 1,
      pageSize: 10,
    },
  );
  const { message } = App.useApp();

  // 获取镜像列表
  const getMirrorList = useCallback(async () => {
    const params: Record<string, any> = {
      page: pagination.current! - 1,
      size: pagination.pageSize,
      name: searchText || undefined,
      image_type: activeTab === CommonTabKeys.Public ? 1 : 0,
    };
    const [res] = await to(getMirrorListReq(params));
    if (res && res.data) {
      const { content = [], totalElements = 0 } = res.data;
      setTableData(content);
      setTotal(totalElements);
    }
  }, [activeTab, pagination, searchText]);

  useEffect(() => {
    getMirrorList();
  }, [getMirrorList]);

  // 切换 Tab，重置数据
  const hanleTabChange: TabsProps['onChange'] = (value) => {
    setSearchText('');
    setInputText('');
    setPagination({
      current: 1,
      pageSize: 10,
    });
    setTotal(0);
    setTableData([]);
    setActiveTab(value);
  };

  // 删除镜像
  const deleteMirror = async (id: number) => {
    const [res] = await to(deleteMirrorReq(id));
    if (res) {
      message.success('删除成功');
      // 如果是一页的唯一数据，删除后，请求第一页的数据
      // 否则直接刷新这一页的数据
      setPagination((prev) => {
        return {
          ...prev,
          current: tableData.length === 1 ? Math.max(1, prev.current! - 1) : prev.current,
        };
      });
    }
  };

  // 搜索
  const onSearch: SearchProps['onSearch'] = (value) => {
    setSearchText(value);
    setPagination((prev) => ({
      ...prev,
      current: 1,
    }));
  };

  // 查看详情
  const toDetail = (record: MirrorData) => {
    navigate(`info/${record.id}`);
    setCacheState({
      activeTab,
      pagination,
      searchText,
    });
  };

  // 处理删除
  const handleMirrorDelete = (record: MirrorData) => {
    modalConfirm({
      title: '删除后，该镜像将不可恢复',
      content: '是否确认删除?',
      onOk: () => {
        deleteMirror(record.id);
      },
    });
  };

  // 创建镜像
  const createMirror = () => {
    navigate(`create`);
    SessionStorage.setItem(SessionStorage.mirrorNameKey, '');
    setCacheState({
      activeTab,
      pagination,
      searchText,
    });
  };

  // 分页切换
  const handleTableChange: TableProps<MirrorData>['onChange'] = (
    pagination,
    _filters,
    _sorter,
    { action },
  ) => {
    if (action === 'paginate') {
      setPagination(pagination);
    }
    // console.log(pagination, filters, sorter, action);
  };

  const columns: TableProps<MirrorData>['columns'] = [
    {
      title: '镜像名称',
      dataIndex: 'name',
      key: 'name',
      width: '30%',
      render: tableCellRender(),
    },
    {
      title: '版本数据',
      dataIndex: 'version_count',
      key: 'version_count',
      width: '15%',
      render: tableCellRender(),
    },
    {
      title: '镜像描述',
      dataIndex: 'description',
      key: 'description',
      width: '35%',
      render: tableCellRender(true),
    },
    {
      title: '创建时间',
      dataIndex: 'create_time',
      key: 'create_time',
      width: '20%',
      render: tableCellRender(false, TableCellValueType.Date),
    },
    {
      title: '操作',
      dataIndex: 'operation',
      width: activeTab === CommonTabKeys.Private ? 200 : 150,
      key: 'operation',
      render: (_: any, record: MirrorData) => (
        <div>
          <Button
            type="link"
            size="small"
            key="info"
            icon={<KFIcon type="icon-chakanxiangqing" />}
            onClick={() => toDetail(record)}
          >
            查看详情
          </Button>
          {activeTab === CommonTabKeys.Private && (
            <ConfigProvider
              theme={{
                token: {
                  colorLink: themes['warningColor'],
                },
              }}
            >
              <Button
                type="link"
                size="small"
                key="remove"
                icon={<KFIcon type="icon-shanchu" />}
                onClick={() => handleMirrorDelete(record)}
              >
                删除
              </Button>
            </ConfigProvider>
          )}
        </div>
      ),
    },
  ];

  return (
    <div className={styles['mirror-list']}>
      <div className={styles['mirror-list__tabs-container']}>
        <Tabs activeKey={activeTab} items={mirrorTabItems} onChange={hanleTabChange} />
      </div>
      <div className={styles['mirror-list__content']}>
        <div className={styles['mirror-list__content__filter']}>
          <Input.Search
            placeholder="按镜像名称筛选"
            allowClear
            onSearch={onSearch}
            onChange={(e) => setInputText(e.target.value)}
            style={{ width: 300 }}
            value={inputText}
          />
          {activeTab === CommonTabKeys.Private && (
            <Button
              style={{ marginLeft: '20px' }}
              type="default"
              onClick={createMirror}
              icon={<KFIcon type="icon-xinjian2" />}
            >
              创建镜像
            </Button>
          )}
          <Button
            style={{ marginRight: 0, marginLeft: 'auto' }}
            type="default"
            onClick={getMirrorList}
            icon={<KFIcon type="icon-shuaxin" />}
          >
            刷新
          </Button>
        </div>
        <div className={classNames('vertical-scroll-table', styles['mirror-list__content__table'])}>
          <Table
            dataSource={tableData}
            columns={columns}
            scroll={{ y: 'calc(100% - 55px)' }}
            pagination={{
              ...pagination,
              total: total,
              showSizeChanger: true,
              showQuickJumper: true,
              showTotal: () => `共${total}条`,
            }}
            onChange={handleTableChange}
            rowKey="id"
          />
        </div>
      </div>
    </div>
  );
}

export default MirrorList;
