/*
 * @Author: 赵伟
 * @Date: 2024-04-16 13:58:08
 * @Description: 模型部署服务列表
 */
import KFIcon from '@/components/KFIcon';
import PageTitle from '@/components/PageTitle';
import { serviceTypeOptions } from '@/enums';
import { useCacheState } from '@/hooks/useCacheState';
import { deleteServiceReq, getServiceListReq } from '@/services/modelDeployment';
import themes from '@/styles/theme.less';
import { ServiceCreatedMessage } from '@/utils/constant';
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,
  Select,
  Table,
  type TablePaginationConfig,
  type TableProps,
} from 'antd';
import { type SearchProps } from 'antd/es/input';
import classNames from 'classnames';
import { useCallback, useEffect, useState } from 'react';
import { CreateServiceVersionFrom, ServiceData, ServiceOperationType } from '../types';
import styles from './index.less';

const allServiceTypeOptions = [{ label: '全部', value: '' }, ...serviceTypeOptions];

function ModelDeployment() {
  const navigate = useNavigate();
  const { message } = App.useApp();
  const [cacheState, setCacheState] = useCacheState();
  const [serviceType, setServiceType] = useState(cacheState?.serviceType ?? '');
  const [searchText, setSearchText] = useState(cacheState?.searchText);
  const [inputText, setInputText] = useState(cacheState?.searchText);
  const [tableData, setTableData] = useState<ServiceData[]>([]);
  const [total, setTotal] = useState(0);
  const [pagination, setPagination] = useState<TablePaginationConfig>(
    cacheState?.pagination ?? {
      current: 1,
      pageSize: 10,
    },
  );

  // 获取模型部署服务列表
  const getServiceList = useCallback(async () => {
    const params: Record<string, any> = {
      page: pagination.current! - 1,
      size: pagination.pageSize,
      service_name: searchText || undefined,
      service_type: serviceType,
    };
    const [res] = await to(getServiceListReq(params));
    if (res && res.data) {
      const { content = [], totalElements = 0 } = res.data;
      setTableData(content);
      setTotal(totalElements);
    }
  }, [pagination, searchText, serviceType]);

  // 去创建服务版本
  const gotoCreateServiceVersion = useCallback(
    (serviceId: number) => {
      SessionStorage.setItem(
        SessionStorage.serviceVersionInfoKey,
        {
          operationType: ServiceOperationType.Create,
          lastPage: CreateServiceVersionFrom.CreateService,
        },
        true,
      );

      navigate(`serviceInfo/${serviceId}/createVersion`);
    },
    [navigate],
  );

  // 获取模型部署服务列表
  useEffect(() => {
    getServiceList();
  }, [getServiceList]);

  // 接收创建服务成功的消息
  useEffect(() => {
    const handleMessage = (e: MessageEvent) => {
      const { type, payload } = e.data;
      if (type === ServiceCreatedMessage) {
        modalConfirm({
          title: '创建服务成功',
          content: '是否创建服务版本?',
          isDelete: false,
          cancelText: '稍后创建',
          onOk: () => {
            gotoCreateServiceVersion(payload);
          },
        });
      }
    };

    window.addEventListener('message', handleMessage);
    return () => {
      window.removeEventListener('message', handleMessage);
    };
  }, [gotoCreateServiceVersion]);

  // 删除模型部署
  const deleteService = async (record: ServiceData) => {
    const [res] = await to(deleteServiceReq(record.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 handleServiceDelete = (record: ServiceData) => {
    modalConfirm({
      title: '删除后，该服务将不可恢复',
      content: '是否确认删除?',
      onOk: () => {
        deleteService(record);
      },
    });
  };

  // 创建、更新服务
  const createService = (record?: ServiceData) => {
    setCacheState({
      pagination,
      searchText,
      serviceType: serviceType,
    });

    if (record) {
      navigate(`editService/${record.id}`);
    } else {
      navigate('createService');
    }
  };

  // 查看详情
  const toDetail = (record: ServiceData) => {
    setCacheState({
      pagination,
      searchText,
      serviceType: serviceType,
    });

    navigate(`serviceInfo/${record.id}`);
  };

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

  const columns: TableProps<ServiceData>['columns'] = [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      width: '20%',
      render: tableCellRender(false, TableCellValueType.Index, {
        page: pagination.current! - 1,
        pageSize: pagination.pageSize!,
      }),
    },
    {
      title: '服务名称',
      dataIndex: 'service_name',
      key: 'service_name',
      width: '20%',
      render: tableCellRender(false, TableCellValueType.Link, {
        onClick: toDetail,
      }),
    },
    {
      title: '服务类型',
      dataIndex: 'service_type_name',
      key: 'service_type_name',
      width: '20%',
      render: tableCellRender(),
    },
    {
      title: '版本数量',
      dataIndex: 'version_count',
      key: 'version_count',
      width: '20%',
      render: tableCellRender(),
    },
    {
      title: '服务描述',
      dataIndex: 'description',
      key: 'description',
      render: tableCellRender(),
      width: '20%',
    },
    {
      title: '更新时间',
      dataIndex: 'update_time',
      key: 'update_time',
      width: '20%',
      render: tableCellRender(false, TableCellValueType.Date),
    },
    {
      title: '操作',
      dataIndex: 'operation',
      width: 300,
      key: 'operation',
      render: (_: any, record: ServiceData) => (
        <div>
          <Button
            type="link"
            size="small"
            key="edit"
            icon={<KFIcon type="icon-bianji" />}
            onClick={() => createService(record)}
          >
            编辑
          </Button>
          <Button
            type="link"
            size="small"
            key="run"
            icon={<KFIcon type="icon-xiangqing" />}
            onClick={() => toDetail(record)}
          >
            查看详情
          </Button>
          <ConfigProvider
            theme={{
              token: {
                colorLink: themes['warningColor'],
              },
            }}
          >
            <Button
              type="link"
              size="small"
              key="remove"
              icon={<KFIcon type="icon-shanchu" />}
              onClick={() => handleServiceDelete(record)}
            >
              删除
            </Button>
          </ConfigProvider>
        </div>
      ),
    },
  ];

  return (
    <div className={styles['model-deployment']}>
      <PageTitle title="服务列表"></PageTitle>
      <div className={styles['model-deployment__content']}>
        <div className={styles['model-deployment__content__filter']}>
          <Input.Search
            placeholder="按服务名称筛选"
            onSearch={onSearch}
            onChange={(e) => setInputText(e.target.value)}
            style={{ width: 300 }}
            value={inputText}
            allowClear
          />
          <Select
            style={{ width: 100, marginLeft: '20px' }}
            placeholder="请选择"
            onChange={(value) => setServiceType(value ?? '')}
            options={allServiceTypeOptions}
            value={serviceType}
            allowClear
          ></Select>
          <Button
            style={{ marginLeft: 'auto', marginRight: '20px' }}
            type="default"
            onClick={() => createService()}
            icon={<KFIcon type="icon-xinjian2" />}
          >
            创建推理服务
          </Button>
        </div>
        <div
          className={classNames(
            'vertical-scroll-table',
            styles['model-deployment__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 ModelDeployment;
