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

import React from 'react';
import { Table, Modal, message, Dropdown, Button,Switch,Tooltip} from 'antd';
import { Route, withRouter } from 'react-router-dom';
import { PageControl } from "@/components";
import DownloadLiveModal from '@/components/DownloadLiveModal';


import ManageCoursewareModal from '../modal/ManageCoursewareModal';
import ShareLiveModal from '../modal/ShareLiveModal';
import RelatedPlanModal from '../modal/RelatedPlanModal';

import './LiveCourseList.less';
import { QuestionCircleOutlined } from '@ant-design/icons';
import { appId, shareUrl, LIVE_SHARE,LIVE_REPLAY_MAP} from '@/domains/course-domain/constants';
import CourseService from "@/domains/course-domain/CourseService";
import BaseService from "@/domains/basic-domain/baseService";
import DataList from '../DataList/DataList';
import User from '@/common/js/user';
import _ from "underscore";


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 _appId =  appId;
    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 = (item) =>{
    let _shelfState = item.shelfState
    if(_shelfState==='NO'){
      _shelfState = "YES";
      item.shelfState = "YES"
    }else{
      _shelfState = "NO"
      item.shelfState = "NO"
    }
    const params={
      "liveCourseId": item.liveCourseId,
      "shelfState":_shelfState
    }
    CourseService.turnOnOrOffLiveCloudCourse(params).then((res)=>{
      if(res.success){
        if(_shelfState === "YES"){
          message.success("已开启展示");
        }else{
          message.success("已取消展示");
        }
      }
    }) 
  }

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

    window.RCHistory.push({
      pathname: `${match.url}/live-course-data?type=large&id=${item.liveCourseId}`
    });
  }
  parseColumns = () => {
    const menu = (item) => (
      <div className="live-course-more-menu">
        <div>
          上课记录
        </div>
        <div
          onClick={() => {
            this.handleShowRepeatModal(item);
          }}
        >
          回放记录
        </div>
      </div>
    );
    let columns
    const userRole =  User.getUserRole();
    if(userRole !=="CloudLecturer"){
      columns = [
        {
          title: "直播课",
          width: "23%",
          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} />
                    }    
                  })
                }
                { !hasCover  && 
                  <img className="course-cover" src={'https://image.xiaomaiketang.com/xm/Yip2YtFDwH.png'} />
                }
                <div>
                    { record.courseName.length > 17?
                      <Tooltip title={record.courseName}>
                        <div className="course-name">{record.courseName}</div>
                      </Tooltip>
                      :
                      <div className="course-name">{record.courseName}</div>
                    }
                   <div>
                      <span className="course-time">{formatDate("YYYY-MM-DD H:i",parseInt(record.startTime))}~{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">
                    { record.teacherName.length > 4 ?
                        <Tooltip title={record.teacherName}>
                          <span className="teacher">讲师：{record.teacherName}</span>
                        </Tooltip>
                        :
                        <span className="teacher">讲师：{record.teacherName}</span>
                      }
                      
                      { record.admins.length >0 &&
                        <>
                          <span  className="split"> | </span>
                          { 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>
                              :
                              <span className="assistant">助教：
                                { record.admins.map((item,index)=>{
                                    return <span>{item.adminName} { (index < record.admins.length-1)&&(<span> 、</span>)} </span>
                                  })
                                }
                              </span>
                          }
                            
                        </>
                      }
                   </div>
                </div>
              </div>
            )
          }
        },
        {
          title: "课程分类",
          width: "10%",
          key: "couseCatalog",
          dataIndex: "couseCatalog",
          render: (val, item) => {
            return (
              <div className="categoryName">{item.categoryName}</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  defaultChecked={item.shelfState==="YES"?true:false}  onChange={()=>this.changeShelfState(item)}/>
            ) 
          },
        },
        {
          title: '创建时间',
          width: "9%",
          key: "created",
          dataIndex: "created",
          sorter: true,
          render: (val, item) => {
            return (
              <span>{formatDate('YYYY-MM-DD H:i', val)}</span>
            );
          },
        },
        {
          title: '关联项',
          width: "15%",
          key: "planList",
          dataIndex: "planList",
          render: (val, record) => {
            return  (
              <div className="related-task">
                  { 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>
                    :
                    <span></span>
                  }
              </div>
            )
          },
        },
        {
          title: "操作",
          width: "15%",
          key: "operate",
          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} />
                    }    
                  })
                }
                { !hasCover  && 
                  <img className="course-cover" src={'https://image.xiaomaiketang.com/xm/Yip2YtFDwH.png'} />
                }
                <div>
                    { record.courseName.length > 17?
                      <Tooltip title={record.courseName}>
                        <div className="course-name">{record.courseName}</div>
                      </Tooltip>
                      :
                      <div className="course-name">{record.courseName}</div>
                    }
                   <div>
                      <span className="course-time">{formatDate("YYYY-MM-DD H:i",parseInt(record.startTime))}~{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">
                   { record.teacherName.length > 4 ?
                      <Tooltip title={record.teacherName}>
                        <span className="teacher">讲师：{record.teacherName}</span>
                      </Tooltip>
                      :
                      <span className="teacher">讲师：{record.teacherName}</span>
                    }
                      
                      
                      { record.admins.length >0 &&
                        <>
                          <span  className="split"> | </span>
                          { 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>
                              :
                              <span className="assistant">助教：
                                { record.admins.map((item,index)=>{
                                    return <span>{item.adminName} { (index < record.admins.length-1)&&(<span> 、</span>)} </span>
                                  })
                                }
                              </span>
                          }
                        </>
                      }
                   </div>
                </div>
              </div>
            )
          }
        },
        {
          title: "课程分类",
          width: "10%",
          key: "couseCatalog",
          dataIndex: "couseCatalog",
          render: (val, item) => {
            return (
              <div className="categoryName">{item.categoryName}</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>{formatDate('YYYY-MM-DD H:i', val)}</span>
            );
          },
        },
        {
          title: '关联项',
          width: "15%",
          key: "planList",
          dataIndex: "planList",
          render: (val, record) => {
            return  (
              <div className="related-task">
                  { 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>
                    :
                    <span></span>
                  }
              </div>
            )
          },
        },
      ];
    }
    this.setState({ columns })
  }
  handleAdminName = (adminArray)=>{
    let adminStr = "";
    adminArray.map((item,index)=>{
      if(index < adminArray.length-1){
        adminStr = adminStr + item.adminName + '、';
      }else{
        adminStr = adminStr + item.adminName
      }
    })
    return adminStr
  }

  handlePlanName = (planArray)=>{
    let planStr = "";
    planArray.map((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">
        <Table
          bordered
          size="middle"
          pagination={false}
          columns={columns}
          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}
            type={type}
            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" }} />
        <Route path={`${match.url}/live-course-data`} component={DataList} />
      </div>
    )
  }
}

export default withRouter(LiveCourseList);