/* eslint-disable react/react-in-jsx-scope */
import { Table, Space, Popconfirm } from 'antd';
import moment from 'moment';
import * as coursesAPI from '../../apis/coursesAPI';
import { useTranslation } from 'react-i18next';

const CourseTable = ({
  coursesData,
  totalSize,
  isCourse,
  isPureWeb,
  initTab,
  handleTableChange,
  handlePageSizeChange,
  currentPage,
  currentPageSize,
  handleCreateCourse,
  handleCreateAlbum,
  handleDeleteCourse,
  handleShowCourseDetail,
  handleDeleteAlbum,
  handleCopyUrl,
  handleRouterToOtherPage,
  handleCompletedLiveCourse,
  platform,
  loading,
}) => {
  const { t, i18n } = useTranslation();

  const columns = (
    handleCreateCourse,
    handleDeleteCourse,
    handleShowCourseDetail,
    initTab,
    handleCopyUrl,
    handleRouterToOtherPage,
    isPureWeb,
    handleCompletedLiveCourse,
    platform, // 预留的参数当前的环境
  ) => {
    // 我创建的列表只有状态是未审核的才能修改或删除
    const canEditAndDelete = (record) =>
      (record.Status === 1 || record.Status === 3) && // 未审核 || 已拒绝
      initTab === 1; // 我创建的列表

    // 只有状态是已审核的免费课程才能分享
    const canShare = (record) =>
      record.Status === 2 && // 已审核
      record.NeedPay === false; // 不需要购买

    // 已审核后可以查看详情（我创建的）
    const canShowDetail = (record) => record.Status === 2 && initTab === 1;

    // 老师端在web不能进入课程 并且我创建的里的课程状态要是已审核或者我申请的已经开始的课程
    const isShowStartCourseButton = (record) =>
      record.CourseType === 1 && // 课程是直播课
      ((!isPureWeb && // 非web端（壳子里面）
        initTab === 1 && // 我创建的列表
        (record.Status === 2 || record.Status === 4)) || // 课程状态是已审核或者已开始
        (initTab === 3 && record.Status === 4)); // 我参与的列表下 只有已开始

    // 开始课程和进入课程的文案
    const isStartCourse = (record) =>
      initTab === 1 && // 我创建的tab
      record.Status === 2; // 已审核

    const token =
      sessionStorage.getItem('token') &&
      sessionStorage.getItem('token') !== 'null'
        ? JSON.parse(sessionStorage.getItem('token'))
        : null;
    // 是否结束课程 需要是直播课、是否壳子、是否是我创建的列表、课程状态是否已开始
    const isEndCourse = (record) =>
      record.CourseType === 1 &&
      !isPureWeb &&
      initTab === 1 &&
      record.Status === 4;
    const tableColumns = [
      {
        title: t('课程名称'),
        dataIndex: 'Name',
        fixed: 'left',
        key: 'Name',
        width: 250,
      },
      {
        title: t('状态'),
        dataIndex: 'Status',
        key: 'Status',
        render: (status) => `${getStatusName(status)}`,
        width: 100,
      },
      {
        title: t('开始时间'),
        dataIndex: 'StartTime',
        key: 'StartTime',
        render: (startTime) => `${getStartTimeName(startTime)}`,
        width: 120,
      },
      {
        title: t('操作'),
        key: 'Operation',
        fixed: 'right',
        width: 250,
        render: (_, record) => (
          <Space size='middle'>
            {canEditAndDelete(record) && (
              <a
                onClick={() => {
                  handleCreateCourse(record.Code);
                }}>
                {t('修改')}
              </a>
            )}
            {canEditAndDelete(record) && (
              <Popconfirm
                title={t('是否删除该课程')}
                onConfirm={() => {
                  handleDeleteCourse(record.Code);
                }}
                onCancel={() => {}}
                okText={t('是')}
                cancelText={t('否')}>
                <a> {t('删除')} </a>
              </Popconfirm>
            )}
            {canShowDetail(record) && (
              <a onClick={() => handleShowCourseDetail(record.Code)}>
                {t('详情')}
              </a>
            )}
            {canShare(record) && (
              <a onClick={() => handleCopyUrl(record.CourseShareUrl)}>
                {t('分享')}
              </a>
            )}
            {isShowStartCourseButton(record) && (
              <a
                onClick={() => {
                  if (record.IsAssistant) {
                    handleRouterToOtherPage(
                      '/video_course_player/' + record.Code + '/' + platform,
                    );
                  } else {
                    coursesAPI.sendCourseEntryNotice(
                      `target=joinCourse?code=${record.Code}&token=${token}`,
                    );
                  }
                }}>
                {isStartCourse(record) ? t('开始课程') : t('进入课程')}
              </a>
            )}
            {isEndCourse(record) && (
              <Popconfirm
                title={t('是否结束该课程')}
                onConfirm={() => {
                  handleCompletedLiveCourse(record.Code);
                }}
                onCancel={() => {}}
                okText={t('是')}
                cancelText={t('否')}>
                <a>{t('结束课程')}</a>
              </Popconfirm>
            )}
          </Space>
        ),
      },
    ];
    if (initTab === 2) {
      return [
        ...tableColumns.slice(0, tableColumns.length - 1),
        {
          title: t('操作'),
          key: 'Operation',
          fixed: 'right',
          width: 250,
          render: (_, record) => (
            <Space size='middle'>
              {/* {(record.Status === 2 || record.Status === 4) && (
                <a onClick={() => handleCopyUrl(record.CourseLiveUrl)}>
                  {t('分享')}
                </a>
              )} */}

              {record.CourseType === 1 && record.Status === 4 && (
                <a
                  onClick={() => {
                    handleRouterToOtherPage(
                      '/video_course_player/' + record.Code + '/' + platform,
                    );
                  }}>
                  {t('进入课程')}
                </a>
              )}
            </Space>
          ),
        },
      ];
    } else {
      return tableColumns;
    }
  };

  const getStatusName = (status) => {
    switch (status) {
      case 1:
        return t('待审核');
      case 2:
        return t('已审核');
      case 3:
        return t('已拒绝');
      case 4:
        return t('已开始');
      case 5:
        return t('已结束');
      case 6:
        return t('已取消');
      case 7:
        return t('延时');
      case 8:
        return t('不在线');
      default:
        return t('暂无');
    }
  };

  const getStartTimeName = (startTime) => {
    const dateObj = moment(startTime).local();
    const formattedTime = dateObj.format('YYYY-MM-DD HH:mm:ss');
    if (formattedTime.includes('0001-01-01')) {
      return '--';
    }
    return formattedTime;
  };

  return (
    <Table
      rowKey={(record) => record.Code}
      onRow={(record) => {
        return {
          onClick: (event) => {
            if (
              event.target.tagName !== 'A' &&
              event.target.tagName !== 'SPAN'
            ) {
              let path;
              if (isCourse) {
                path = '/detail/' + record.Code + '/course';
              } else {
                path = '/detail/' + record.Code + '/album';
              }
              handleRouterToOtherPage(path);
            }
          },
        };
      }}
      locale={{ emptyText: t('暂无数据') }}
      columns={columns(
        handleCreateCourse,
        handleDeleteCourse,
        handleShowCourseDetail,
        initTab,
        handleCopyUrl,
        handleRouterToOtherPage,
        isPureWeb,
        handleCompletedLiveCourse,
        platform,
      )}
      loading={loading}
      dataSource={coursesData}
      pagination={{
        current: currentPage,
        pageSize: currentPageSize,
        showSizeChanger: true,
        onShowSizeChange: handlePageSizeChange,
        total: totalSize,
      }}
      onChange={(pagination, filters) => {
        handleTableChange(pagination, filters);
      }}
      className='flex flex-col flex-grow'
    />
  );
};

export default CourseTable;
