/*
 * @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 PhotoClip from 'photoclip'

import './AddLiveBasic.less';

const defaultCover = 'https://image.xiaomaiketang.com/xm/YNfi45JwFA.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 // 图片是否上传成功
    }
  }
  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) => {
    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);
  }
 
   //上传图片
   uploadImage = (imageFile) => {
    const { folderName } = imageFile;
    const fileName =
    window.random_string(16) + folderName.slice(folderName.lastIndexOf("."));
    const self = this;
    this.setState(
      {
        visible: true,
      },
      () => {
        setTimeout(() => {
          const okBtnDom = document.querySelector("#headPicModal");
          const options = {
            size: [500, 282],
            ok: okBtnDom,
            maxZoom: 3,
            style: {
              jpgFillColor: "transparent",
            },
            done: function (dataUrl) {
              clearTimeout(self.timer);
              self.timer = setTimeout(() => {
                if ((self.state.rotate != this.rotate()) || (self.state.scale != this.scale())) {
                  console.log(this.scale(), 'scale')
                  const _dataUrl = this.clip()
                  const cutImageBlob = self.convertBase64UrlToBlob(_dataUrl);
                  self.setState({
                    cutImageBlob,
                    dataUrl: _dataUrl,
                    rotate: this.rotate(),
                    scale: this.scale()
                  })
                }

              }, 500)

              const cutImageBlob = self.convertBase64UrlToBlob(dataUrl);
              self.setState({
                cutImageBlob,
                dataUrl
              })
              setTimeout(() => {
                cutFlag = false;
              }, 2000);
            },
            fail: (failInfo) => {
              message.error("图片上传失败了，请重新上传");
            },
            loadComplete: function (img) {
              setTimeout(() => {
                const _dataUrl = this.clip()
                self.setState({
                  dataUrl: _dataUrl,
                  hasImgReady: true 
                })
              }, 100)

            },
          };
          const imgUrl = `${imageFile.ossUrl}?${new Date().getTime()}`
          if (!this.state.photoclip) {
            const _photoclip = new PhotoClip("#headPicModal", options);
            _photoclip.load(imgUrl);
            this.setState({
              photoclip: _photoclip,
            });
          } else {
            this.state.photoclip.clear();
            this.state.photoclip.load(imgUrl);
          }

        }, 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,
        visible: false
      },()=>this.updateCover())
   
    });
  };
  // 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
    })
    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 className="opt-btns">
              <Button onClick={() => {
                this.setState({
                  showSelectFileModal: true
                })
              }}>上传图片</Button>
              <span
                className={`default-btn ${isDefaultCover ? 'disabled' : ''}`}
                onClick={this.handleResetCoverUrl}
              >使用默认图</span>
              <div className="tips">建议尺寸1280*720像素，图片支持jpg、jpeg、png格式。</div>
            </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>
        <ImgCutModalNew
          title="裁剪"
          width={530}
          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() }}
        />
        {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}
          />
        }
        <Modal
          title="设置图片"
          width={1080}
          visible={visible}
          maskClosable={false}
          closeIcon={<span className="icon iconfont modal-close-icon">&#xe6ef;</span>}
          onCancel={() => {
            this.setState({ visible: false });
          }}
          zIndex={10001}
          footer={[
            <Button
              key="back"
              onClick={() => {
                this.setState({ visible: false });
              }}
            >
              重新上传
            </Button>,
            <Button
              key="submit"
              type="primary"
              disabled={!hasImgReady}
              onClick={() => {
                if (!cutFlag) {
                  cutFlag = true;
                  this.refs.hiddenBtn.click();
                }
                this.getSignature(cutImageBlob);
              }}
            >
              确定
            </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" style={{width:500,height:282}}>
                <img src={this.state.dataUrl} style={{ width: '100%' }} alt="" />
              </div>
            </div>
          </div>
        </Modal>
      </div>
    )
  }
}

export default AddLiveBasic;