import React from 'react';
import { withRouter } from "react-router-dom";
import { Form, Input, Button, Modal, message} from 'antd';
import SelectPrepareFileModal from '@/modules/prepare-lesson/modal/SelectPrepareFileModal';
import Upload from '@/core/upload';
import StoreService from "@/domains/store-domain/storeService";
import User from "@/common/js/user";
import Bus from '@/core/tbus';
import "./CollegeInfoPage.less";
let cutFlag = false;
class CollegeInfoPage extends React.Component {
  formRef = React.createRef();
  constructor(props) {
    super(props);
    this.state = {
      storeName:null,
      logo:'',
      showSelectFileModal:false,
      cutImageBlob: null,
    }
  }
  componentWillMount() {
    if (User.getEnterpriseId()) {
      this.getStoreDetail()
    } else {
      window.RCHistory.replace('/store-info')
    }
  }
  getStoreDetail = ()=>{
    const params= {
      storeId:User.getStoreId()
    }
    StoreService.getStoreDetail(params).then((res) => {
      const { result = { } } = res;
      const {
        storeName,
        logo
      } = result;
      this.formRef.current.setFieldsValue({
        storeName:storeName
      });
      this.setState({
        storeName,
        logo
      })
    });
  }
  onChangeFiledValue=(filed,value)=>{
    this.setState({
      [filed]:value
    })
  }
  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.setState({
      logo:coverClicpPath
    })
  }
   // 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" });
  };
  updateInfo=()=>{
    const { storeName, logo } = this.state;
    if(!storeName){
      message.warning('请输入学院名称');
     return;
    }
    const params= {
      storeName,
      logo,
      storeId:User.getStoreId()
    }
    StoreService.updateStoreMessage(params).then((res) => {
      User.setStoreName(storeName);
      Bus.trigger('storeNameChange',storeName);
      message.success('保存成功');
    });
  }
  render() {
    const {
      storeName,
      showSelectFileModal,
      visible,
      hasImgReady,
      logo,
      cutImageBlob,
    } = this.state;
    return (
      <div className="page college-info-page">
        <div className="content-header">学院基本信息</div>
        <div className="box">
          <div className="college-info-header">学院基本信息</div>
          <div className="college-info-page-form">
           
            <Form ref={this.formRef}>
              <Form.Item
                label="学院LOGO"
              >
                <div className="logo-con">
                  <div className="logo-img-con">
                    { logo ?  <img src={logo}  className="logo-img"/> : <div className="logo-box"><span className="text">Logo</span></div>}
                  </div>
                  <div className="upload-box">
                    <span onClick={() => {this.setState({ showSelectFileModal:true  })}} className="upload-btn">
                      <span>上传</span>
                    </span>
                    <div className="tip">建议尺寸702*180px。最大2M，支持jpg、jpeg和png。</div>
                  </div>  
                </div>
              </Form.Item>
              <Form.Item
                label="学院名称"
                name="storeName"
                rules={[{ required: true}]}
              >
                <Input
                  value={storeName}
                  style={{ width: '300px' }}
                  placeholder="请输入学院名称"
                  onChange={(e) => this.onChangeFiledValue("storeName", e.target.value)}
                  maxLength={30}
                />
              </Form.Item>
          
            </Form>
          </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}
            />
          }
          <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><Button type="primary" onClick={this.updateInfo} htmlType="submit" className="submit-btn">更新信息</Button></div>
        </div>

      </div>
    )
  }
}

export default withRouter(CollegeInfoPage);