/*
 * @Author: 吴文洁
 * @Date: 2020-08-05 10:12:45
 * @LastEditors: zhangleyuan
 * @LastEditTime: 2021-01-15 19:58:12
 * @Description: 视频课-列表模块
 * @Copyright: 杭州杰竞科技有限公司 版权所有
 */
import React from 'react';
import { Table, Modal, message , Tooltip,Switch,Dropdown} from 'antd';

import { PageControl } from "@/components";
import { LIVE_SHARE_MAP } from '@/common/constants/academic/cloudClass';
import { appId, shareUrl, LIVE_SHARE } from '@/domains/course-domain/constants';


import ShareLiveModal from '@/modules/course-manage/modal/ShareLiveModal';
import WatchDataModal from '../modal/WatchDataModal'
import CourseService from "@/domains/course-domain/CourseService";

import User from '@/common/js/user'


import './VideoCourseList.less';

const ENV = process.env.DEPLOY_ENV || 'dev';

class VideoCourseList extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      id: '', // 视频课ID
      studentIds:[]
    }
  }

  componentDidMount() {
    const videoCourseItem = localStorage.getItem('videoCourseItem');
    if (videoCourseItem) {
      const _videoCourseItem = JSON.parse(videoCourseItem);
      this.handleShowShareModal(_videoCourseItem, true);
    }
  }
  
  // 观看数据弹窗
  handleShowWatchDataModal = (record) => {
    console.log('111');
    console.log("record",record);
    const watchDataModal = (
      <WatchDataModal
        type='videoCourseList'
        data={record}
        close={() => {
          this.setState({
            watchDataModal:  null
          });
        }}
      />
    );
    this.setState({ watchDataModal });
  }

  // 请求表头
  parseColumns = () => {
    const columns = [
      {
        title: '视频课',
        key: 'scheduleName',
        dataIndex: 'scheduleName',
        width:'15%',
        render: (val, record) => {
          const { coverUrl, scheduleVideoUrl } = record;
          return (
            <div className="record__item">
              {/* 上传了封面的话就用上传的封面, 没有的话就取视频的第一帧 */}
              <img className="course-cover" src={coverUrl || `${scheduleVideoUrl}?x-oss-process=video/snapshot,t_0,m_fast`} />
              { record.courseName.length > 25?
                <Tooltip title={record.courseName}>
                  <div className="course-name">{record.courseName}</div>
                </Tooltip>
                :
                <div className="course-name">{record.courseName}</div>
              }
            </div>
          )
        }
      },
      {
        title: '课程分类',
        key: 'categoryName',
        dataIndex: 'categoryName',
        width: '10%',
        render: (val, record) => {
          return (
            <div className="record__item">
              {record.categoryOneName}{ record.categoryTwoName?`-${record.categoryTwoName}`:''}
            </div>
          )
        }
      },
      {
        title: '创建人',
        key: 'createName',
        dataIndex: 'createName',
        width: '8%',
        render: (val) => {
          return (
              <div>
                { val &&
                  <Tooltip title={val}>
                    <div>
                    
                    {val.length > 4 ? `${val.slice(0,4)}...` : val}

                  </div>
                </Tooltip>
                }
             </div>
          )
        }
      },
      {
        title: <span>
          <span>店铺展示</span>
          <Tooltip  title={<div>开启后，用户可在店铺内查看到此课程。若课程“未成功开课”，则系统会自动“关闭”店铺展示。<br/>关闭后，店铺内不再展示此课程，但用户仍可通过分享的海报/链接查看此课程。</div>}><i className="icon iconfont" style={{ marginLeft: '5px',cursor:'pointer',color:'#bfbfbf'}}>&#xe61d;</i></Tooltip>
        </span>,
        width: '12%',
        dataIndex: "courseware",
        render: (val, item, index) => {
          return  (
            <Switch  defaultChecked={item.shelfState==="YES"?true:false}  onChange={()=>this.changeShelfState(item)}/>
          ) 
        },
      },
      {
        title: "观看用户数",
        width: "10%",
        key: "watchUserCount",
        dataIndex: "watchUserCount",
        render: (val, item) => {
          return (
            <div className="watchUserCount">{val}</div>
          )
        },
      },
      {
        title: '创建时间',
        width: "10%",
        key: 'created',
        dataIndex: 'created',
        sorter: true,
        render: (val) => {
          return formatDate('YYYY-MM-DD H:i', val) 
        }
      },
      {
        title: '更新时间',
        width: "10%",
        key: 'updated',
        dataIndex: 'updated',
        sorter: true,
        render: (val) => {
          return formatDate('YYYY-MM-DD H:i', val) 
        }
      },
      {
        title: '操作',
        key: 'operate',
        dataIndex: 'operate',
        width: "20%",
        render: (val, record) => {
          return (
            <div className="operate">
              <div className="operate__item" onClick={()=>this.handleShowWatchDataModal(record)}>观看数据</div>
              <span className="operate__item split"> | </span>
              <div className="operate__item" onClick={() => this.handleShowShareModal(record)}>分享</div>
              <span className="operate__item split"> | </span>
              <Dropdown overlay={this.renderMoreOperate(record)}>
                <span className="more-operate">
                  <span className="operate-text">更多</span>
                  <span
                    className="iconfont icon"
                    style={{ color: "#5289FA" }}
                  >
                    &#xe824;
                  </span>
                </span>
              </Dropdown>
            </div>
          )
        }
      }
    ];
    return columns;
  }

  renderMoreOperate = (item) => {
    return (
      <div className="live-course-more-menu">
          <div
            className="operate__item"
            onClick={() => {
              RCHistory.push(`/create-video-course?type=edit&id=${item.id}`);
            }}
          >编辑</div>
          <div
            className="operate__item"
            onClick={() => this.handleDeleteVideoCourse(item.id)}
          >删除</div>
      </div>
    )
  }
    //改变上架状态
  changeShelfState = (item) =>{
    let _shelfState = item.shelfState
    if(_shelfState==='NO'){
      _shelfState = "YES";
      item.shelfState = "YES"
    }else{
      _shelfState = "NO"
      item.shelfState = "NO"
    }
    const params={
      courseId: item.id,
      shelfState:_shelfState
    }
    CourseService.changeVideoShelfState(params).then((res)=>{
      if(res.success){
        if(_shelfState === "YES"){
          message.success("已开启展示");
        }else{
          message.success("已取消展示");
        }
      }
    }) 
  }
  // 删除视频课
  handleDeleteVideoCourse = (scheduleId) => {
    Modal.confirm({
      title: '你确定要删除此视频课吗？',
      content: '删除后，学员将不能进行观看。',
      icon: <span className="icon iconfont default-confirm-icon">&#xe6f4;</span>,
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        const param ={
          courseId:scheduleId,
          storeId:User.getStoreId()
        }
        CourseService.delVideoSchedule(
          param
        ).then(() => {
          message.success('删除成功');
          this.props.onChange();
        })
      }
    });
  }



  // 显示分享弹窗
  handleShowShareModal = (record, needStr = false) => {
    const { id, scheduleVideoUrl } = record;

    const _appId =  appId;
    const htmlUrl = `${LIVE_SHARE}video_detail/${id}?id=${User.getStoreId()}`;
    const longUrl = htmlUrl;
    const { coverUrl, courseName } = record;
    const shareData = {
      longUrl,
      coverUrl,
      scheduleVideoUrl,
      courseName,
    };

    const shareLiveModal = (
      <ShareLiveModal
        needStr={needStr}
        data={shareData}
        type="videoClass"
        close={() => {
          this.setState({
            shareLiveModal:  null
          });
          localStorage.setItem('videoCourseItem', '');
        }}
      />
    );

    this.setState({ shareLiveModal });
  }

  handleChangeTable = (pagination, filters, sorter) => {
    const { columnKey, order } = sorter;
    const { query } = this.props;
    let { order: _order } =query;
    // 按创建时间升序排序
    if (columnKey === 'created' && order === 'ascend') { _order = 'CREATED_ASC'; }
    // 按创建时间降序排序
    if (columnKey === 'created' && order === 'descend') { _order = 'CREATED_DESC'; }
    // 按更新时间升序排序
    if (columnKey === 'updated' && order === 'ascend') { _order = 'UPDATED_ASC'; }
    // 按更新时间降序排序
    if (columnKey === 'updated' && order === 'descend') { _order = 'UPDATED_DESC'; }

    const _query = {
      ...query,
      orderEnum: _order
    };
    this.props.onChange(_query);
  }
  
  render() {

    const { dataSource = [], totalCount, query } = this.props;
    const { current, size } = query;

    return (
      <div className="video-course-list">
        <Table
          rowKey={record => record.id}
          dataSource={dataSource}
          columns={this.parseColumns()}
          onChange={this.handleChangeTable}
          pagination={false}
        />

        <div className="box-footer">
          <PageControl
            current={current - 1}
            pageSize={size}
            total={totalCount}
            toPage={(page) => {
              const _query = {...query, current: page + 1};
              this.props.onChange(_query)
            }}
          />
        </div>   
        { this.state.shareLiveModal }
        { this.state.watchDataModal }
      </div>
    )
  }
}

export default VideoCourseList;
