/*
 * @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 { 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 ENUM from "../../../knowledge-base/ENUM.js";
import User from '@/common/js/user'


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:[],
      RelatedPlanModalVisible:false,
      selectPlanList:{}
    }
  }

  componentDidMount() {
    const videoCourseItem = localStorage.getItem('videoCourseItem');
    if (videoCourseItem) {
      const _videoCourseItem = JSON.parse(videoCourseItem);
      this.handleShowShareModal(_videoCourseItem, true);
    }
  }
  
  // 观看数据弹窗
  handleShowWatchDataModal = (record) => {
    const watchDataModal = (
      <WatchDataModal
        type='videoCourseList'
        data={record}
        close={() => {
          this.setState({
            watchDataModal:  null
          });
        }}
      />
    );
    this.setState({ watchDataModal });
  }
  
  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 { coverUrl, scheduleVideoUrl } = record;
          return (
            <div className="record__item">
              <img className="course-cover" src={coverUrl || defaultCoverUrl} />
              <div>
                <Tooltip title={record.courseName}>
                  <div className="course-name">{record.courseName}</div>
                </Tooltip>
                <div className="course-text">地点：一行最多二十字超出一行最多二十字超出</div>
                <div className="course-text">12-01 09:00 ~ 01-01 14:00</div>
              </div>
            </div>
          )
        }
      },
      {
        title: '上课状态',
        key: 'courseState',
        dataIndex: 'courseState',
        width: 120,
        render: (val, record) => {
          return (
            <div className="record__item">
              {ENUM.offlineStateShow[val]}
            </div>
          )
        }
      },
      {
        title: '课程分类',
        key: 'categoryName',
        dataIndex: 'categoryName',
        width: 120,
        render: (val, record) => {
          return (
            <div className="record__item">
              {record.categoryOneName}{ record.categoryTwoName?`-${record.categoryTwoName}`:''}
            </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: "teacher",
        dataIndex: "teacher",
        render: (val, item) => {
          return (
            <div className="watchUserCount">张老师</div>
          )
        },
      },
      {
        title: '报名时间',
        width: 181,
        key: 'updated',
        dataIndex: 'updated',
        sorter: true,
        render: (val) => {
          return formatDate('YYYY-MM-DD H:i', val) 
        }
      },
      {
        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={()=>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;
  }

  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(); });
  }

  renderMoreOperate = (item) => {
    return (
      <div className="live-course-more-menu">
        {(User.getUserRole() === "CloudManager" || User.getUserRole() === "StoreManager") &&
          <div
            className="operate__item"
            key="plan"
            onClick={() => {
              this.handleRelatedModalShow(item);
            }}
          >关联培训计划</div>
        }
        <div
          className="operate__item"
          key="edit"
          onClick={() => {
            RCHistory.push(`/create-graphics-course?type=edit&id=${item.id}`);
          }}
        >编辑</div>
        <div
          className="operate__item"
          key="delete"
          onClick={() => this.handleDeleteOfflineCourse(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("已取消展示");
        }
      }
    }) 
  }
  // 删除视频课
  handleDeleteOfflineCourse = (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}graphics_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 { RelatedPlanModalVisible, selectCourseId, selectPlanList } = this.state;
    const { dataSource = [], totalCount, query } = this.props;
    const { current, size } = query;

    return (
      <div className="offline-course-list">
        <Table
          rowKey={record => record.id}
          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>  
        {RelatedPlanModalVisible &&
          <RelatedPlanModal 
            onClose={this.closeRelatedPlanModalVisible}
            visible={RelatedPlanModalVisible}
            selectCourseId={selectCourseId}
            selectPlanList={selectPlanList}
            onChange={this.onChangeSelectPlanList}
            onConfirm={this.onConfirmSelectPlanList}
          />
        } 
        { 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 OfflineCourseList;
