import React from "react"
import { Table, Modal, message, Tooltip, Switch, Dropdown } from "antd"
import _ from "underscore"
import { PageControl } from "@/components"
import { LIVE_SHARE } from "@/domains/course-domain/constants"
import { Route, withRouter } from 'react-router-dom';
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 VideoCourseDetail from '../VideoCourseDetail';
import WatchData from "./WatchData";
import { XMTable } from '@/components';
import college from '@/common/lottie/college';
import "./VideoCourseList.less"

class VideoCourseList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      id: '', // 视频课ID
      studentIds: [],
      RelatedPlanModalVisible: false,
      selectPlanList: {},
      ShelfLoading: false,
      // dataSource: [],
    };
  }

  componentDidMount() {
    const videoCourseItem = localStorage.getItem('videoCourseItem');
    if (videoCourseItem) {
      const _videoCourseItem = JSON.parse(videoCourseItem);
      this.handleShowShareModal(_videoCourseItem, true);
    }
  }

    // 跳转课程详情页
    handleLinkToCourseDetail = (courseId) => {
      const { match } = this.props;
  
      window.RCHistory.push(`${match.url}/video-course-detail?courseId=${courseId}`)
    }

  // 观看数据弹窗
  handleShowWatchDataModal = (item) => {
    const { match } = this.props;
    window.RCHistory.push({
      pathname: `${match.url}/course-data?courseName=${item.courseName}&courseId=${item.id}`
    })
  }

  // 请求表头
  parseColumns = () => {
    const { type } = this.props;
    const { ShelfLoading } = this.state;
    const columns = [
      {
        title: "线上课",
        key: "scheduleName",
        dataIndex: "scheduleName",
        width: 321,
        fixed: 'left',
        render: (val, record) => {
          const { coverUrl } = record;
          return (
            <div className='record__item'>
              <img
                className='course-cover'
                src={
                  coverUrl ||  'https://image.xiaomaiketang.com/xm/mt3ZQRxGKB.png'
                }
                alt='封面图'
              />
              <Choose>
                <When condition={record.courseName.length > 25}>
                  <Tooltip title={record.courseName}>
                    <div className='course-name'>{record.courseName}</div>
                  </Tooltip>
                </When>
                <Otherwise>
                  <div className='course-name'>{record.courseName}</div>
                </Otherwise>
              </Choose>
            </div>
          );
        },
      },
      {
        title: (
          <span>
            <span>课程分类</span>
            <If condition={type !== 'internal'}>
              <Tooltip title={<div>外部课程的分类由系统提供，不影响企业课程分类。</div>}>
                <i className='icon iconfont' style={{ marginLeft: '5px', cursor: 'pointer', color: '#bfbfbf', fontSize: '14px', fontWeight: 'normal' }}>
                  &#xe61d;
                </i>
              </Tooltip>
            </If>
          </span>
        ),
        key: "categoryName",
        dataIndex: "categoryName",
        width: 150,
        render: (val, record) => {
          return (
            <Choose>
              <When condition={type === 'internal'}>
                <div className='record__item'>
                  {record.categoryOneName}
                  {record.categoryTwoName ? `-${record.categoryTwoName}` : ''}
                </div>
              </When>
              <Otherwise>
                <div className='record__item'>{record.categorySonName}</div>
              </Otherwise>
            </Choose>
          );
        },
      },
      {
        title: '课节数',
        key: 'chapterNum',
        dataIndex: 'chapterNum',
        className: "chapterNum",
        width: 100,
        align: 'right',
        render: (val,item) => {
          return <div onClick={()=>this.handleLinkToCourseDetail(item.id)}>{val || 1}</div>
        }
      },
      {
        title: (
          <span>
            <span>学院展示</span>
            <Tooltip
              title={
                <div>
                  开启后，学员可在学院内查看到此课程。
                  <br />
                  关闭后，学院内不再展示此课程，但学员仍可通过分享的海报/链接查看此课程。
                </div>
              }>
              <i className='icon iconfont' style={{ marginLeft: '5px', cursor: 'pointer', color: '#bfbfbf', fontSize: '14px', fontWeight: 'normal' }}>
                &#xe61d;
              </i>
            </Tooltip>
          </span>
        ),
        width: 120,
        key: 'shelfState',
        dataIndex: 'shelfState',
        render: (val, item, index) => {
          return (
            <Switch
              loading={ShelfLoading}
              checked={item.shelfState === 'YES'}
              defaultChecked={item.shelfState}
              onClick={(checked) => {
                this.changeShelfState(checked, item, index);
              }}
            />
          );
        },
      },
      {
        title: "观看学员数",
        width: 150,
        key: "watchUserCount",
        dataIndex: "watchUserCount",
        align: 'right',
        render: (val, item) => {
          return <div className='watchUserCount' onClick={() => this.handleShowWatchDataModal(item)}>{val || 0}</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: '创建时间',
        width: 181,
        key: 'created',
        dataIndex: 'created',
        sorter: true,
        render: (val) => {
          return window.formatDate('YYYY-MM-DD H:i', val);
        },
      },
      {
        title: '更新时间',
        width: 181,
        key: 'updated',
        dataIndex: 'updated',
        sorter: true,
        render: (val) => {
          return window.formatDate('YYYY-MM-DD H:i', val);
        },
      },
      {
        title: '关联项',
        width: 200,
        key: 'planList',
        dataIndex: 'planList',
        render: (val, record) => {
          return (
            <div className='related-task'>
              <Choose>
                <When condition={record.relatedPlanList}>
                  <Tooltip title={this.handlePlanName(record.relatedPlanList)} placement='top' arrowPointAtCenter>
                    {record.relatedPlanList.map((item, index) => {
                      return (
                        <span key={item.planId}>
                          {item.planName} {index < record.relatedPlanList.length - 1 && <span> 、</span>}
                        </span>
                      );
                    })}
                  </Tooltip>
                </When>
                <Otherwise>
                  <span></span>
                </Otherwise>
              </Choose>
            </div>
          );
        },
      },
      {
        title: '操作',
        key: 'operate',
        dataIndex: 'operate',
        width: 160,
        fixed: 'right',
        render: (val, record) => {
          return (
            <div className='operate'>
              <If condition={type === "internal"}>
                <div className='operate__item' onClick={() => this.handleShowShareModal(record)}>
                  分享
                </div>
                <span className='operate__item split'> | </span>
              </If>
              <Dropdown overlay={this.renderMoreOperate(record)}>
                <span className='more-operate'>
                  <span className='operate-text'>更多</span>
                  <span className='iconfont icon' style={{ color: '#2966FF' }}>
                    &#xe824;
                  </span>
                </span>
              </Dropdown>
            </div>
          );
        },
      },
    ];

    type !== 'internal' && columns.splice(5, 1);
    return columns;
  };

  renderMoreOperate = (item) => {
    const { type } = this.props;
    return (
      <div className='live-course-more-menu'>
        <If condition={type !== 'internal'}>
          <div className='operate__item' onClick={() => this.handleShowShareModal(item)}>
            分享
          </div>
        </If>
        {(User.getUserRole() === 'CloudManager' || User.getUserRole() === 'StoreManager') && (
          <div className='operate__item' onClick={() => this.handleRelatedModalShow(item)}>
            关联培训计划
          </div>
        )}
        <If condition={type === 'internal'}>
          <div
            className='operate__item'
            onClick={() => {
              window.RCHistory.push(`/create-video-course?type=edit&id=${item.id}`);
            }}>
            编辑
          </div>
          <div className='operate__item' onClick={() => this.handleDeleteVideoCourse(item.id)}>
            删除
          </div>
        </If>
      </div>
    );
  };

  handlePlanName = (planArray) => {
    let planStr = '';
    planArray.forEach((item, index) => {
      if (index < planArray.length - 1) {
        planStr = planStr + item.planName + '、';
      } else {
        planStr = planStr + item.planName;
      }
    });
    return planStr;
  };
  //改变上架状态
  changeShelfState = (checked, item, index) => {
    let _shelfState = checked ? 'YES' : 'NO';
    if (checked) {
      _shelfState = 'YES';
    } else {
      _shelfState = 'NO';
    }
    const params = {
      courseId: item.id,
      shelfState: _shelfState,
    };
    CourseService.changeVideoShelfState(params).then(() => {
      if (_shelfState === 'YES') {
        message.success('已开启展示');
      } else {
        message.success('已取消展示');
      }
      this.props.changeShelfState(index, _shelfState);
    });
  };

  // 删除线上课
  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 { type } = this.props;
    const { id, scheduleVideoUrl } = record;
    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'
        courseDivision={type}
        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, type, match } = this.props;
    const { current, size } = query;
    const { RelatedPlanModalVisible, selectPlanList, selectCourseId } = this.state;
    return (
      <div className={`video-course-list ${type !== 'internal' ? 'video-course-list-mt' : ''}`}>
        <XMTable
          renderEmpty={{
            image: college,
            description: '暂无数据',
          }}
          rowKey={(record) => record.id}
          dataSource={dataSource}
          columns={this.parseColumns()}
          onChange={this.handleChangeTable}
          pagination={false}
          bordered
          scroll={{ x: 1500 }}
          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}
        <Route path={`${match.url}/video-course-detail`} component={VideoCourseDetail} />
        <Route path={`${match.url}/course-data`} component={WatchData} />
      </div>
    );
  }
}

export default withRouter(VideoCourseList);
