/*
 * @Author: 吴文洁 
 * @Date: 2020-07-16 11:05:17 
 * @Last Modified by: mikey.zhaopeng
 * @Last Modified time: 2020-11-24 14:29:52
 * @Description: 添加直播-简介
 */

import React from 'react';
import { Input, message, Upload, Radio, Row, Col, Button, Popover, Switch } from 'antd';
import Service from '@/common/js/service';
import EditorBox from '../components/EditorBox';
import User from '@/common/js/user';
import UploadOss from '@/core/upload';
import './AddLiveIntro.less';
import SelectPrepareFileModal from '@/modules/prepare-lesson/modal/SelectPrepareFileModal';
import { DISK_MAP } from '@/common/constants/academic/lessonEnum';
import { ImgCutModalNew } from '@/components';


const { TextArea } = Input;
const defaultCover = 'https://xiaomai-image.oss-cn-hangzhou.aliyuncs.com/1599635741526.png';
class AddLiveIntro extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      warmUrl: defaultCover,
      showSelectFileModal: false,
      diskList: [],
      selectType:null
    }
  }

  // 上传封面图
  handleShowImgCutModal = (event) => {
    const imageFile = event.target.files[0];
    if (!imageFile) return;      
    this.setState({
      imageFile,
      showCutModal: true,
    });
  }

   // 选择暖场资源
   handleSelectVideo = (file) => {
    const { selectType } = this.state; 
    this.setState({
      showSelectFileModal: false
    })
    const { ossUrl, resourceId, folderName, folderFormat, folderSize } = file;
    if(selectType === 'WARMUP'){
      const liveCourseWarmMedia = {
        contentType: 'WARMUP',
        mediaType: folderFormat === 'MP4' ? 'VIDEO' : 'PICTURE',
        mediaContent: resourceId,
        mediaUrl: ossUrl,
        mediaName: folderName,
        size: folderSize
      }
      this.props.onChange('liveCourseWarmMedia', liveCourseWarmMedia);
    }else{
        // 最多添加九图片
        const { liveCourseMediaRequests } = this.props.data;

        const list = _.filter(liveCourseMediaRequests, (item) => {
          return item.mediaType == "PICTURE";
        });
        if (list.length > 8) {
          message.warning("最多添加9张图片");
          return;
        }
        liveCourseMediaRequests.push({
          contentType: 'INTRO',
          size: folderSize,
          mediaName: folderName,
          mediaContent: resourceId,
          mediaType: 'PICTURE',
          mediaUrl: ossUrl,
        });
        this.props.onChange('liveCourseMediaRequests', liveCourseMediaRequests);
    }
   
  }
  // 获取机构可见的磁盘
  // handleFetchDiskList = () => {
  //   axios.Apollo('public/apollo/getUserDisk', {}).then((res) => {
  //     const { result = [] } = res;
  //     const diskList = result.map((item) => {
  //       return {
  //         ...item,
  //         folderName: DISK_MAP[item.disk]
  //       }
  //     });
  //     this.setState({ diskList });
  //   });
  // }

  // 删除简介
  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, length) => {
    const { liveCourseMediaRequests } = this.props.data;
    liveCourseMediaRequests[index].mediaContent = value;
    liveCourseMediaRequests[index].mediaContentLength = length
    this.props.onChange('liveCourseMediaRequests', liveCourseMediaRequests);
  }

  handleAddIntroText = () => {
    const { liveCourseMediaRequests } = this.props.data;
    liveCourseMediaRequests.push({
      contentType:"INTRO",
      mediaType: 'TEXT',
      mediaContent: '',
      key: Math.random()
    });

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

  handleUpload = (Blob) => {
    this.setState({
      showSelectFileModal: true,
      selectType:'INTRO'
    })
    // 最多添加九图片
    // 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 = window.random_string(16) + name.slice(name.lastIndexOf('.'));
    // const params = {
    //   resourceName,
    //   accessTypeEnum: 'PUBLIC',
    //   bizCode: 'LIVE_COURSE_MEDIA',
    //   instId:User.getStoreId(),
    // }
    // Service.Hades("public/hades/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 })
    // });
  }
  whetherVisitorsJoinChange = ()=>{
    if(this.props.data.whetherVisitorsJoin==="NO"){
      this.props.onChange('whetherVisitorsJoin','YES')
    }else{
      this.props.onChange('whetherVisitorsJoin','NO')
    }
  }
  componentWillMount() {
    // this.handleFetchDiskList();
  }
  // componentWillUnmount() {
  //   const { xhr } = this.state;
  //   xhr && xhr.abort();
  // }

  render() {
    const {liveType, isXiaomai, isEdit, data: { introduction, needRecord,whetherVisitorsJoin,liveCourseMediaRequests = [], liveCourseWarmMedia = {} } } = this.props;
    const { showCutModal, warmUrl, showSelectFileModal, diskList, imageFile,selectType} = this.state
    console.log('liveCourseMediaRequests',liveCourseMediaRequests);
    return (
      <div className="add-live__intro-info">
        <div className="playback" >
          
          <span className="label"><span className="require">*</span>直播回放：</span>
          <div className="content">
            <Radio.Group value={needRecord} onChange={(e) => { this.props.onChange('needRecord', e.target.value) }}  disabled={!isEdit ? true: false}>
              <Row style={{ marginBottom: '5px' }}>
                <Col span={24}>
                  <Radio value="YES">
                    自动录制 
                    <span className="playback__text">系统自助进行全程直播录制</span>
                  </Radio>
                </Col>
              </Row>
              <Row>
                <Col span={8}>
                  <Radio value="NO">
                    手动录制
                    <span className="playback__text">讲师手动选择何时开始录制</span>
                  </Radio>
                </Col>
              </Row>
            </Radio.Group>
          </div>
        </div>
        <div className="allow-tourist-join">
          <span className="label">观看设置：</span>
          <div className="content">
            <div>
                <Switch checked={whetherVisitorsJoin==="YES"? true:false} onChange={this.whetherVisitorsJoinChange}/>
            </div>  
            <div>
              <div class="instro-text">
                <div>开启：允许未绑定手机号的用户进入直播间观看直播</div>
                <div>关闭：仅限绑定了手机号的用户可以进入直播间观看直播</div>
              </div>
            </div> 
          </div>
        </div>
        <div className="warmup">
            <span className="label">直播暖场图：</span>
            <div className="course-cover__wrap">
              <div className="img-content" style={ liveCourseWarmMedia.mediaUrl ? {background: '#000'} : {} }>
                <img src={liveCourseWarmMedia.mediaType === 'VIDEO' ? `${liveCourseWarmMedia.mediaUrl}?x-oss-process=video/snapshot,t_0,m_fast` : (liveCourseWarmMedia.mediaUrl ? liveCourseWarmMedia.mediaUrl : defaultCover )} />
                {
                  liveCourseWarmMedia.mediaUrl && 
                  <div className="img-delete-wrap">
                    <img src="https://xiaomai-image.oss-cn-hangzhou.aliyuncs.com/1600073872956.png" onClick={() => {
                      this.props.onChange('liveCourseWarmMedia', {});
                    }}/>
                  </div>
                }
              </div>
              <div className="opt-btns">
                <Button 
                  disabled={!isEdit}
                  onClick={() => {
                  this.setState({
                    showSelectFileModal: true,
                    selectType:'WARMUP'
                  })
                }}>上传图片/视频</Button>
               
                <div className="tips">
                  <div>建议尺寸1280*720px或16:9。图片最大5M，支持jpg、jpeg和png；视频最大500M，</div>
                  <div>支持mp4。</div>
                </div>

                <Popover content={
                  <div className="example-wrap">
                    <p className="title">直播间暖场图示例</p>
                    <p className="text">直播开始前，展示在直播间视频区域</p>
                    <img src='https://xiaomai-image.oss-cn-hangzhou.aliyuncs.com/1599644482652.png'></img>
                  </div>
                }>
                  <div className="checkExample">查看示例</div>
                </Popover>
              </div>
            
            </div>
        </div>
     
        
        <div className="introduce">
          <span className="label">直播简介：</span>
          <div className="content">
                <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, length) => { this.handleChangeIntro(index, val, length) }}
                            />
                            {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} />
                            </div>
                            {this.renderLittleIcon(index)}
                          </div>
                        )
                      }
                    })
                  }
                </div>
                <div className="operate">
                  <div className="operate__item" onClick={this.handleAddIntroText}>
                    <span className="icon iconfont">&#xe639;</span>
                    <span className="text">文字</span>
                  </div>
                  <div className="operate__item" onClick={this.handleUpload}>
                    <span className="icon iconfont">&#xe63b;</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">&#xe63b;</span>
                      <span className="text">图片</span>
                    </div>
                  </Upload> */}
                </div>
                <div className="tips">
                  • 图片支持jpeg、jpg、png、gif格式
              </div>
        
          </div>
        </div>
        {/* 选择暖场图文件弹窗 */}
        <SelectPrepareFileModal
          operateType="select"
          accept={selectType==="INTRO"?"image/jpeg,image/png,image/jpg":"video/mp4,image/jpeg,image/png,image/jpg"}
          selectTypeList={ selectType==="INTRO" ? ['JPG', 'JPEG', 'PNG']: ['MP4', 'JPG', 'JPEG', 'PNG'] }
          tooltip={ selectType==="INTRO"?'支持文件类型：jpg、jpeg、png':'支持文件类型：jpg、jpeg、png、mp4'}
          isOpen={showSelectFileModal}
          onClose={() => {
            this.setState({ showSelectFileModal: false })
          }}
          onSelect={this.handleSelectVideo}
        />
        
      </div>
    )
  }
}

export default AddLiveIntro;
