import React from 'react';
import { Input, Button, Modal, message } from 'antd';
import Upload from '@/core/upload';
import SelectPrepareFileModal from '@/modules/prepare-lesson/modal/SelectPrepareFileModal';
import Service from "@/common/js/service";
import BaseService from "@/domains/basic-domain/baseService";
import User from "@/common/js/user";
import './CreateCollege.less';

let cutFlag = false;

export default class CreateCollege extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      avatar: 'https://image.xiaomaiketang.com/xm/rJeQaZxtc7.png',
      logo: 'https://image.xiaomaiketang.com/xm/HNHCAF6Fc2.png',
      name: '',
    };
  }

  componentDidMount() {
    const enterpriseId = User.getEnterpriseId();
    this.getEnterpriseUser(enterpriseId);
  }
  
  getEnterpriseUser(enterpriseId) {
    const params = {
      enterpriseId,
      userId: User.getUserId(),
    }
    BaseService.getEnterpriseUser(params).then((res) => {
      const { name, avatar } = res.result;
      this.setState({ name, avatar })
    });
  }

  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);
      }
    );
  };

  // 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" });
  };

  //获取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
    })
  }

  submit = () => {
    const { logo, collegeName } = this.state;
    const params = {
      enterpriseId: User.getEnterpriseId(),
      userId: User.getUserId(),
      logo,
      storeName: collegeName,
    }
    Service.Hades('public/hades/createStore', params).then((res) => {
      if (res.success) {
        window.RCHistory.push('/college-manage')
      }
    })
  }

  render() {
    const {
      avatar,
      name,
      collegeName,
      logo,
      showSelectFileModal,
      visible,
      hasImgReady,
      cutImageBlob,
    } = this.state;
    return (
      <div className="college-manage-page">
        <div className="college-header">
          <div className="box">
            <img className="box-image" src="https://image.xiaomaiketang.com/xm/HNHCAF6Fc2.png" />
            <div className="user">
              <img className="image" src={avatar} />
              <span className="name">{name}</span>
              <span
                className="logout"
                onClick={() => {
                  window.RCHistory.goBack();
                }}
              >退出</span>
            </div>
          </div>
        </div>
        <div className="create-box">
          <div className="image-box" onClick={() => {this.setState({ showSelectFileModal:true  })}}>
            <img className="image" src={logo} />
          </div>
          <span className="tip">建议尺寸702*180px，JPG/PNG格式，图片小于2M。</span>
          <Input
            className="input"
            placeholder="请输入学院名称"
            value={collegeName}
            onChange={(e) => {
              this.setState({ collegeName: e.target.value })
            }}
          ></Input>
          <Button
            className="button"
            type="primary"
            onClick={() => this.submit()}
          >确定创建</Button>
        </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>
          </div>
        </Modal>
      </div>
    )
  }
}