/*
 * @Author: 吴文洁
 * @Date: 2020-08-05 10:12:45
 * @LastEditors: wufan
 * @LastEditTime: 2021-07-05 10:23:10
 * @Description: 线上课-列表模块
 * @Copyright: 杭州杰竞科技有限公司 版权所有
 */
import User from '@/common/js/user';
import college from '@/common/lottie/college';
import { PageControl, XMTable } from '@/components';
import { LIVE_SHARE } from '@/domains/course-domain/constants';
import CourseService from '@/domains/course-domain/CourseService';
import ShareLiveModal from '@/modules/course-manage/modal/ShareLiveModal';
import { Dropdown, message, Modal, Switch, Tooltip } from 'antd';
import React from 'react';
import RelatedPlanModal from '../../modal/RelatedPlanModal';
import WatchDataModal from '../modal/WatchDataModal';
import './GraphicsCourseList.less';

const defaultCoverUrl = 'https://image.xiaomaiketang.com/xm/wFnpZtp2yB.png';

class GraphicsCourseList 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.forEach((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 } = record;
          return (
            <div className='record__item'>
              {/* 上传了封面的话就用上传的封面, 没有的话就取视频的第一帧 */}
              <img className='course-cover' src={coverUrl || defaultCoverUrl} 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: '课程分类',
        key: 'categoryName',
        dataIndex: 'categoryName',
        width: 120,
        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', fontWeight: 'normal' }}>
                &#xe61d;
              </i>
            </Tooltip>
          </span>
        ),
        width: 120,
        dataIndex: 'courseware',
        render: (val, item, index) => {
          return (
            <Switch
              size='small'
              checked={item.shelfState === 'YES'}
              defaultChecked={item.shelfState === 'YES' ? true : false}
              onChange={(checked) => this.changeShelfState(index, item, checked)}
            />
          );
        },
      },
      {
        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 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>
                          {item.planName} {index < record.relatedPlanList.length - 1 && <span> 、</span>}{' '}
                        </span>
                      );
                    })}
                  </Tooltip>
                </When>
                <Otherwise>
                  <span></span>
                </Otherwise>
              </Choose>
            </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: '#2966FF' }}>
                    &#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={() => {
            window.RCHistory.push(`/create-graphics-course?type=edit&id=${item.id}`);
          }}>
          编辑
        </div>
        <div className='operate__item' key='delete' onClick={() => this.handleDeleteGraphicsCourse(item.id)}>
          删除
        </div>
      </div>
    );
  };
  //改变上架状态
  changeShelfState = (index, item, checked) => {
    let _shelfState = checked ? 'YES' : 'NO';
    // if(_shelfState==='NO'){
    //   _shelfState = "YES";
    // }else{
    //   _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('已取消展示');
        }
        this.props.changeShelfState(index, _shelfState);
      }
    });
  };
  // 删除视频课
  handleDeleteGraphicsCourse = (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 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='graphicsClass'
        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='video-course-list'>
        <XMTable
          renderEmpty={{
            image: college,
            description: '暂无数据',
          }}
          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}
          />
        )}
        {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 GraphicsCourseList;
