/*
 * @Author: 赵伟
 * @Date: 2024-04-16 13:58:08
 * @Description: 开发环境列表
 */

import KFIcon from '@/components/KFIcon';
import { DevEditorStatus } from '@/enums';
import { useCacheState } from '@/hooks/useCacheState';
import { useComputingResource } from '@/hooks/useComputingResource';
import { DatasetData, ModelData } from '@/pages/Dataset/config';
import {
  deleteEditorReq,
  getEditorListReq,
  startEditorReq,
  stopEditorReq,
} from '@/services/developmentEnvironment';
import themes from '@/styles/theme.less';
import { parseJsonText } from '@/utils';
import { openAntdModal } from '@/utils/modal';
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,
  Table,
  type TablePaginationConfig,
  type TableProps,
} from 'antd';
import classNames from 'classnames';
import { useCallback, useEffect, useState } from 'react';
import CreateMirrorModal from '../components/CreateMirrorModal';
import EditorStatusCell from '../components/EditorStatusCell';
import styles from './index.less';

export type EditorData = {
  id: number;
  name: string;
  status: string;
  computing_resource: string;
  update_by: string;
  create_time: string;
  url: string;
  computing_resource_id: number;
  dataset?: string | DatasetData;
  model?: string | ModelData;
  image?: string;
};

function EditorList() {
  const navigate = useNavigate();
  const [cacheState, setCacheState] = useCacheState();
  const { message } = App.useApp();
  const [tableData, setTableData] = useState<EditorData[]>([]);
  const [total, setTotal] = useState(0);
  const [pagination, setPagination] = useState<TablePaginationConfig>(
    cacheState?.pagination ?? {
      current: 1,
      pageSize: 10,
    },
  );
  const getResourceDescription = useComputingResource()[1];

  // 获取编辑器列表
  const getEditorList = useCallback(async () => {
    const params: Record<string, any> = {
      page: pagination.current! - 1,
      size: pagination.pageSize,
    };
    const [res] = await to(getEditorListReq(params));
    if (res && res.data) {
      const { content = [], totalElements = 0 } = res.data;
      content.forEach((item: EditorData) => {
        item.dataset = typeof item.dataset === 'string' ? parseJsonText(item.dataset) : null;
        item.model = typeof item.model === 'string' ? parseJsonText(item.model) : null;
        item.image = typeof item.image === 'string' ? parseJsonText(item.image) : null;
      });
      setTableData(content);
      setTotal(totalElements);
    }
  }, [pagination]);

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

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

  // 启动编辑器
  const startEditor = async (id: number) => {
    const [res] = await to(startEditorReq(id));
    if (res) {
      message.success('操作成功');
      getEditorList();
    }
  };

  // 停止编辑器
  const stopEditor = async (id: number) => {
    modalConfirm({
      title: '停止后，该编辑器将不可使用',
      content: '是否确认停止?',
      isDelete: false,
      onOk: async () => {
        const [res] = await to(stopEditorReq(id));
        if (res) {
          message.success('操作成功');
          getEditorList();
        }
      },
    });
  };

  // 制作镜像
  const createMirror = (id: number) => {
    const { close } = openAntdModal(CreateMirrorModal, {
      envId: id,
      onOk: () => {
        close();
      },
    });
  };

  // 处理删除
  const handleEditorDelete = (record: EditorData) => {
    modalConfirm({
      title: '删除后，该编辑器将不可恢复',
      content: '是否确认删除?',
      onOk: () => {
        deleteEditor(record.id);
      },
    });
  };

  // 创建编辑器
  const createEditor = () => {
    navigate(`/developmentEnvironment/create`);
    setCacheState({
      pagination,
    });
  };

  // 跳转编辑器页面
  const gotoEditorPage = (e: React.MouseEvent, record: EditorData) => {
    e.stopPropagation();
    SessionStorage.setItem(SessionStorage.editorUrlKey, record.url);
    navigate(`/developmentEnvironment/editor`);
    setCacheState({
      pagination,
    });
  };

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

  const columns: TableProps<EditorData>['columns'] = [
    {
      title: '编辑器名称',
      dataIndex: 'name',
      key: 'name',
      width: '16%',
      render: (text, record, index) =>
        record.url && record.status === DevEditorStatus.Running
          ? tableCellRender<EditorData>(true, TableCellValueType.Link, {
              onClick: (record, e) => gotoEditorPage(e, record),
            })(text, record, index)
          : tableCellRender<EditorData>(true, TableCellValueType.Text)(text, record, index),
    },
    {
      title: '计算资源',
      dataIndex: 'computing_resource',
      key: 'computing_resource',
      width: '12%',
      render: tableCellRender(),
    },
    {
      title: '资源规格',
      dataIndex: 'computing_resource_id',
      key: 'computing_resource_id',
      width: '12%',
      render: tableCellRender(true, TableCellValueType.Custom, {
        format: getResourceDescription,
      }),
    },
    {
      title: '数据集',
      dataIndex: ['dataset', 'showValue'],
      key: 'dataset',
      width: '12%',
      render: tableCellRender(true),
    },
    {
      title: '模型',
      dataIndex: ['model', 'showValue'],
      key: 'model',
      width: '12%',
      render: tableCellRender(true),
    },
    {
      title: '镜像',
      dataIndex: ['image', 'showValue'],
      key: 'image',
      width: '12%',
      render: tableCellRender(true),
    },
    {
      title: '创建者',
      dataIndex: 'update_by',
      key: 'update_by',
      width: '12%',
      render: tableCellRender(true),
    },
    {
      title: '创建时间',
      dataIndex: 'create_time',
      key: 'create_time',
      width: '12%',
      render: tableCellRender(true, TableCellValueType.Date),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 80,
      render: EditorStatusCell,
    },
    {
      title: '操作',
      dataIndex: 'operation',
      width: 270,
      key: 'operation',
      render: (_: any, record: EditorData) => (
        <div>
          {record.status === DevEditorStatus.Pending ||
          record.status === DevEditorStatus.Running ? (
            <Button
              type="link"
              size="small"
              key="stop"
              icon={<KFIcon type="icon-tingzhi" />}
              onClick={() => stopEditor(record.id)}
            >
              停止
            </Button>
          ) : (
            <Button
              type="link"
              size="small"
              key="debug"
              icon={<KFIcon type="icon-tiaoshi" />}
              onClick={() => startEditor(record.id)}
            >
              启动
            </Button>
          )}
          {record.status !== DevEditorStatus.Running ? (
            <Button
              type="link"
              size="small"
              key="jingxiang"
              icon={<KFIcon type="icon-jingxiang" />}
              onClick={() => createMirror(record.id)}
            >
              制作镜像
            </Button>
          ) : null}
          <ConfigProvider
            theme={{
              token: {
                colorLink: themes['warningColor'],
              },
            }}
          >
            <Button
              type="link"
              size="small"
              key="remove"
              icon={<KFIcon type="icon-shanchu" />}
              onClick={() => handleEditorDelete(record)}
            >
              删除
            </Button>
          </ConfigProvider>
        </div>
      ),
    },
  ];

  return (
    <div className={styles['develop-env']}>
      <div className={styles['develop-env__header']}>
        <Button
          style={{ marginLeft: '20px' }}
          type="default"
          onClick={createEditor}
          icon={<KFIcon type="icon-xinjian2" />}
        >
          创建开发环境
        </Button>
        <Button
          style={{ marginLeft: '20px' }}
          type="default"
          onClick={getEditorList}
          icon={<KFIcon type="icon-shuaxin" />}
        >
          刷新
        </Button>
      </div>
      <div className={classNames('vertical-scroll-table', styles['develop-env__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>
  );
}

export default EditorList;
