/*
 * @Author: 吴文洁
 * @Date: 2020-07-14 15:43:00
 * @Last Modified by: chenshu
 * @Last Modified time: 2021-03-16 17:37:23
 * @Description: 大班直播、互动班课的直播课列表
 */

import User from '@/common/js/user'
import college from '@/common/lottie/college'
import { PageControl, XMTable } from '@/components'
import DownloadLiveModal from '@/components/DownloadLiveModal'
import BaseService from '@/domains/basic-domain/baseService'
import { LIVE_SHARE } from '@/domains/course-domain/constants'
import CourseService from '@/domains/course-domain/CourseService'
import { QuestionCircleOutlined } from '@ant-design/icons'
import { Dropdown, message, Modal, Switch, Tooltip } from 'antd'
import React from 'react'
import { Route, withRouter } from 'react-router-dom'
import _ from 'underscore'
import DataList from '../DataList/DataList'
import ManageCoursewareModal from '../modal/ManageCoursewareModal'
import RelatedPlanModal from '../modal/RelatedPlanModal'
import ShareLiveModal from '../modal/ShareLiveModal'
import './LiveCourseList.less'

const { confirm } = Modal
const courseStateShow = {
  UN_START: {
    code: 1,
    title: '待开课',
    color: '#FFB129',
  },
  STARTING: {
    code: 2,
    title: '上课中',
    color: '#238FFF',
  },
  FINISH: {
    code: 3,
    title: '已完成',
    color: '#3BBDAA',
  },
  EXPIRED: {
    code: 4,
    title: '未成功开课',
    color: '#999',
  },
}
class LiveCourseList extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      columns: [],
      openDownloadModal: false,
      url: '',
      RelatedPlanModalVisible: false,
      selectPlanList: {},
    }
  }
  componentWillMount() {
    this.parseColumns()
  }
  componentDidMount() {
    this.getDownloadVersion()
  }
  // 显示分享弹窗
  handleShowShareModal = (item, needStr = false) => {
    const { liveCourseId } = item

    const htmlUrl = `${LIVE_SHARE}live_detail/${liveCourseId}?id=${User.getStoreId()}`
    const longUrl = htmlUrl
    console.log('htmlUrl', htmlUrl, longUrl)

    const shareData = { ...item, longUrl }
    const shareLiveModal = (
      <ShareLiveModal
        needStr={needStr}
        data={shareData}
        type='liveClass'
        title='直播课'
        close={() => {
          this.setState({
            shareLiveModal: null,
          })
          localStorage.setItem('largeLiveCourseItem', '')
        }}
      />
    )

    this.setState({ shareLiveModal })
  }

  //改变上架状态
  changeShelfState = (index, item, checked) => {
    let _shelfState = checked ? 'YES' : 'NO'
    const params = {
      liveCourseId: item.liveCourseId,
      shelfState: _shelfState,
    }
    CourseService.turnOnOrOffLiveCloudCourse(params).then((res) => {
      if (res.success) {
        if (_shelfState === 'YES') {
          message.success('已开启展示')
        } else {
          message.success('已取消展示')
        }
        this.props.changeShelfState(index, _shelfState)
      }
    })
  }

  // 前往上课数据页面
  handleLinkToClassData = (item) => {
    const { match } = this.props

    window.RCHistory.push({
      pathname: `${match.url}/live-course-data?type=large&id=${item.liveCourseId}`,
    })
  }
  parseColumns = () => {
    let columns
    const userRole = User.getUserRole()
    if (userRole !== 'CloudLecturer') {
      columns = [
        {
          title: '直播课',
          width: '23%',
          key: 'course',
          fixed: 'left',
          dataIndex: 'courseName',
          render: (val, record) => {
            let hasCover = false
            return (
              <div className='record__item'>
                {record.courseMediaVOS.map((item, index) => {
                  if (item.contentType === 'COVER') {
                    hasCover = true
                    return <img key={item.mediaContent + index} className='course-cover' src={item.mediaUrl} alt='' />
                  } else {
                    return null
                  }
                })}
                {!hasCover && <img className='course-cover' src={'https://image.xiaomaiketang.com/xm/Yip2YtFDwH.png'} alt='' />}
                <div>
                  <Choose>
                    <When condition={record.courseName.length > 14}>
                      <Tooltip title={record.courseName}>
                        <div className='course-name'>{record.courseName}</div>
                      </Tooltip>
                    </When>
                    <Otherwise>
                      {' '}
                      <div className='course-name'>{record.courseName}</div>
                    </Otherwise>
                  </Choose>

                  <div>
                    <span className='course-time'>
                      {window.formatDate('YYYY-MM-DD H:i', parseInt(record.startTime))}~{window.formatDate('H:i', parseInt(record.endTime))}
                    </span>
                    <span
                      className='course-status'
                      style={{ color: courseStateShow[record.courseState].color, border: `1px solid ${courseStateShow[record.courseState].color}` }}>
                      {courseStateShow[record.courseState].title}
                    </span>
                  </div>
                  <div className='teacher-assistant'>
                    <Choose>
                      <When condition={record.teacherName && record.teacherName.length > 4}>
                        <Tooltip title={record.teacherName}>
                          <span className='teacher'>讲师：{record.teacherName}</span>
                        </Tooltip>
                      </When>
                      <Otherwise>
                        <span className='teacher'>讲师：{record.teacherName}</span>
                      </Otherwise>
                    </Choose>

                    <If condition={record.admins.length > 0}>
                      <span className='split'> | </span>
                      <Choose>
                        <When condition={this.handleAdminName(record.admins).length > 4}>
                          <Tooltip title={this.handleAdminName(record.admins)}>
                            <span className='assistant'>
                              助教：
                              {record.admins.map((item, index) => {
                                return (
                                  <span key={item.adminId + index}>
                                    {item.adminName} {index < record.admins.length - 1 && <span> 、</span>}{' '}
                                  </span>
                                )
                              })}
                            </span>
                          </Tooltip>
                        </When>
                        <Otherwise>
                          <span className='assistant'>
                            助教：
                            {record.admins.map((item, index) => {
                              return (
                                <span>
                                  {item.adminName} {index < record.admins.length - 1 && <span> 、</span>}{' '}
                                </span>
                              )
                            })}
                          </span>
                        </Otherwise>
                      </Choose>
                    </If>
                  </div>
                </div>
              </div>
            )
          },
        },
        {
          title: '课程分类',
          width: '10%',
          key: 'couseCatalog',
          dataIndex: 'couseCatalog',
          render: (val, item) => {
            return <div className='categoryName'>{item.categorySonName}</div>
          },
        },
        {
          title: '课件管理',
          width: '8%',
          key: 'courseware',
          dataIndex: 'courseware',
          render: (val, item) => {
            return (
              <span
                className='courseware'
                onClick={() => {
                  this.setState({
                    editData: item,
                    openCoursewareModal: true,
                  })
                }}>
                {item.courseDocumentCount}个
              </span>
            )
          },
        },
        {
          title: '上课数据',
          width: '9%',
          key: 'quota',
          dataIndex: 'quota',
          render: (val, item) => {
            return (
              <span
                className='iconfont icon quota-icon'
                onClick={() => {
                  this.handleLinkToClassData(item)
                }}>
                &#xe7d6;
              </span>
            )
          },
        },
        {
          title: (
            <span>
              <span>学院展示</span>
              <Tooltip
                title={
                  <div>
                    开启后，学员可在学院内查看到此课程。若课程“未成功开课”，则系统会自动“关闭”学院展示。
                    <br />
                    关闭后，学院内不再展示此课程，但学员仍可通过分享的海报/链接查看此课程。
                  </div>
                }>
                <i className='icon iconfont' style={{ marginLeft: '5px', cursor: 'pointer', color: '#bfbfbf', fontSize: '14px', fontWeight: 'normal' }}>
                  &#xe61d;
                </i>
              </Tooltip>
            </span>
          ),
          width: '9%',
          key: 'shelfState',
          dataIndex: 'shelfState',
          render: (val, item, index) => {
            return (
              <Switch
                size='small'
                checked={item.shelfState === 'YES'}
                defaultChecked={item.shelfState === 'YES' ? true : false}
                onChange={(checked) => this.changeShelfState(index, item, checked)}
              />
            )
          },
        },
        {
          title: '创建时间',
          width: '9%',
          key: 'created',
          dataIndex: 'created',
          sorter: true,
          render: (val, item) => {
            // -29000：与后端约定 在初始化学院时，创建时间（标志位-29000）默认展示为'-'
            return <span style={{ whiteSpace: 'nowrap' }}>{val === -29000 ? '-' : window.formatDate('YYYY-MM-DD H:i', val)}</span>
          },
        },
        {
          title: '关联项',
          width: '15%',
          key: 'planList',
          dataIndex: 'planList',
          render: (val, record) => {
            return (
              <div className='related-task'>
                <Choose>
                  <When condition={record.relatedPlanList}>
                    <Tooltip title={this.handlePlanName(record.relatedPlanList)} placement='top' arrowPointAtCenter>
                      {record.relatedPlanList.map((item, index) => {
                        return (
                          <span>
                            {item.planName} {index < record.relatedPlanList.length - 1 && <span> 、</span>}{' '}
                          </span>
                        )
                      })}
                    </Tooltip>
                  </When>
                  <Otherwise>
                    <span></span>
                  </Otherwise>
                </Choose>
              </div>
            )
          },
        },
        {
          title: '操作',
          width: 210,
          key: 'operate',
          fixed: 'right',
          dataIndex: 'operate',
          render: (val, item) => {
            return (
              <div className='operate'>
                {(item.courseState === 'UN_START' || item.courseState === 'STARTING') &&
                  (item.teacherId === User.getUserId() || _.pluck(item.admins, 'adminId').includes(User.getUserId())) && (
                    <>
                      <div
                        key='enter_live_room1'
                        className='operate__item'
                        onClick={() => {
                          this.handleEnterLiveRoom(item)
                        }}>
                        进入直播间
                      </div>
                      <span className='operate__item split' key='view_play_back_split'>
                        {' '}
                        |{' '}
                      </span>
                    </>
                  )}
                {item.courseState === 'FINISH' && item.haveRecord === 'YES' && (
                  <>
                    <div
                      key='view_play_back'
                      className='operate__item'
                      onClick={() => {
                        this.handleViewPlayBack(item)
                      }}>
                      查看回放
                    </div>
                    <span className='operate__item split' key='view_play_back_split'>
                      {' '}
                      |{' '}
                    </span>
                  </>
                )}
                {item.courseState !== 'EXPIRED' && (
                  <>
                    <div
                      key='share'
                      className='operate__item'
                      onClick={() => {
                        this.handleShowShareModal(item)
                      }}>
                      分享
                    </div>
                  </>
                )}
                {item.courseState !== 'EXPIRED' && (
                  <>
                    <span key='split1' className='operate__item split'>
                      {' '}
                      |{' '}
                    </span>
                    <div className='big-live'>
                      <Dropdown overlay={this.renderMoreOperate(item)}>
                        <span className='more-operate'>
                          <span className='operate-text'>更多</span>
                          <span className='iconfont icon' style={{ color: '#2966FF' }}>
                            &#xe824;
                          </span>
                        </span>
                      </Dropdown>
                    </div>
                  </>
                )}
                {item.courseState === 'EXPIRED' && (
                  <div className='operate__item' onClick={() => this.handleDelete(item)}>
                    删除
                  </div>
                )}
              </div>
            )
          },
        },
      ]
    } else {
      columns = [
        {
          title: '直播课',
          width: '25%',
          key: 'course',
          dataIndex: 'courseName',
          render: (val, record) => {
            let hasCover = false
            return (
              <div className='record__item'>
                {record.courseMediaVOS.map((item, index) => {
                  if (item.contentType === 'COVER') {
                    hasCover = true
                    return <img className='course-cover' src={item.mediaUrl} alt='' />
                  }
                })}
                {!hasCover && <img className='course-cover' src={'https://image.xiaomaiketang.com/xm/Yip2YtFDwH.png'} alt='' />}
                <div>
                  <Choose>
                    <When condition={record.courseName.length > 17}>
                      <Tooltip title={record.courseName}>
                        <div className='course-name'>{record.courseName}</div>
                      </Tooltip>
                    </When>
                    <Otherwise>
                      <div className='course-name'>{record.courseName}</div>
                    </Otherwise>
                  </Choose>

                  <div>
                    <span className='course-time'>
                      {window.formatDate('YYYY-MM-DD H:i', parseInt(record.startTime))}~{window.formatDate('H:i', parseInt(record.endTime))}
                    </span>
                    <span
                      className='course-status'
                      style={{ color: courseStateShow[record.courseState].color, border: `1px solid ${courseStateShow[record.courseState].color}` }}>
                      {courseStateShow[record.courseState].title}
                    </span>
                  </div>
                  <div className='teacher-assistant'>
                    <Choose>
                      <When condition={record.teacherName && record.teacherName.length > 4}>
                        <Tooltip title={record.teacherName}>
                          <span className='teacher'>讲师：{record.teacherName}</span>
                        </Tooltip>
                      </When>
                      <Otherwise>
                        <span className='teacher'>讲师：{record.teacherName}</span>
                      </Otherwise>
                    </Choose>

                    <If condition={record.admins.length > 0}>
                      <span className='split'> | </span>
                      <Choose>
                        <When condition={this.handleAdminName(record.admins).length > 4}>
                          <Tooltip title={this.handleAdminName(record.admins)}>
                            <span className='assistant'>
                              助教：
                              {record.admins.map((item, index) => {
                                return (
                                  <span>
                                    {item.adminName} {index < record.admins.length - 1 && <span> 、</span>}{' '}
                                  </span>
                                )
                              })}
                            </span>
                          </Tooltip>
                        </When>
                        <Otherwise>
                          <span className='assistant'>
                            助教：
                            {record.admins.map((item, index) => {
                              return (
                                <span>
                                  {item.adminName} {index < record.admins.length - 1 && <span> 、</span>}{' '}
                                </span>
                              )
                            })}
                          </span>
                        </Otherwise>
                      </Choose>
                    </If>
                  </div>
                </div>
              </div>
            )
          },
        },
        {
          title: '课程分类',
          width: '10%',
          key: 'couseCatalog',
          dataIndex: 'couseCatalog',
          render: (val, item) => {
            return <div className='categoryName'>{item.categorySonName}</div>
          },
        },
        {
          title: '课件管理',
          width: '8%',
          key: 'courseware',
          dataIndex: 'courseware',
          render: (val, item) => {
            return (
              <span
                className='courseware'
                onClick={() => {
                  this.setState({
                    editData: item,
                    openCoursewareModal: true,
                  })
                }}>
                {item.courseDocumentCount}个
              </span>
            )
          },
        },
        {
          title: '上课数据',
          width: '9%',
          key: 'quota',
          dataIndex: 'quota',
          render: (val, item) => {
            return (
              <span
                className='iconfont icon quota-icon'
                onClick={() => {
                  this.handleLinkToClassData(item)
                }}>
                &#xe7d6;
              </span>
            )
          },
        },
        {
          title: '创建时间',
          width: '9%',
          key: 'created',
          dataIndex: 'created',
          sorter: true,
          render: (val, item) => {
            return <span>{window.formatDate('YYYY-MM-DD H:i', val)}</span>
          },
        },
        {
          title: '关联项',
          width: '15%',
          key: 'planList',
          dataIndex: 'planList',
          render: (val, record) => {
            return (
              <div className='related-task'>
                <Choose>
                  <When condition={record.relatedPlanList}>
                    <Tooltip title={this.handlePlanName(record.relatedPlanList)} placement='top' arrowPointAtCenter>
                      {record.relatedPlanList.map((item, index) => {
                        return (
                          <span>
                            {item.planName} {index < record.relatedPlanList.length - 1 && <span> 、</span>}{' '}
                          </span>
                        )
                      })}
                    </Tooltip>
                  </When>
                  <Otherwise>
                    <span></span>
                  </Otherwise>
                </Choose>
              </div>
            )
          },
        },
      ]
    }
    this.setState({ columns })
  }
  handleAdminName = (adminArray) => {
    let adminStr = ''
    adminArray.forEach((item, index) => {
      if (index < adminArray.length - 1) {
        adminStr = adminStr + item.adminName + '、'
      } else {
        adminStr = adminStr + item.adminName
      }
    })
    return adminStr
  }

  handlePlanName = (planArray) => {
    let planStr = ''
    planArray.forEach((item, index) => {
      if (index < planArray.length - 1) {
        planStr = planStr + item.planName + '、'
      } else {
        planStr = planStr + item.planName
      }
    })
    return planStr
  }

  renderMoreOperate = (item) => {
    return (
      <div className='live-course-more-menu'>
        {(User.getUserRole() === 'CloudManager' || User.getUserRole() === 'StoreManager') && (
          <div className='operate__item' onClick={() => this.handleRelatedModalShow(item)}>
            关联培训任务
          </div>
        )}
        <div className='operate__item' onClick={() => this.toEditCoursePage(item)}>
          编辑
        </div>
        {item.courseState !== 'STARTING' && (
          <div className='operate__item' onClick={() => this.handleDelete(item)}>
            删除
          </div>
        )}
      </div>
    )
  }
  handleDelete = (record) => {
    return confirm({
      title: '你确定要删除直播课？',
      content: '删除后，学员将不能观看直播课/回放',
      icon: <span className='icon iconfont default-confirm-icon'>&#xe839; </span>,
      okText: '删除',
      okType: 'danger',
      cancelText: '取消',
      width: 440,
      height: 188,
      onOk: () => {
        this.deleteConfirm(record)
      },
    })
  }
  deleteConfirm = (item) => {
    const params = {
      liveCourseId: item.liveCourseId,
    }
    CourseService.delLiveCloudCourse(params).then((res) => {
      if (res.success) {
        message.success('已删除')
        this.props.onChange()
      }
    })
  }
  toEditCoursePage = (item) => {
    window.RCHistory.push({
      pathname: `/create-live-course?type=edit&id=${item.liveCourseId}`,
    })
  }
  refreshCourseList = () => {
    this.props.onChange(this.props.query)
  }
  //进入直播间
  handleEnterLiveRoom = (item) => {
    if (item.startTime - Date.now() > 1800000) {
      Modal.warning({
        title: '你来得太早了',
        okText: '我知道了',
        content: '请于开始上课前30分钟来直播上课。',
        icon: (
          <span className='icon iconfont default-confirm-icon' style={{ color: '#FFBB54 !important' }}>
            &#xe834;
          </span>
        ),
      })
    } else {
      CourseService.getLiveCloudCourseDetail({
        liveCourseId: item.liveCourseId,
      }).then((res) => {
        const url = `xmqx://liveCourseId=${item.liveCourseId}`
        if (res.result.courseState === 'FINISH') {
          Modal.warning({
            title: '刷新页面',
            icon: <QuestionCircleOutlined />,
            content: '课次已结束，请刷新一下',
            onOk: () => {
              this.refreshCourseList()
            },
          })
        } else {
          this.setState({ url, openDownloadModal: true })
        }
      })
    }
  }
  onShowSizeChange = (current, size) => {
    if (current === size) {
      return
    }
    let _query = this.props.query
    _query.size = size
    this.props.onChange(_query)
  }
  getDownloadVersion() {
    const isMac = /macintosh|mac os x/i.test(navigator.userAgent)
    // 判断学员系统
    let platform
    if (!isMac) {
      platform = 1
    } else {
      platform = 4
    }
    BaseService.getLastedVersion({ model: 5, platform }).then((res) => {
      const { result = {} } = res
      this.setState({ downloadUrl: result.releaseUrl })
    })
  }
  handleViewPlayBack = (item) => {
    let htmlUrl
    if (item.teacherId === User.getUserId()) {
      htmlUrl = `${LIVE_SHARE}replay/${item.liveCourseId}?teacherId=${User.getUserId()}&id=${User.getStoreId()}`
    } else if (_.pluck(item.admins, 'adminId').includes(User.getUserId())) {
      htmlUrl = `${LIVE_SHARE}replay/${item.liveCourseId}?userId=${User.getUserId()}&id=${User.getStoreId()}`
    } else {
      htmlUrl = `${LIVE_SHARE}replay/${item.liveCourseId}?id=${User.getStoreId()}`
    }
    window.open(htmlUrl)
  }
  handleRelatedModalShow = (item) => {
    const selectPlanList = {}
    if (item.relatedPlanList) {
      item.relatedPlanList.map((item, index) => {
        selectPlanList[item.planId] = {}
        selectPlanList[item.planId].planId = item.planId
        selectPlanList[item.planId].taskBaseVOList = [{ taskId: item.taskId }]
        return item
      })
    }

    this.setState({
      RelatedPlanModalVisible: true,
      selectCourseId: item.liveCourseId,
      selectPlanList: selectPlanList,
    })
  }
  closeRelatedPlanModalVisible = () => {
    this.setState({
      RelatedPlanModalVisible: false,
    })
  }
  onChangeSelectPlanList = (selectPlanList) => {
    this.setState({
      selectPlanList: selectPlanList,
    })
  }
  onConfirmSelectPlanList = () => {
    this.setState(
      {
        RelatedPlanModalVisible: false,
      },
      () => {
        this.props.onChange()
      }
    )
  }
  handleChangeTable = (pagination, filters, sorter) => {
    const { columnKey, order } = sorter
    const { query } = this.props
    let _columnKey
    let _order
    // 按创建时间升序排序
    if (columnKey === 'created' && order === 'ascend') {
      _columnKey = 'CREATED'
      _order = 'SORT_ASC'
    }
    // 按创建时间降序排序
    if (columnKey === 'created' && order === 'descend') {
      _columnKey = 'CREATED'
      _order = 'SORT_DESC'
    }
    const _query = {
      ...query,
      sortMap: {},
    }
    _query.sortMap[_columnKey] = _order
    this.props.onChange(_query)
  }
  render() {
    const { total, query, courseList, loading } = this.props
    const { current, size } = query
    const { openDownloadModal, downloadUrl, url, columns, openCoursewareModal, editData, RelatedPlanModalVisible, selectCourseId, selectPlanList } = this.state
    const { match } = this.props

    return (
      <div className='live-course-list'>
        <XMTable
          renderEmpty={{
            image: college,
            description: '暂无数据',
          }}
          bordered
          size='middle'
          pagination={false}
          columns={columns}
          scroll={{ x: 1300 }}
          loading={loading}
          dataSource={courseList}
          onChange={this.handleChangeTable}
          rowKey={(row) => row.liveCourseId}
        />
        {total > 0 && (
          <div className='box-footer'>
            <PageControl
              current={current - 1}
              pageSize={size}
              total={parseInt(total)}
              toPage={(page) => {
                const _query = { ...query, current: page + 1 }
                this.props.onChange(_query)
              }}
              onShowSizeChange={this.onShowSizeChange}
            />
          </div>
        )}
        {this.state.shareLiveModal}
        {openCoursewareModal && (
          <ManageCoursewareModal
            data={editData}
            onCancel={() => {
              this.props.onChange()
              this.setState({ openCoursewareModal: false })
            }}
          />
        )}
        {openDownloadModal && (
          <DownloadLiveModal
            url={downloadUrl}
            onCancel={() => {
              this.setState({
                url: '',
                openDownloadModal: false,
              })
            }}
          />
        )}
        {RelatedPlanModalVisible && (
          <RelatedPlanModal
            onClose={this.closeRelatedPlanModalVisible}
            visible={RelatedPlanModalVisible}
            selectCourseId={selectCourseId}
            selectPlanList={selectPlanList}
            onChange={this.onChangeSelectPlanList}
            onConfirm={this.onConfirmSelectPlanList}
          />
        )}
        <iframe src={url} style={{ display: 'none' }} title='navigation' />
        <Route path={`${match.url}/live-course-data`} component={DataList} />
      </div>
    )
  }
}

export default withRouter(LiveCourseList)
