/*
 * @Author: 吴文洁 
 * @Date: 2020-07-16 11:05:17 
 * @Last Modified by: 吴文洁
 * @Last Modified time: 2020-07-17 16:17:10
 * @Description: 添加直播-简介
 */

import React from 'react';
import { Input, message, Upload } from 'antd';
import _ from 'underscore';

import { randomString } from '@/domains/basic-domain/utils';
import Service from '@/common/js/service';

import EditorBox from '../components/EditorBox';

import './Introduction.less';

const { TextArea } = Input;

class Introduction extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
    }
  }

  // 删除简介
  handleDeleteIntro = (index) => {
    const { liveCourseMediaRequests } = this.props.data;

    liveCourseMediaRequests.splice(index, 1);
    this.props.onChange('liveCourseMediaRequests', liveCourseMediaRequests);
  }

  // 上移简介
  handleMoveUpIntro = (index) => {
    const { liveCourseMediaRequests } = this.props.data;
    const prevItem = liveCourseMediaRequests[index];
    const nextItem = liveCourseMediaRequests[index + 1];

    liveCourseMediaRequests.splice(index, 2, nextItem, prevItem);
    this.props.onChange('liveCourseMediaRequests', liveCourseMediaRequests);
  }

  // 下移简介
  handleMoveDownIntro = (index) => { 
    const { liveCourseMediaRequests } = this.props.data;
    const prevItem = liveCourseMediaRequests[index - 1];
    const nextItem = liveCourseMediaRequests[index];

    liveCourseMediaRequests.splice(index - 1, 2, nextItem, prevItem);
    this.props.onChange('liveCourseMediaRequests', liveCourseMediaRequests);
  }

  renderLittleIcon = (index) => {
    const { liveCourseMediaRequests } = this.props.data;
    return (
      <div className="little-icon">
        <span
          className="icon iconfont close"
          onClick={() => { this.handleDeleteIntro(index); }}
        ></span>

        {
          index > 0 &&
          <span
            className="icon iconfont"
            onClick={() => { this.handleMoveDownIntro(index); }}
          >&#xe6d1;</span>
        }
        {
          index !== liveCourseMediaRequests.length - 1 &&
          <span
            className="icon iconfont"
            onClick={() => { this.handleMoveUpIntro(index); }}
          >&#xe6cf;</span>
        }
      </div>
    )
  }

  handleChangeIntro = (index, value) => {
    const { liveCourseMediaRequests } = this.props.data;
    liveCourseMediaRequests[index].mediaContent = value;
    this.props.onChange('liveCourseMediaRequests', liveCourseMediaRequests);
  }

  handleAddIntroText = () => {
    const { liveCourseMediaRequests } = this.props.data;
    liveCourseMediaRequests.push({
      mediaType: 'TEXT',
      mediaContent: '',
      key: randomString(16)
    });

    this.props.onChange('liveCourseMediaRequests', liveCourseMediaRequests);
  }

  handleUpload = (Blob) => {
    // 最多添加九图片
    const { liveCourseMediaRequests } = this.props.data;
    const list = _.filter(liveCourseMediaRequests, (item) => {
      return item.mediaType === "PICTURE";
    });

    if (list.length > 8) {
      message.warning("最多添加9张图片");
      return;
    }

    const { instId } = window.currentUserInstInfo;
    const { name, size } = Blob;
    const resourceName = randomString(16) + name.slice(name.lastIndexOf('.'));
    const params = {
      resourceName,
      accessTypeEnum: 'PUBLIC',
      bizCode: 'LIVE_COURSE_MEDIA',
      instId: instId,
    }
    Service.Hades("public/apollo/commonOssAuthority", params).then((res) => {
      const { resourceId } = res.result;
      const signInfo = res.result;
    
      // 构建上传的表单
      const xhr = new XMLHttpRequest();
      const formData = new FormData();
      formData.append("OSSAccessKeyId", signInfo.accessId);
      formData.append("policy", signInfo.policy);
      formData.append("callback", signInfo.callback);
      formData.append("Signature", signInfo.signature);
      formData.append("key", signInfo.key);
      formData.append("file", Blob);
      formData.append("success_action_status", 200);
      xhr.open("POST", signInfo.host);
     
      xhr.onload = () => {
        liveCourseMediaRequests.push({
          size,
          mediaName: name,
          mediaContent: resourceId,
          mediaType: 'PICTURE',
          mediaUrl: window.URL.createObjectURL(Blob),
        });

        this.props.onChange('liveCourseMediaRequests', liveCourseMediaRequests);
      };
      xhr.onerror = () => {
        xhr.abort();
      };
      xhr.send(formData);
      this.setState({ xhr })
    });
  }

  componentWillUnmount() {
    const { xhr } = this.state;
    xhr && xhr.abort();
  }

  render() {
    const {
      iveScene,
      data: {
        introduction,
        label = '直播课简介',
        liveCourseMediaRequests = []
      },
    } = this.props;
    // 是否是互动班课
    const isInteractive = iveScene === 'interactive';

    return (
      <div className="add-live__intro-info">
        <span className="lable">{label}：</span>
        <div className="content">
          {
            isInteractive &&
            <TextArea
              value={introduction}
              placeholder="简单介绍下这次课吧"
              maxLength={200}
              style={{ width: 480 }}
              onChange={(e) => { this.props.onChange('introduction', e.target.value) }}
            />
          }

          <If condition={!isInteractive}>
            <div className="intro-list">
              {
                liveCourseMediaRequests.map((item, index) => {
                  if (item.mediaType === 'TEXT') {
                    return (
                      <div className="intro-list__item" key={item.key}>
                        <EditorBox

                          detail={{
                            content: item.mediaContent
                          }}
                          onChange={(val) => { this.handleChangeIntro(index, val)}}
                        />
                        { this.renderLittleIcon(index) }
                      </div> 
                    )
                  }

                  if (item.mediaType === 'PICTURE') {
                    return (
                      <div className="intro-list__item picture" key={index}>
                        <div className="img__wrap">
                          <img src={item.mediaUrl} alt="introImg" />
                        </div>
                        { this.renderLittleIcon(index) }
                      </div>
                    )
                  }

                  return item;
                })
              }
            </div>
            <div className="operate">
              <div className="operate__item" onClick={this.handleAddIntroText}>
                <span className="icon iconfont">&#xe760;</span>
                <span className="text">文字</span>
              </div>

              <Upload
                fileList={[]}
                accept="image/jpeg, image/png, image/jpg, image/gif"
                beforeUpload={(Blob) => {
                  this.handleUpload(Blob);
                  return false;
                }}
              >
                <div className="operate__item">
                  <span className="icon iconfont">&#xe74a;</span>
                  <span className="text">图片</span>
                </div>
              </Upload>
            </div>,
            <div className="tips">
              • 图片支持jpeg、jpg、png、gif格式
            </div>
          </If>
        </div>
      </div>
    )
  }
}

export default Introduction;
