/*
 * @Author: 吴文洁 
 * @Date: 2020-07-15 17:29:12 
 * @Last Modified by: 吴文洁
 * @Last Modified time: 2020-07-15 18:16:05
 * @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 './AddLiveBasic.less';

const defaultCover = 'https://image.xiaomaiketang.com/xm/YNfi45JwFA.png';
const fieldNames  = { label: 'categoryName', value: 'id', children: 'sonCategoryList' };
let cutFlag = false;
class AddLiveBasic extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      imageFile: null,
      showCutModal: false,
      courseCatalogList:[],
      showSelectFileModal: false
    }
  }
  componentWillUnmount() {
  }
  componentDidMount(){
    this.getCourseCatalogList();
  }
  getCourseCatalogList = ()=>{
    StoreService.getCourseCatalogList({current:1,size:1000}).then((res) => {
        this.setState({
          courseCatalogList:res.result.records
        })
    });
  }
 
  // 上传封面图
  handleShowImgCutModal = (event) => {
    const imageFile = event.target.files[0];
    if (!imageFile) return;
    this.setState({
      imageFile,
      showCutModal: true,
    });
  }

  // 使用默认封面图
  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) => {
    console.log('111');
    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.uploadImage(file);

    // this.setState({
    //   showSelectFileModal: false
    // })
    // const { ossUrl, resourceId, folderName, folderFormat, folderSize } = file;
    // const coverObj = {
    //   contentType: 'COVER',
    //   mediaType: 'PICTURE',
    //   mediaContent: resourceId,
    //   mediaUrl: ossUrl,
    //   mediaName: folderName,
    //   size: folderSize
    // }
    // this.props.onChange('coverObj', coverObj);
  }
  //上传图片
  uploadImage = (imageFile) => {
    const { folderName } = imageFile;
    const fileName =
      window.random_string(16) + folderName.slice(folderName.lastIndexOf("."));
    this.setState(
      {
        visible: true,
      },
      () => {
        setTimeout(() => {
          const okBtnDom = document.querySelector("#headPicModal");
          const viewImgDom = document.querySelector('#preview-url-box');

          const options = {
            size: [297, 169],
            rotateFree: false,
            ok: okBtnDom,
            view: viewImgDom,
            maxZoom: 3,
            style: {
              jpgFillColor: "transparent",
            },
            done: (dataUrl) => {
              const cutImage = this.convertBase64UrlToBlob(dataUrl);
              this.getSignature(cutImage, fileName);
              setTimeout(() => {
                cutFlag = false;
              }, 2000);
            },
            fail: (failInfo) => {
            },
            loadComplete:(img)=>{
              this.refs.headPicModal.click();
              this.setState({
                previewUrl: img.src
              })
            }
          };
          if (!this.state.photoclip) {
            const photoclip = new PhotoClip("#headPicModal", options);
            photoclip.load(imageFile.ossUrl);
            console.log("photoclip-222",photoclip);
            this.setState({
              photoclip,
            });
          } else {
            this.state.photoclip.clear();
            this.state.photoclip.load(imageFile.ossUrl);
          }
        },200);
      }
    );
  };
   //获取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
      })
   
    });
  };
  // base64转换成blob
  convertBase64UrlToBlob = (urlData) => {
    const bytes = window.atob(urlData.split(",")[1]);
    const ab = new ArrayBuffer(bytes.length);
    const ia = new Uint8Array(ab);
    for (let i = 0; i < bytes.length; i++) {
      ia[i] = bytes.charCodeAt(i);
    }
    return new Blob([ab], { type: "image/png" });
  };
  updateCover = () =>{
    const {coverClicpPath,coverId} = this.state
    this.setState({
      showSelectFileModal: false
    })
    // const coverObj = {
    //   contentType: 'COVER',
    //   mediaType: 'PICTURE',
    //   mediaContent: coverClicpPath,
    // }
    // console.log("coverObj",coverObj);
    this.props.onChange('coverUrl', coverClicpPath);
    setTimeout(()=>{
      this.props.onChange('coverId', coverId);
    },1000)
  
  }
  render() {
    const { showCutModal, imageFile,courseCatalogList,showSelectFileModal,visible } = 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 className="opt-btns">
              {/* <input
                type="file"
                value={fileName} // 避免选择同一文件 value不改变 不触发onChange事件
                accept="image/png, image/jpeg, image/bmp, image/jpg"
                ref="stagePicInputFile"
                style={{display: 'none'}}
                onChange={() => {  this.setState({
                  showSelectFileModal: true
                }) }}
              /> */}

              <Button onClick={() => {
                this.setState({
                  showSelectFileModal: true
                })
              }}>上传图片</Button>
              <span
                className={`default-btn ${isDefaultCover ? 'disabled' : ''}`}
                onClick={this.handleResetCoverUrl}
              >使用默认图</span>
              <div className="tips">建议尺寸690*398像素，图片支持jpg、jpeg、png格式。</div>
            </div>
          </div>
        </div>
        <div className="course-catalog">
          <span className="label"><span className="require">*</span>课程分类：</span>
          { pageType === 'add' &&
            <Cascader defaultValue={[categoryName]} options={courseCatalogList} displayRender={	label => label.join('-')}  fieldNames={fieldNames} onChange={this.catalogChange} style={{ width: 240 }} placeholder="请选择课程分类" />
          }
          { (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="请选择课程分类" />
          }
        </div>
        <ImgCutModalNew
          title="裁剪"
          width={550}
          cutWidth={500}
          cutHeight={282}
          cutContentWidth={500}
          cutContentHeight={300}
          visible={showCutModal}
          imageFile={imageFile}
          bizCode='LIVE_COURSE_MEDIA'
          onOk={(urlStr, resourceId) => {
            this.setState({ showCutModal: false });
            this.props.onChange('coverId', resourceId, urlStr);
            this.state.currentInputFile.value = '';
          }}
          onClose={() => this.setState({ showCutModal: false })}
          reUpload={() => { this.state.currentInputFile.click() }}
        />

        <SelectPrepareFileModal
          operateType="select"
          accept="video/mp4,image/jpeg,image/png,image/jpg"
          selectTypeList={['MP4', 'JPG', 'JPEG', 'PNG']}
          tooltip='支持文件类型：jpg、jpeg、png、mp4'
          isOpen={showSelectFileModal}
          onClose={() => {
            this.setState({ showSelectFileModal: false })
          }}
          onSelect={this.handleSelectCover}
        />
        <Modal
          title="设置图片"
          width={1080}
          visible={visible}
          maskClosable={false}
          onCancel={() => {
            this.setState({ visible: false });
          }}
          footer={[
            <Button
              key="back"
              onClick={() => {
                this.setState({ visible: false });
              }}
            >
              重新上传
            </Button>,
            <Button
              key="submit"
              type="primary"
              onClick={() => {
                if (!cutFlag) {
                  cutFlag = true;
                  this.refs.hiddenBtn.click();
                }
                this.setState({ visible: false });
                this.updateCover()
              }}
            >
              确定
            </Button>,
          ]}
        >
          <div className="clip-box">
            <div
              id="headPicModal"
              ref="headPicModal"
              style={{
                width: "500px",
                height: "430px",
                marginBottom: 0,
              }}
            ></div>
            <div id="clipBtn" style={{ display: "none" }} ref="hiddenBtn"></div>
            <div className="preview-img">
              <div className="title">效果预览</div>
              {/* <img src={previewUrl} alt="图片预览" className="preview-url" /> */}
              <div id="preview-url-box"></div>
            </div>
          </div>
        </Modal>
      </div>
    )
  }
}

export default AddLiveBasic;