/*
 * @Author: 赵伟
 * @Date: 2024-04-16 13:58:08
 * @Description: 模型部署服务列表
 */
import PageTitle from '@/components/PageTitle';
import { getPointsConsumptionReq, getPointsStatisticsReq } from '@/services/points';
import themes from '@/styles/theme.less';
import { to } from '@/utils/promise';
import statusTableCell from '@/utils/statusTableCell';
import tableCellRender, { TableCellValueType } from '@/utils/table';
import { Link } from '@umijs/max';
import { Table, type TablePaginationConfig, type TableProps } from 'antd';
import classNames from 'classnames';
import { useEffect, useState } from 'react';
import Statistics from './components/Statistics';
import styles from './index.less';

enum TaskType {
  DevEnvironment = 'dev_environment',
  Workflow = 'workflow',
  Ray = 'ray',
  Service = 'service',
  AutoML = 'machine_learn',
  ActiveLearn = 'active_learn',
}

const taskTypeOptions = [
  {
    value: TaskType.DevEnvironment,
    label: '开发环境',
  },
  {
    value: TaskType.Workflow,
    label: '实验',
  },
  {
    value: TaskType.Ray,
    label: '超参数自动寻优',
  },
  {
    value: TaskType.Service,
    label: '服务',
  },
  {
    value: TaskType.AutoML,
    label: '自动机器学习',
  },
  {
    value: TaskType.ActiveLearn,
    label: '主动学习',
  },
];

export type PointsData = {
  computing_resource_id: number;
  credit_per_hour: number; // 每小时消耗的积分
  deduce_credit: number;
  deduce_last_time: string;
  description: string;
  id: number;
  node_id: string;
  start_time: string;
  state: number;
  workflow_id?: number; // 流水线id
  task_id: number; // 实验id
  task_ins_id: number; // 实例id
  task_type: string;
  user_id: number;
  task_state: 0 | 1; // 任务是否被删除，0：删除
};

export type PointsStatistics = {
  deduceCredit: number;
  userCredit: number;
};

// 格式化任务
const formatTask = (value: string, record: PointsData) => {
  let url;
  switch (record.task_type) {
    case TaskType.DevEnvironment:
      url = `/developmentEnvironment`;
      break;
    case TaskType.Workflow:
      if (record.workflow_id && record.task_ins_id) {
        url = `/pipeline/experiment/instance/${record.workflow_id}/${record.task_ins_id}`;
      }
      break;
    case TaskType.Ray:
      if (record.task_id && record.task_ins_id) {
        url = `/pipeline/hyperparameter/instance/${record.task_id}/${record.task_ins_id}`;
      }
      break;
    case TaskType.AutoML:
      if (record.task_id && record.task_ins_id) {
        url = `/pipeline/automl/instance/${record.task_id}/${record.task_ins_id}`;
      }
      break;
    case TaskType.ActiveLearn:
      if (record.task_id && record.task_ins_id) {
        url = `/pipeline/active-learn/instance/${record.task_id}/${record.task_ins_id}`;
      }
      break;
    case TaskType.Service:
      if (record.task_id && record.task_ins_id) {
        url = `/dataset/modelDeployment/serviceInfo/${record.task_id}/versionInfo/${record.task_ins_id}`;
      }
      break;
    default:
      break;
  }

  if (url && record.task_state === 1) {
    return <Link to={url}>{value}</Link>;
  } else {
    return <span>{value}</span>;
  }
};

function PointsDetail() {
  const [tableData, setTableData] = useState<PointsData[]>([]);
  const [total, setTotal] = useState(0);
  const [statistics, setStatistics] = useState<PointsStatistics>();
  const [pagination, setPagination] = useState<TablePaginationConfig>({
    current: 1,
    pageSize: 10,
  });

  useEffect(() => {
    // 获取积分统计
    const getPointsStatistics = async () => {
      const [res] = await to(getPointsStatisticsReq());
      if (res && res.data) {
        setStatistics(res.data);
      }
    };

    getPointsStatistics();
  }, []);

  useEffect(() => {
    // 获取积分消费明细
    const getPointsConsumption = async () => {
      const params: Record<string, any> = {
        page: pagination.current! - 1,
        size: pagination.pageSize,
      };
      const [res] = await to(getPointsConsumptionReq(params));
      if (res && res.data) {
        const { content = [], totalElements = 0 } = res.data;
        setTableData(content);
        setTotal(totalElements);
      }
    };

    getPointsConsumption();
  }, [pagination]);

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

  const columns: TableProps<PointsData>['columns'] = [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      width: 80,
      render: tableCellRender(false, TableCellValueType.Index, {
        page: pagination.current! - 1,
        pageSize: pagination.pageSize!,
      }),
    },
    {
      title: '任务',
      dataIndex: 'task_name',
      key: 'task_name',
      width: '15%',
      render: formatTask,
    },
    {
      title: '任务类型',
      dataIndex: 'task_type',
      key: 'task_type',
      width: '10%',
      render: statusTableCell(taskTypeOptions),
    },
    {
      title: '积分/小时',
      dataIndex: 'credit_per_hour',
      key: 'credit_per_hour',
      width: '10%',
      render: tableCellRender(),
    },
    {
      title: '消耗的积分(分)',
      dataIndex: 'deduce_credit',
      key: 'deduce_credit',
      width: '12%',
      render: tableCellRender(),
    },
    {
      title: '资源规格',
      dataIndex: 'description',
      key: 'description',
      render: tableCellRender(true),
    },
    {
      title: '开始时间',
      dataIndex: 'start_time',
      key: 'start_time',
      width: '15%',
      render: tableCellRender(false, TableCellValueType.Date),
    },
    {
      title: '状态',
      dataIndex: 'state',
      key: 'state',
      width: '8%',
      render: statusTableCell([
        {
          value: 0,
          label: '已结束',
          color: themes['textColor'],
        },
        {
          value: 1,
          label: '进行中',
          color: themes['primaryColor'],
        },
        {
          value: 2,
          label: '准备中',
          color: themes['pendingColor'],
        },
      ]),
    },
  ];

  return (
    <div className={styles['points-detail']}>
      <PageTitle title="算力积分明细"></PageTitle>
      <div className={styles['points-detail__content']}>
        <div className={styles['points-detail__content__top']}>
          <Statistics
            remaining={statistics?.userCredit}
            consuming={statistics?.deduceCredit}
          ></Statistics>
        </div>
        <div
          className={classNames('vertical-scroll-table', styles['points-detail__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 PointsDetail;
