/*
 * @Author: 赵伟
 * @Date: 2024-04-16 13:58:08
 * @Description: 镜像详情
 */
import KFIcon from '@/components/KFIcon';
import PageTitle from '@/components/PageTitle';
import SubAreaTitle from '@/components/SubAreaTitle';
import { MirrorVersionStatus } from '@/enums';
import { useCacheState } from '@/hooks/useCacheState';
import { useDomSize } from '@/hooks/useDomSize';
import {
  deleteMirrorVersionReq,
  getMirrorInfoReq,
  getMirrorVersionListReq,
} from '@/services/mirror';
import themes from '@/styles/theme.less';
import { formatDate } from '@/utils/date';
import { safeInvoke } from '@/utils/functional';
import { to } from '@/utils/promise';
import SessionStorage from '@/utils/sessionStorage';
import tableCellRender, { TableCellValueType } from '@/utils/table';
import { modalConfirm } from '@/utils/ui';
import { useNavigate, useParams } from '@umijs/max';
import {
  App,
  Button,
  Col,
  ConfigProvider,
  Flex,
  Row,
  Table,
  type TablePaginationConfig,
  type TableProps,
} from 'antd';
import { useCallback, useEffect, useMemo, useState } from 'react';
import MirrorStatusCell from '../components/MirrorStatusCell';
import styles from './index.less';

export type MirrorInfoData = {
  name?: string;
  description?: string;
  version_count?: string;
  create_time?: string;
  image_type?: number;
};

export type MirrorVersionData = {
  id: number;
  version: string;
  url: string;
  status: MirrorVersionStatus;
  file_size: string;
  create_time: string;
  tag_name: string;
};

function MirrorInfo() {
  const navigate = useNavigate();
  const urlParams = useParams();
  const [cacheState, setCacheState] = useCacheState();
  const [mirrorInfo, setMirrorInfo] = useState<MirrorInfoData>({});
  const [tableData, setTableData] = useState<MirrorVersionData[]>([]);
  const [topRef, { height: topHeight }] = useDomSize<HTMLDivElement>(0, 0, [mirrorInfo]);
  const [total, setTotal] = useState(0);
  const [pagination, setPagination] = useState<TablePaginationConfig>(
    cacheState?.pagination ?? {
      current: 1,
      pageSize: 10,
    },
  );
  const { message } = App.useApp();
  const isPublic = useMemo(() => mirrorInfo.image_type === 1, [mirrorInfo]);
  const mirrorId = safeInvoke(Number)(urlParams.id);

  // 获取镜像详情
  const getMirrorInfo = useCallback(async () => {
    if (!mirrorId) {
      return;
    }
    const [res] = await to(getMirrorInfoReq(mirrorId));
    if (res && res.data) {
      setMirrorInfo(res.data);
    }
  }, [mirrorId]);

  // 获取镜像版本列表
  const getMirrorVersionList = useCallback(async () => {
    if (!mirrorId) {
      return;
    }
    const params = {
      page: pagination.current! - 1,
      size: pagination.pageSize,
      image_id: mirrorId,
    };
    const [res] = await to(getMirrorVersionListReq(params));
    if (res && res.data) {
      const { content = [], totalElements = 0 } = res.data;
      setTableData(content);
      setTotal(totalElements);
    }
  }, [mirrorId, pagination]);

  // 获取镜像详情
  useEffect(() => {
    getMirrorInfo();
  }, [getMirrorInfo]);

  // 获取镜像版本列表
  useEffect(() => {
    getMirrorVersionList();
  }, [getMirrorVersionList]);

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

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

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

  const createMirrorVersion = () => {
    navigate(`add-version`);
    SessionStorage.setItem(SessionStorage.mirrorNameKey, mirrorInfo.name || '');
    setCacheState({
      pagination,
    });
  };

  const columns: TableProps<MirrorVersionData>['columns'] = [
    {
      title: '镜像版本',
      dataIndex: 'tag_name',
      key: 'tag_name',
      width: '30%',
      render: tableCellRender(),
    },
    {
      title: '镜像地址',
      dataIndex: 'url',
      key: 'url',
      width: '40%',
      render: tableCellRender('auto', TableCellValueType.Text, { copyable: true }),
    },
    {
      title: '版本描述',
      dataIndex: 'description',
      key: 'description',
      width: '30%',
      render: tableCellRender(true),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: MirrorStatusCell,
    },
    {
      title: '镜像大小',
      dataIndex: 'file_size',
      key: 'file_size',
      width: 120,
      render: tableCellRender(),
    },
    {
      title: '创建时间',
      dataIndex: 'create_time',
      key: 'create_time',
      width: 200,
      render: tableCellRender(false, TableCellValueType.Date),
    },
    {
      title: '操作',
      dataIndex: 'operation',
      width: 120,
      key: 'operation',
      hidden: isPublic,
      render: (_: any, record: MirrorVersionData) => (
        <div>
          {!isPublic && record.status && record.status !== MirrorVersionStatus.Building && (
            <ConfigProvider
              theme={{
                token: {
                  colorLink: themes['warningColor'],
                },
              }}
            >
              <Button
                type="link"
                size="small"
                key="remove"
                icon={<KFIcon type="icon-shanchu" />}
                onClick={() => handleVersionDelete(record)}
              >
                删除
              </Button>
            </ConfigProvider>
          )}
        </div>
      ),
    },
  ];

  return (
    <div className={styles['mirror-info']}>
      <PageTitle title="镜像详情"></PageTitle>
      <div className={styles['mirror-info__content']}>
        <div ref={topRef}>
          <SubAreaTitle
            title="基本信息"
            image={require('@/assets/img/mirror-basic.png')}
            style={{ marginBottom: '26px' }}
          ></SubAreaTitle>
          <div className={styles['mirror-info__basic']}>
            <Row gutter={40} style={{ marginBottom: '20px' }}>
              <Col span={10}>
                <div className={styles['mirror-info__basic__item']}>
                  <div className={styles['label']}>镜像名称：</div>
                  <div className={styles['value']}>{mirrorInfo.name}</div>
                </div>
              </Col>
              <Col span={10}>
                <div className={styles['mirror-info__basic__item']}>
                  <div className={styles['label']}>版本数：</div>
                  <div className={styles['value']}>{mirrorInfo.version_count ?? '--'}</div>
                </div>
              </Col>
            </Row>
            <Row gutter={40}>
              <Col span={10}>
                <div className={styles['mirror-info__basic__item']}>
                  <div className={styles['label']}>镜像描述：</div>
                  <div className={styles['value']}>{mirrorInfo.description}</div>
                </div>
              </Col>
              <Col span={10}>
                <div className={styles['mirror-info__basic__item']}>
                  <div className={styles['label']}>创建时间：</div>
                  <div className={styles['value']}>{formatDate(mirrorInfo.create_time)}</div>
                </div>
              </Col>
            </Row>
          </div>
          <Flex justify="flex-start" align="center" style={{ marginTop: '40px' }}>
            <SubAreaTitle
              title="镜像版本"
              image={require('@/assets/img/mirror-version.png')}
            ></SubAreaTitle>
            {!isPublic && (
              <Button
                style={{ marginLeft: 'auto' }}
                type="default"
                onClick={createMirrorVersion}
                icon={<KFIcon type="icon-xinjian2" />}
              >
                新增镜像版本
              </Button>
            )}
            <Button
              style={{ marginLeft: isPublic ? 'auto' : '20px', marginRight: 0 }}
              type="default"
              onClick={getMirrorVersionList}
              icon={<KFIcon type="icon-shuaxin" />}
            >
              刷新
            </Button>
          </Flex>
        </div>
        <div
          className="vertical-scroll-table"
          style={{ marginTop: '24px', height: `calc(100% - ${topHeight + 24}px)` }}
        >
          <Table
            dataSource={tableData}
            columns={columns}
            scroll={{ y: 'calc(100% - 55px)' }}
            pagination={{
              ...pagination,
              total,
              showSizeChanger: true,
              showQuickJumper: true,
              showTotal: () => `共${total}条`,
            }}
            onChange={handleTableChange}
            rowKey="id"
          />
        </div>
      </div>
    </div>
  );
}

export default MirrorInfo;
