/*
 * @Author: 吴文洁 
 * @Date: 2020-07-14 15:43:00 
 * @Last Modified by: mikey.zhaopeng
 * @Last Modified time: 2020-11-23 20:23:12
 * @Description: 大班直播、互动班课的直播课列表
 */

import React from 'react';
import { Table, Modal, message, Dropdown, Button,Switch,Tooltip} from 'antd';
import { Route, withRouter } from 'react-router-dom';
// import Bus from '@/core/bus';
// import User from "@/core/user";
// import User_t from "@/teacher/core/user";
import { PageControl } from "@/components";
// import { LIVE_SHARE_MAP } from '@/common/constants/academic/cloudClass';
import DownloadLiveModal from '@/components/DownloadLiveModal';

// import LiveStudentListModal from '../modal/LiveStudentListModal';
// import CheckBalanceModal from '../modal/CheckBalanceModal';
// import StartLiveModal from '../modal/StartLiveModal';
// import ClassRecordModal from '../modal/ClassRecordModal';
// import PlayBackRecordModal from '../modal/PlayBackRecordModal';
import ManageCoursewareModal from '../modal/ManageCoursewareModal';
import ShareLiveModal from '../modal/ShareLiveModal';
// import AccountChargeModal from '../modal/AccountChargeModal';
// import SelectStudent from '../modal/select-student';

import './LiveCourseList.less';
import { QuestionCircleOutlined } from '@ant-design/icons';
import { appId, shareUrl, LIVE_SHARE } from '@/domains/course-domain/constants';
import CourseService from "@/domains/course-domain/CourseService";
import DataList from '../DataList/DataList';

const { confirm } = Modal;
const courseStateShow = {
  UN_START: {
    code: 1,
    title: "待上课",
    color: "#FDBE31",
  },
  STARTING: {
    code: 2,
    title: "上课中",
    color: "#238FFF",
  },
  FINISH: {
    code: 3,
    title: "已完成",
    color: "#2FC83C",
  },
  EXPIRED: {
    code: 4,
    title: "未成功开课",
    color: "#CCCCCC",
  },
};
class LiveCourseList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      columns: [],
      openDownloadModal:false,
      url:''
    }
  }
  componentWillMount(){
    this.parseColumns();
  }
  componentDidMount() {
    
  }
  // 显示分享弹窗
  handleShowShareModal = (item, needStr = false) => {
    const _appId =  appId;
    const _shareUrl = shareUrl;
    const { liveCourseId } = item;
    const { saaSVersionEnum } = window.currentUserInstInfo;

    const htmlUrl = `${LIVE_SHARE}liveShare?id=${liveCourseId}&saasVersion=${saaSVersionEnum}`;
    const link = `${_appId}&redirect_uri=${encodeURIComponent(htmlUrl)}%26appid%3D${_appId}&response_type=code&scope=snsapi_base&state=state#wechat_redirect`;
    const longUrl = `${_shareUrl}${link}`;

    const shareData = { ...item, longUrl };
    const shareLiveModal = (
      <ShareLiveModal
        needStr={needStr}
        data={shareData}
        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>
    );
 
    const 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/YNfi45JwFA.png'} />
              }
              <div>
                 <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>
                    <span className="teacher">讲师：{record.teacherName}</span>
                    
                    { record.admins.length >0 &&
                      <>
                        <span  className="split"> | </span>
                        <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="开启后，用户可在店铺内查看到此课程。若课程“未成功开课”，则系统会自动“关闭”店铺展示。关闭后，店铺内不再展示此课程，但用户仍可通过分享的海报/链接查看此课程。"><i className="icon iconfont" style={{ marginLeft: '5px',cursor:'pointer',color:'#bfbfbf'}}>&#xe61d;</i></Tooltip>
        </span>,
        width: "7%",
        dataIndex: "courseware",
        render: (val, item, index) => {
          return  (
            <Switch  defaultChecked={item.shelfState==="YES"?true:false}  onChange={()=>this.changeShelfState(item)}/>
          ) 
        },
      },
      {
        title: "操作",
        width: "15%",
        key: "operate",
        dataIndex: "operate",
        render: (val, item) => {
          return (
    
            <div className="operate">
              { (item.courseState==="UN_START" || item.courseState==="STARTING") && 
                <div
                  key="enter_live_room1"
                  className="operate__item"
                  onClick={() => { this.handleEnterLiveRoom(item) }}
                >进入直播间
                </div>
              }
              { (item.courseState==="FINISH") && 
              
                  <>
                  <div
                    key="view_play_back"
                    className="operate__item"
                  >查看回放</div>
                  </>
                
              }
              { item.courseState!=="EXPIRED" && 
                  <>
                  <span className="operate__item split" key="view_play_back_split"> | </span>
                  <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: "#5289FA" }}
                        >
                         &#xe824;
                        </span>
                      </span>
                    </Dropdown>
                  </div>
                </>
              }
              { item.courseState==="EXPIRED" &&
                <div
                 className="operate__item"
                 onClick={()=>this.handleDelete(item)}
               >删除</div>
              }
            </div>
          )
        }
      }
    ];
    this.setState({ columns })
  }

  renderMoreOperate = (item) => {
    return (
      <div className="live-course-more-menu">
          <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: <QuestionCircleOutlined />,
      okText: '删除',
      okType: 'danger',
      cancelText: '取消',
      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" }}
          >
            &#xe6f1;
          </span>
        ),
      });
    } else {
      // axios
      //   .Apollo("public/businessLive/getCourseDetail", {
      //     liveCourseId: item.liveCourseId,
      //   })
      //   .then((res) => {
      //     const url = `xiaomai5://instId=${instId}&courseId=${item.liveCourseId}&teacherId=${item.teacherId}&uid=${ teacherId ? User_t.uid() : User.uid()}&aid=${teacherId ? "" : User.aid()}&tid=${teacherId || ""}&identity=${identity}&classType=${item.liveType}&xmVersion=${window.NewVersion ? '5.0' : '4.0'}`;
      //     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)
  }
  
  render() {
    const { total, query, courseList, loading} = this.props;
    const { current, size } = query;
    const { openDownloadModal,
      downloadUrl, url, columns,
      openCoursewareModal,
      editData
    } = this.state;
    const { match } = this.props;

    return (
      <div className="live-course-list">
        <Table
          bordered
          size="middle"
          pagination={false}
          columns={columns}
          loading={loading}
          dataSource={courseList}
          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 });
            }}
          />
        )}
        <iframe src={url} style={{ display: "none" }} />
        <Route path={`${match.url}/live-course-data`} component={DataList} />
      </div>
    )
  }
}

export default withRouter(LiveCourseList);