/*
 * @Author: 吴文洁
 * @Date: 2020-07-15 17:29:12
 * @Last Modified by: chenshu
 * @Last Modified time: 2021-03-29 16:19:49
 * @Description: 新建/编辑直播课-基本信息
 */

import React from 'react';
import { Input, Button, message, Cascader, Modal } from 'antd';
import UploadOss from '@/core/upload';
import { ImgCutModalNew } from '@/components';
import StoreService from '@/domains/store-domain/storeService';
import SelectPrepareFileModal from '@/modules/prepare-lesson/modal/SelectPrepareFileModal';
import Upload from '@/core/upload';
import Cropper from 'react-cropper';
import ImgClipModal from '@/components/ImgClipModal'
import 'cropperjs/dist/cropper.css';
import './AddLiveBasic.less';

const defaultCover = 'https://image.xiaomaiketang.com/xm/Yip2YtFDwH.png';
const fieldNames = { label: 'categoryName', value: 'id', children: 'sonCategoryList' };
let cutFlag = false;
let timer = null;
class AddLiveBasic extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      imageFile: null,
      showCutModal: false,
      courseCatalogList: [],
      showSelectFileModal: false,
      cutImageBlob: null,
      hasImgReady: false, // 图片是否上传成功
      cropperInstace:null
    }
  }
  componentWillUnmount() {}

  componentDidMount() {
    this.getCourseCatalogList();
  }
  getCourseCatalogList = () => {
    StoreService.getCourseCatalogList({ current: 1, size: 1000 }).then((res) => {
      this.setState({
        courseCatalogList: res.result.records,
      });
    });
  }
 
  // 使用默认封面图
  handleResetCoverUrl = () => {
    const {
      data: { coverUrl },
    } = this.props;
    const isDefaultCover = coverUrl === defaultCover;
    // 如果已经是默认图的话，不做任何任何处理
    if (isDefaultCover) return;
    message.success('已替换为默认图');
    this.props.onChange('coverUrl', defaultCover);
    setTimeout(() => {
      this.props.onChange('coverId', null);
    }, 1000);
  };

  catalogChange = (value) => {
    const changeValueLength = value.length;
    switch (changeValueLength) {
      case 1:
        this.props.onChange('categoryId', value[0]);
        break;
      case 2:
        this.props.onChange('categoryId', value[1]);
        break;
      default:
        this.props.onChange('categoryId', null);
        break;
    }
  };
  handleSelectCover = (file) => {
    this.setState({
      visible: true,
      imageFile:file
    }); 
  }
 


  //获取resourceId
  getSignature = (blob, fileName) => {
    const { choosedBannerId } = this.state;
    Upload.uploadBlobToOSS(blob, 'cover' + new Date().valueOf(), null, 'signInfo').then((signInfo) => {
      this.setState(
        {
          coverClicpPath: signInfo.fileUrl,
          coverId: signInfo.resourceId,
          visible: false,
        },
        () => this.updateCover()
      );
    });
  };
  updateCover = () =>{
    const {coverClicpPath,coverId} = this.state
    this.setState({
      showSelectFileModal: false,
    });
    this.props.onChange('coverUrl', coverClicpPath);
    setTimeout(() => {
      this.props.onChange('coverId', coverId);
    }, 1000);
  };
  render() {
    const { showCutModal, imageFile, courseCatalogList, showSelectFileModal, visible, cutImageBlob, hasImgReady } = this.state;
    const { data, pageType, isEdit } = this.props;
    const { courseName, categoryName, coverUrl } = data;
    const fileName = '';
    // 当前是否使用的是默认图片
    const isDefaultCover = coverUrl === defaultCover;
    return (
      <div className='add-live__basic-info'>
        <div className='course-name'>
          <span className='label'>
            <span className='require'>*</span>课程名称：
          </span>
          <Input
            value={courseName}
            placeholder='请输入直播名称(40字以内)'
            maxLength={40}
            style={{ width: 240 }}
            onChange={(e) => {
              this.props.onChange('courseName', e.target.value);
            }}
          />
        </div>
        <div className='course-cover'>
          <span className='label'>封面图：</span>

          <div className='course-cover__wrap'>
            
            <div className='img-content'>
              {isDefaultCover && <span className='tag'>默认图</span>}
              <img src={coverUrl} />
            </div>
          </div>
          <div className='opt-btns'>
              <Button
                onClick={() => {
                  this.setState({
                    showSelectFileModal: true,
                  });
                }}>
                上传图片
              </Button>
              <span className={`default-btn ${isDefaultCover ? 'disabled' : ''}`} onClick={this.handleResetCoverUrl}>
                使用默认图
              </span>
              <div className='tips'>建议尺寸1280*720px或16:9。封面图最大5M，支持jpg、jpeg和png。</div>
            </div>
        </div>
        <div className='course-catalog'>
          <span className='label'>
            <span className='require'>*</span>课程分类：
          </span>
          {pageType === 'add' && (
            <Cascader
              options={courseCatalogList}
              displayRender={(label) => label.join('-')}
              fieldNames={fieldNames}
              onChange={this.catalogChange}
              style={{ width: 240 }}
              placeholder='请选择课程分类'
              suffixIcon={
                <span className='icon iconfont' style={{ fontSize: '12px', color: '#BFBFBF' }}>
                  &#xe835;
                </span>
              }
            />
          )}
          {pageType === 'edit' && categoryName && (
            <Cascader
              disabled={!isEdit ? true : false}
              defaultValue={[categoryName]}
              options={courseCatalogList}
              displayRender={(label) => label.join('-')}
              fieldNames={fieldNames}
              onChange={this.catalogChange}
              style={{ width: 240 }}
              placeholder='请选择课程分类'
              suffixIcon={
                <span className='icon iconfont' style={{ fontSize: '12px', color: '#BFBFBF' }}>
                  &#xe835;
                </span>
              }
            />
          )}
        </div>
        {showSelectFileModal && 
          <SelectPrepareFileModal
            key='basic'
            operateType='select'
            multiple={false}
            accept='image/jpeg,image/png,image/jpg'
            selectTypeList={['JPG', 'JPEG', 'PNG']}
            tooltip='支持文件类型：jpg、jpeg、png'
            isOpen={showSelectFileModal}
            onClose={() => {
              this.setState({ showSelectFileModal: false });
            }}
            onSelect={this.handleSelectCover}
          />
        }
        { visible &&
          <ImgClipModal visible={visible} imgUrl={imageFile.ossUrl} onConfirm={this.getSignature} onClose={()=>{this.setState({ visible: false });}}/>
        }
      </div>
    );
  }
}

export default AddLiveBasic;
