/*
 * @Author: 吴文洁
 * @Date: 2020-08-05 10:12:45
 * @LastEditors: zhangleyuan
 * @LastEditTime: 2021-03-27 16:24:47
 * @Description: 视频课-列表模块
 * @Copyright: 杭州杰竞科技有限公司 版权所有
 */
import React from 'react';
import { Table, Modal, message , Tooltip,Switch,Dropdown} from 'antd';
import { Route, withRouter } from 'react-router-dom';
import moment from 'moment';
import $ from 'jquery';
import { PageControl } from "@/components";
import { appId, shareUrl, LIVE_SHARE } from '@/domains/course-domain/constants';
import OfflineCourseData from '@/modules/course-manage/offline-course/OfflineCourseData';
import ShareLiveModal from '@/modules/course-manage/modal/ShareLiveModal';
import Service from "@/common/js/service";
import CourseService from "@/domains/course-domain/CourseService";
import RelatedPlanModal from '../../modal/RelatedPlanModal';
import PreviewOfflineModal from '../modal/PreviewOfflineModal';
import ENUM from "../../../knowledge-base/ENUM.js";
import User from '@/common/js/user'
import QRCodeModal from '../modal/QRCodeModal';
import './OfflineCourseList.less';

const ENV = process.env.DEPLOY_ENV || 'dev';
const defaultCoverUrl = 'https://image.xiaomaiketang.com/xm/YNfi45JwFA.png';

class OfflineCourseList 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);
    }
  }
  
  handlePlanName = (planArray)=>{
    let planStr = "";
    planArray.map((item,index)=>{
      if(index < planArray.length-1){
        planStr = planStr + item.planName + '、';
      }else{
        planStr = planStr + item.planName
      }
    })
    return planStr
  }
  // 请求表头
  parseColumns = () => {
    const columns = [
      {
        title: '线下课',
        key: 'scheduleName',
        dataIndex: 'scheduleName',
        width:321,
        fixed: 'left',
        render: (val, record) => {
          const { courseMediaVOS, courseName, offlinePlace, calendarTime, startTime, endTime } = record;
          const coverUrl = (_.find(courseMediaVOS, data => data.contentType === 'COVER') || {}).mediaUrl;
          const time = `${calendarTime.map(item => moment(item).format('MM-DD')).join('、')} ${moment(startTime).format('HH:mm')} ~ ${moment(endTime).format('HH:mm')}`;
          return (
            <div className="record__item">
              <img className="course-cover" src={coverUrl || defaultCoverUrl} />
              <div>
                <Tooltip title={courseName}>
                  <div className="course-name">{courseName}</div>
                </Tooltip>
                <Tooltip title={`地点：${offlinePlace}`}>
                  <div className="course-text">地点：{offlinePlace}</div>
                </Tooltip>
                <Tooltip title={time}>
                  <div className="course-text">{time}</div>
                </Tooltip>
              </div>
            </div>
          )
        }
      },
      {
        title: '课程状态',
        key: 'courseState',
        dataIndex: 'courseState',
        width: 120,
        render: (val, record) => {
          return (
            <div className="course-state">
              <div style={{ width: 6, height: 6, borderRadius: '50%', background: ENUM.offlineStateShow[val].color, marginRight: 8 }}></div>
              {ENUM.offlineStateShow[val].title}
            </div>
          )
        }
      },
      {
        title: '课程分类',
        key: 'categoryName',
        dataIndex: 'categoryName',
        width: 120,
        render: (val, record) => {
          return (
            <div className="record__item">
              {record.categorySonName}
            </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
              disabled={item.courseState === 'EXPIRED'}
              defaultChecked={item.shelfState === "YES"}
              onChange={() => this.changeShelfState(item)}
            />
          ) 
        },
      },
      {
        title: "讲师",
        width: 200,
        key: "teacher",
        dataIndex: "teacher",
        render: (val, item) => {
          return (
            <div>{item.teacherName}</div>
          )
        },
      },
      {
        title: '报名时间',
        width: 181,
        key: 'apply',
        dataIndex: 'apply',
        sorter: true,
        render: (val, item) => {
          return item.startTimeApply ? `${formatDate('MM-DD H:i', item.startTimeApply)} ~ ${formatDate('MM-DD H:i', item.endTimeApply)}` : '-'
        }
      },
      {
        title: '创建时间',
        width: 181,
        key: 'created',
        dataIndex: 'created',
        sorter: true,
        render: (val) => {
          return formatDate('YYYY-MM-DD H:i', val) 
        }
      },
      {
        title: '操作',
        key: 'operate',
        dataIndex: 'operate',
        width: 210,
        fixed: 'right',
        render: (val, record) => {
          return (
            <div className="operate">
              <div className="operate__item" onClick={() => window.RCHistory.push(`/offline-course/data?id=${record.courseId}`)}>参与数据</div>
              {record.courseState !== 'EXPIRED' && <span className="operate__item split"> | </span>}
              {record.courseState !== 'EXPIRED' && <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;
  }
  
  // 显示预览弹窗
  handleShowPreviewModal = (query) => {
    const {
      courseName,
      startTime,
      endTime,
      categoryName,
      offlinePlace,
      courseMediaVOS,
    } = query;
    let coverUrl = '';
    courseMediaVOS.map((item) => {
      switch (item.contentType){
        case "COVER":
          coverUrl = item.mediaUrl;
        break;
        case "INTRO":
          this.getTextDetail('introduce', item.mediaUrl);
          break;  
        default:
          break;
      }
      return item;
    })
    setTimeout(() => {
      const { introduce } = this.state;
  
      const data = {
        coverUrl,
        courseName,
        startTime,
        endTime,
        categoryName,
        introduce,
        offlinePlace,
      }
      const previewOfflineModal = (
        <PreviewOfflineModal
          data={data}
          close={() => {
            this.setState({
              previewOfflineModal: null
            })
          }}
        />
      );
      this.setState({ previewOfflineModal });
    }, 500)
  }

  getTextDetail = (key, url) => {
    $.ajax({
      data: {},
      type: 'GET',
      url,
      contentType:'application/x-www-form-urlencoded; charset=UTF-8',
      success: (res) => {
        this.setState({ [key]: res, [`load${key}`]: true });
      }
    })
  }

  renderMoreOperate = (item) => {
    return (
      <div className="live-course-more-menu">
        {item.courseState !== 'EXPIRED' && <div
          className="operate__item"
          key="qrcode"
          onClick={() => {
            this.setState({ openQRCodeModal: true, qrcodeData: item })
          }}
        >考勤二维码</div>}
        <div
          className="operate__item"
          key="preview"
          onClick={() => {
            this.handleShowPreviewModal(item);
          }}
        >预览</div>
        {item.courseState === 'UN_START' && item.courseState === 'STARTING' && <div
          className="operate__item"
          key="cancel"
          onClick={() => {
            this.handleDeleteOfflineCourse(item.courseId);
          }}
        >取消课程</div>}
        {item.courseState === 'UN_START' && <div
          className="operate__item"
          key="edit"
          onClick={() => {
            RCHistory.push(`/create-offline-course?type=edit&id=${item.courseId}`);
          }}
        >编辑</div>}
        <div
          className="operate__item"
          key="delete"
          onClick={() => this.handleDeleteOfflineCourse(item.courseId, true)}
        >删除</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.courseId,
      shelfState:_shelfState
    }
    CourseService.changeVideoShelfState(params).then((res)=>{
      if(res.success){
        if(_shelfState === "YES"){
          message.success("已开启展示");
        }else{
          message.success("已取消展示");
        }
      }
    }) 
  }
  // 删除视频课
  handleDeleteOfflineCourse = (courseId, isDelete) => {
    if (isDelete) {
      Modal.confirm({
        title: '删除课程',
        content: '确定删除该学员吗？删除后用户数据和课程数据将无法恢复。',
        icon: <span className="icon iconfont default-confirm-icon">&#xe6f4;</span>,
        okText: '确定',
        okType: 'danger',
        cancelText: '取消',
        onOk: () => {
          const param ={
            courseId: courseId,
          }
          Service.Hades('public/hades/delOfflineCourse', param).then(() => {
            message.success('删除成功');
            this.props.onChange();
          })
        }
      });
    } else {
      Modal.confirm({
        title: '取消课程',
        content: '确定要取消该课程吗？取消后课程将失效，仅保留已有数据。',
        icon: <span className="icon iconfont default-confirm-icon">&#xe6f4;</span>,
        okText: '确定',
        cancelText: '取消',
        onOk: () => {
          const param ={
            courseId: courseId,
          }
          Service.Hades('public/hades/cancelOfflineCourse', param).then(() => {
            message.success('取消成功');
            this.props.onChange();
          })
        }
      });
    }
  }



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

    const _appId =  appId;
    const htmlUrl = `${LIVE_SHARE}offline_detail/${courseId}?id=${User.getStoreId()}`;
    const longUrl = htmlUrl;
    const { coverUrl, courseName } = record;
    const shareData = {
      longUrl,
      coverUrl,
      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  _columnKey;
    let _order;
    // 按创建时间升序排序
    if (columnKey === 'apply' && order === 'ascend') {_columnKey="START_APPLY_DESC"; _order = 'SORT_ASC'; }
    if (columnKey === 'created' && order === 'ascend') {_columnKey="CREATED"; _order = 'SORT_ASC'; }
    // 按创建时间降序排序
    if (columnKey === 'apply' && order === 'descend') { _columnKey="START_APPLY_DESC"; _order = 'SORT_DESC';}
    if (columnKey === 'created' && order === 'descend') { _columnKey="CREATED"; _order = 'SORT_DESC';}
    const _query = {
      ...query,
      sortMap:{}
    };
    _query.sortMap[_columnKey]=_order;
    this.props.onChange(_query);
  }

  render() {
    const { openQRCodeModal, qrcodeData } = this.state;
    const { dataSource = [], totalCount, query, match } = this.props;
    const { current, size } = query;
    return (
      <div className="offline-course-list">
        <Table
          rowKey={record => record.courseId}
          dataSource={dataSource}
          columns={this.parseColumns()}
          onChange={this.handleChangeTable}
          pagination={false}
          scroll={{ x: 1500}}
          bordered
          className="offline-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>  
        {this.state.shareLiveModal}
        {this.state.previewOfflineModal}
        <QRCodeModal
          visible={openQRCodeModal}
          data={qrcodeData}
          onCancel={() => {
            this.setState({ openQRCodeModal: false })
          }}
        />
        <Route path={`${match.url}/data`} component={OfflineCourseData} />
      </div>
    )
  }
}

export default withRouter(OfflineCourseList);
