/*
 * @Author: 吴文洁
 * @Date: 2020-08-05 10:12:45
 * @LastEditors: yuananting
 * @LastEditTime: 2021-03-24 19:34:48
 * @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 RelatedPlanModal from '../../modal/RelatedPlanModal';
import User from '@/common/js/user'


import './VideoCourseList.less';

const ENV = process.env.DEPLOY_ENV || 'dev';
const userRole =  User.getUserRole();
class VideoCourseList extends React.Component {

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

  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:321,
        fixed: 'left',
        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: 200,
        render: (val, record) => {
          return (
            <div className="record__item">
              {record.categoryOneName}{ record.categoryTwoName?`-${record.categoryTwoName}`:''}
            </div>
          )
        }
      },
      {
        title: '创建人',
        key: 'createName',
        dataIndex: 'createName',
        width: 100,
        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',fontSize:'14px'}}>&#xe61d;</i></Tooltip>
        </span>,
        width: 120,
        dataIndex: "courseware",
        render: (val, item, index) => {
          return  (
            <Switch  defaultChecked={item.shelfState==="YES"?true:false}  onChange={()=>this.changeShelfState(item)}/>
          ) 
        },
      },
      {
        title: "观看用户数",
        width: 110,
        key: "watchUserCount",
        dataIndex: "watchUserCount",
        render: (val, item) => {
          return (
            <div className="watchUserCount">{val}</div>
          )
        },
      },
      {
        title: '创建时间',
        width: 181,
        key: 'created',
        dataIndex: 'created',
        sorter: true,
        render: (val) => {
          return formatDate('YYYY-MM-DD H:i', val) 
        }
      },
      {
        title: '更新时间',
        width: 181,
        key: 'updated',
        dataIndex: 'updated',
        sorter: true,
        render: (val) => {
          return formatDate('YYYY-MM-DD H:i', val) 
        }
      },
      {
        title: '关联项',
        width: 200,
        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: '操作',
        key: 'operate',
        dataIndex: 'operate',
        width: 210,
        fixed: 'right',
        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">
        { (User.getUserRole() === "CloudManager" || User.getUserRole() === "StoreManager") &&
           <div
            className="operate__item"
            onClick={()=>this.handleRelatedModalShow(item)}
          >关联培训计划</div>
        }
          <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>
    )
  }
  
  handlePlanName = (planArray)=>{
    let planStr = "";
    planArray.map((item,index)=>{
      if(index < planArray.length-1){
        planStr = planStr + item.planName + '、';
      }else{
        planStr = planStr + item.planName
      }
    })
    return planStr
  }
  //改变上架状态
  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: '确定',
      okType: 'danger',
      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"
        title="视频课"
        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);
  }
  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.id,
      selectPlanList:selectPlanList
    })
  }
  closeRelatedPlanModalVisible = ()=>{
    this.setState({
      RelatedPlanModalVisible:false
    })
  }
  onChangeSelectPlanList = (selectPlanList)=>{
    this.setState({
      selectPlanList:selectPlanList
    })
  }
  onConfirmSelectPlanList = ()=>{
    this.setState({
      RelatedPlanModalVisible:false
    },()=>{this.props.onChange();})
  }
  render() {

    const { dataSource = [], totalCount, query } = this.props;
    const { current, size } = query;
    const {RelatedPlanModalVisible,selectPlanList,selectCourseId} = this.state;
    return (
      <div className="video-course-list">
        <Table
          rowKey={record => record.id}
          dataSource={dataSource}
          columns={this.parseColumns()}
          onChange={this.handleChangeTable}
          pagination={false}
          scroll={{ x: 1500}}
          bordered
          className="video-list-table"
        />

        <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>   
        { RelatedPlanModalVisible &&
          <RelatedPlanModal 
            onClose={this.closeRelatedPlanModalVisible}
            visible={RelatedPlanModalVisible}
            selectCourseId={selectCourseId}
            selectPlanList={selectPlanList}
            onChange={this.onChangeSelectPlanList}
            onConfirm={this.onConfirmSelectPlanList}
          />
        }
        { this.state.shareLiveModal }
        { this.state.watchDataModal }
      </div>
    )
  }
}

export default VideoCourseList;
