/*
 * @Author: zhangleyuan
 * @Date: 2021-02-20 16:45:51
 * @LastEditors: zhangleyuan
 * @LastEditTime: 2021-03-27 11:20:27
 * @Description: 描述一下
 * @@Copyrigh: © 2020 杭州杰竞科技有限公司 版权所有
 */
import React from 'react';
import { Button,Input,Switch,Radio,Row,Col,Modal,message,Tooltip} from 'antd';
import { withRouter } from 'react-router-dom';
import SelectOperatorModal from '../modal/SelectOperatorModal';
import { ImgCutModalNew } from '@/components';
import SelectPrepareFileModal from '@/modules/prepare-lesson/modal/SelectPrepareFileModal';
import Upload from '@/core/upload';
// import PhotoClip from 'photoclip'
import './BasicInfo.less';


const { TextArea } = Input;
const defaultCover = 'https://image.xiaomaiketang.com/xm/YNfi45JwFA.png';
let cutFlag = false;
let timer = null
class BasicInfo extends React.Component{
  constructor(props) {
    super(props);
    this.state = {
      operatorModalVisible: false,
      showSelectFileModal:false,
      cutImageBlob: null
    };
  }


  handleShowSelectOperatorModal = () =>{
    this.setState({
      operatorModalVisible:true
    })
  }
  handleCloseSelectOperatorMOdal = ()=>{
    this.setState({
      operatorModalVisible:false
    })
  }
  handleConfirmSelectOperator = (selectOperatorList)=> {
    if(selectOperatorList.length === 0){
      message.warning('请选择运营师')
      return;
    }
    this.props.onChange('selectOperatorList',selectOperatorList);
    this.setState({
      operatorModalVisible:false
    })
  }
  enableStateChange = ()=> {
    if(this.props.data.enableState==="NO"){
      this.props.onChange('enableState','YES')
    }else{
      this.props.onChange('enableState','NO')
    }
  }
  
  // 使用默认封面图
  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)
  }
  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) => {
    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)
  }
   // 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" });
  };
  limitNumber = value => {
    if (typeof value === 'string') {
      return !isNaN(Number(value)) ? value.replace(/^(0+)|[^\d]/g, '') : ''
    } else if (typeof value === 'number') {
      return !isNaN(value) ? String(value).replace(/^(0+)|[^\d]/g, '') : ''
    } else {
      return ''
    }
  }
  percentCompleteBlur = (e,field) =>{
    let _percentCompleteLive;
    const { value } = e.target;
    if(value > 100){
      _percentCompleteLive = 100;
    }else{
      if(value < 0){
        _percentCompleteLive = 0;
      }else{
        _percentCompleteLive = value;
      }
    }
    this.props.onChange(field,_percentCompleteLive) 
  }
  
  render(){
    const { operatorModalVisible ,showSelectFileModal,visible,hasImgReady,cutImageBlob} = this.state;
    const { data} = this.props;
    const { planName,coverUrl,instro,enableState,operateType,selectOperatorList,percentCompleteLive,percentCompleteVideo,percentCompletePicture} = data;
    // 当前是否使用的是默认图片
    const isDefaultCover = coverUrl === defaultCover;
    return (
      <div className="plan-basic-info">
          <div className="plan-name">
              <span className="label"><span className="require">*</span>培训计划名称：</span>
              <Input
                  value={planName}
                  placeholder="请输入培训计划名称(20字以内)"
                  maxLength={20}
                  style={{ width: 240 }}
                  onChange={(e)=>this.props.onChange('planName', e.target.value)}
              />    
          </div>
          <div className="cover">
            <span className="label">封面图：</span>
            <div className="cover__wrap">
              <div className="img-content">
                { isDefaultCover &&
                  <span className="tag">默认图</span>
                }
                <img src={coverUrl} width="690"/>
              </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>
          <div className="introduction">
              <span className="label">简介：</span>
              <TextArea
                placeholder="请输入培训计划简介"
                maxLength={200}
                style={{ width: '552px',height:'110px'}}
                className="instro-textarea"
                value={instro}
                onChange={(e)=>this.props.onChange('instro', e.target.value)}
              />
          </div>
          <div className="wether-use">
            <span className="label">是否启用：</span>
            <div className="content">
              <div>
                <Switch checked={enableState==="YES"? true:false} onChange={()=> {this.enableStateChange()}}/>
              </div>  
              <div>
                <div className="instro-text">
                  <div>开启：此培训计划可以分享给用户进行学习</div>
                  <div>关闭：此培训计划暂不可分享给用户进行学习，后续可开启</div>
                </div>
              </div> 
            </div>
          </div>
          <div className="view-range" >
            <span className="label">
              <span className="require">*</span>
              可见范围
              <Tooltip 
                title="学院管理员、管理员默认都可见">
                <span className="iconfont">&#xe61d;</span>
              </Tooltip>：</span>
            <div className="content">
              <Radio.Group  value={operateType} onChange={(e) => { this.props.onChange('operateType', e.target.value) }}>
                <Row style={{ marginBottom: '5px' }}>
                  <Col span={24}>
                    <Radio value="All_Operate">
                      所有运营师 
                      <span className="playback__text">后续新增的运营师都有权限可见</span>
                    </Radio>
                  </Col>
                </Row>
                <Row>
                  <Col span={24}>
                    <Radio value="Assign_Operate">
                      指定运营师
                      <span className="playback__text">仅被选择的运营师有权限可见</span>
                    </Radio>
                  </Col>
                </Row>
              </Radio.Group>
              {operateType==="Assign_Operate" &&
                <div className="choose-business">
                 <Button onClick={()=>{this.handleShowSelectOperatorModal()}}>选择运营师</Button>
                 <span>已选择<span>{selectOperatorList.length}</span>名运营师</span>
                </div>
              }
            </div>
          </div>
          <div className="done-standard">
              <span className="label standard-label"><span className="require">*</span>完成标准：</span>
              <div>
                <div className="live-standard-info">
                  <span className="icon iconfont">&#xe865;</span>
                  <span className="instro">直播课单个课程，用户学习进度达到
                    <Input
                      width="40" 
                      value={percentCompleteLive} 
                      onChange={(e) => { this.props.onChange('percentCompleteLive', e.target.value.replace(/\D/g,'')) }} 
                      onBlur={(e)=>this.percentCompleteBlur(e,'percentCompleteLive')}
                      className="input-box"
                    />%，即视为"已完成"学习
                   
                  </span>
                </div>
                <div className="live-standard-info">
                  <span className="icon iconfont">&#xe864;</span>
                  <span className="instro">视频课单个课程，用户学习进度达到
                    <Input  
                      width="40" 
                      value={percentCompleteVideo} 
                      onChange={(e) => { this.props.onChange('percentCompleteVideo', e.target.value.replace(/\D/g,'')) }} 
                      onBlur={(e)=>this.percentCompleteBlur(e,'percentCompleteVideo')}
                      className="input-box"
                    />
                    %，即视为"已完成"学习
                  </span>
                </div>
                <div className="live-standard-info">
                  <span className="icon iconfont">&#xe601;</span>
                  <span className="instro">图文课单个课程，用户学习进度达到
                    <Input  
                      width="40" 
                      value={percentCompletePicture} 
                      onChange={(e) => { this.props.onChange('percentCompletePicture', e.target.value.replace(/\D/g,'')) }} 
                      onBlur={(e)=>this.percentCompleteBlur(e,'percentCompletePicture')}
                      className="input-box"
                    />
                    %，即视为"已完成"学习
                  </span>
                </div>
                {/* <div className="video-standard-info">
                  <span className="icon iconfont">&#xe864;</span>
                  <span>图文课单个课程，用户学习进度达到
                    <Input
                      width="40"
                      value={percentCompleteVideo} 
                      onChange={(e) => { this.props.onChange('percentCompleteVideo', e.target.value.replace(/\D/g,'')) }} 
                      onBlur={(e) => this.percentCompleteBlur(e, 'percentCompleteVideo')}
                      className="input-box"
                    />
                    %，即视为“已完成”学习
                  </span>
                </div> */}
              </div>  
          </div>
          { operatorModalVisible && 
            <SelectOperatorModal 
              visible={operatorModalVisible}
              onClose={this.handleCloseSelectOperatorMOdal}
              selectOperatorList={selectOperatorList}
              onSelect={this.handleConfirmSelectOperator}
            />
          }
          {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>
                <div id="preview-url-box" style={{width:500,height:282}}>
                  <img src={this.state.dataUrl} style={{ width: '100%' }} alt="" />
                </div>
                <div className="tip-box">
                  <div className="tip">温馨提示</div>
                  <div className="tip">①预览效果图时可能存在延迟，单击左侧图片刷新即可</div>
                  <div className="tip">②设置图片时双击可旋转图片，滚动可放大或缩小图片</div>
                </div>
              </div>
            </div>
          </Modal>
      </div>
    );
  }
}
export default withRouter(BasicInfo)
