/* eslint-disable jsx-a11y/anchor-is-valid */
import { Table, Space, Popconfirm } from 'antd';
import moment from 'moment';
import * as coursesAPI from '../../apis/coursesAPI';

const columns = (
  handleCreateCourse,
  handleDeleteCourse,
  initTab,
  handleCopyUrl,
  handleRouterToOtherPage,
  isPureWeb,
  handleCompletedLiveCourse,
  platform, // 预留的参数当前的环境
) => {
  // 我创建的列表只有状态是未审核的才能删除和编辑
  const isEditAndDelete = (record) =>
    (record.Status === 1 || record.Status === 3) && initTab === 1;
  // 只有状态是已审核的免费课程才能分享
  const isShare = (record) => record.Status === 2 && record.NeedPay === false;
  // 老师端在web不能进入课程 并且我创建的里的课程状态要是已审核或者我申请的已经开始的课程
  const isStartCourse = (record) =>
    record.CourseType === 1 &&
    ((!isPureWeb && initTab === 1 && record.Status === 2) ||
      (initTab === 3 && record.Status === 4));
  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: '课程名称',
      width: 150,
      dataIndex: 'Name',
      fixed: 'left',
      key: 'Name',
    },
    {
      title: '课程形式',
      dataIndex: 'CourseType',
      key: 'CourseType',
      render: (courseType) => `${getCourseTypeName(courseType)}`,
      width: 100,
    },
    {
      title: '所属专辑',
      dataIndex: 'CourseAlbums',
      render: (courseAlbums) => `${getCourseAlbumsName(courseAlbums)}`,
      key: 'CourseAlbums',
      width: 250,
    },
    {
      title: '状态',
      dataIndex: 'Status',
      key: 'Status',
      render: (status) => `${getStatusName(status)}`,
      width: 100,
    },
    {
      title: '开始时间',
      dataIndex: 'StartTime',
      key: 'StartTime',
      // align: "center",
      render: (startTime) => `${getStartTimeName(startTime)}`,
      width: 150,
    },
    {
      title: '课程规模',
      dataIndex: 'AudienceType',
      key: 'AudienceType',
      render: (AudienceType) => `${getAudienceTypeName(AudienceType)}`,
      width: 100,
    },
    {
      title: '播放量',
      dataIndex: 'PlayCount',
      key: 'PlayCount',
      render: (playCount) => `${playCount}`,
      width: 100,
    },
    {
      title: '创建时间',
      dataIndex: 'CreateTime',
      key: 'CreateTime',
      render: (createTime) => `${getStartTimeName(createTime)}`,
      width: 150,
    },
    {
      title: '操作',
      key: 'operation',
      fixed: 'right',
      width: 250,
      render: (_, record) => (
        <Space size='middle'>
          {isEditAndDelete(record) && (
            <a
              onClick={() => {
                handleCreateCourse(record.Code);
              }}>
              修改
            </a>
          )}
          {isEditAndDelete(record) && (
            <Popconfirm
              title='是否删除该课程'
              onConfirm={() => {
                handleDeleteCourse(record.Code);
              }}
              onCancel={() => {}}
              okText='是'
              cancelText='否'>
              <a> 删除 </a>
            </Popconfirm>
          )}
          {isShare(record) && (
            <a onClick={() => handleCopyUrl(record.CourseShareUrl)}>分享</a>
          )}
          {isStartCourse(record) && (
            <a
              onClick={() => {
                if (record.IsAssistant) {
                  handleRouterToOtherPage(
                    '/video_course_player/' + record.Code + '/' + platform,
                  );
                } else {
                  coursesAPI.sendCourseEntryNotice(
                    `target=joinCourse?code=${record.Code}&token=${token}`,
                  );
                }
              }}>
              {initTab === 1 ? '开始课程' : '进入课程'}
            </a>
          )}
          {isEndCourse(record) && (
            <a onClick={() => handleCompletedLiveCourse(record.Code)}>
              结束课程
            </a>
          )}
        </Space>
      ),
    },
  ];
  if (initTab === 2) {
    return [
      ...tableColumns.slice(0, tableColumns.length - 1),
      {
        title: '操作',
        key: 'operation',
        fixed: 'right',
        width: 250,
        render: (_, record) => (
          <Space size='middle'>
            {(record.Status === 2 || record.Status === 4) && (
              <a onClick={() => handleCopyUrl(record.CourseLiveUrl)}>分享</a>
            )}

            {record.CourseType === 1 && record.Status === 4 && (
              <a
                onClick={() => {
                  handleRouterToOtherPage(
                    '/video_course_player/' + record.Code + '/' + platform,
                  );
                }}>
                进入课程
              </a>
            )}
          </Space>
        ),
      },
    ];
  } else {
    return tableColumns;
  }
};
// 专辑表头
const albumColumns = (
  handleCreateAlbum,
  handleDeleteAlbum,
  initTab,
  handleCopyUrl,
) => {
  return [
    {
      title: '专辑名称',
      width: 250,
      dataIndex: 'Name',
      key: 'Name',
    },

    // {
    //   title: '开始时间',
    //   dataIndex: 'StartTime',
    //   key: 'StartTime',
    //   render: (startTime) => `${getStartTimeName(startTime)}`,
    //   width: 150,
    // },
    {
      title: '课程规模',
      dataIndex: 'AudienceType',
      key: 'AudienceType',
      render: (AudienceType) => `${getAudienceTypeName(AudienceType)}`,
      width: 100,
    },
    {
      title: '创建时间',
      dataIndex: 'CreateTime',
      key: 'CreateTime',
      render: (createTime) => `${getStartTimeName(createTime)}`,
      width: 150,
    },
    {
      title: '操作',
      key: 'operation',
      fixed: 'right',
      width: 250,
      render: (_, record) => (
        <Space size='middle'>
          <a
            onClick={() => {
              handleCreateAlbum(record.Code);
            }}>
            修改
          </a>
          <Popconfirm
            title='是否删除该专辑'
            onConfirm={() => {
              handleDeleteAlbum(record.Code);
            }}
            onCancel={() => {}}
            okText='是'
            cancelText='否'>
            <a> 删除 </a>
          </Popconfirm>
          <a onClick={() => handleCopyUrl(record.CourseShareUrl)}>分享</a>
        </Space>
      ),
    },
  ];
};

const getCourseTypeName = (courseType) => {
  switch (courseType) {
    case 1:
      return '直播课程';
    case 2:
      return '多媒体课程';
    default:
      return '暂无';
  }
};

const getStatusName = (status) => {
  switch (status) {
    case 1:
      return '待审核';
    case 2:
      return '已审核';
    case 3:
      return '已拒绝';
    case 4:
      return '已开始';
    case 5:
      return '已结束';
    case 6:
      return '已取消';
    case 7:
      return '延时';
    case 8:
      return '不在线';
    default:
      return '暂无';
  }
};
const getAudienceTypeName = (AudienceType) => {
  switch (AudienceType) {
    case 0:
      return '未填写';
    case 1:
      return '公开课';
    case 2:
      return '私有课';
    default:
      return '暂无';
  }
};
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;
};

const getCourseAlbumsName = (courseAlbums) => {
  if (!courseAlbums || courseAlbums.length === 0) return '暂无';
  let courseAlbumsNameList = [];
  for (let i of courseAlbums) {
    courseAlbumsNameList.push(i.Name);
  }
  return courseAlbumsNameList.join('、');
};
// const data = [];
// for (let i = 0; i < 100; i++) {
//   data.push({
//     key: i,
//     name: `Edward ${i}`,
//     age: 32,
//     address: `London Park no. ${i}`,
//   });
// }
const CourseTable = ({
  coursesData,
  totalSize,
  isCourse,
  isPureWeb,
  initTab,
  handleTableChange,
  handlePageSizeChange,
  currentPage,
  currentPageSize,
  handleCreateCourse,
  handleCreateAlbum,
  handleDeleteCourse,
  handleDeleteAlbum,
  handleCopyUrl,
  handleRouterToOtherPage,
  handleCompletedLiveCourse,
  platform,
}) => (
  <Table
    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: '暂无数据' }}
    columns={
      isCourse
        ? columns(
            handleCreateCourse,
            handleDeleteCourse,
            initTab,
            handleCopyUrl,
            handleRouterToOtherPage,
            isPureWeb,
            handleCompletedLiveCourse,
            platform,
          )
        : albumColumns(
            handleCreateAlbum,
            handleDeleteAlbum,
            initTab,
            handleCopyUrl,
          )
    }
    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;
