import React from 'react';
import { Input, Button, Modal, message, Form } from 'antd';
import Upload from '@/core/upload';
import Service from "@/common/js/service";
import BaseService from "@/domains/basic-domain/baseService";
import User from "@/common/js/user";
import Breadcrumbs from "@/components/Breadcrumbs";
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/fe4NCjr7XF.png',
      name: '',
      enterpriseId: User.getEnterpriseId(),
    };
  }

  componentDidMount() {
    this.getEnterpriseUser();
  }
  
  getEnterpriseUser() {
    const { enterpriseId } = this.state;
    const params = {
      enterpriseId,
      userId: User.getUserId(),
    }
    BaseService.getEnterpriseUser(params).then((res) => {
      const { name, avatar, isAdmin } = res.result;
      if (!isAdmin) {
        message.error('你没有该权限');
        window.RCHistory.replace('/college-manage')
        return null;
      }
      this.setState({ name, avatar })
    });
  }

  handleSelectCover = (e) => {
    const imageFile = e.target.files[0];
    Upload.uploadBlobToOSS(imageFile, 'cover' + (new Date()).valueOf()).then((url) => {
      this.uploadImage({ folderName: imageFile.name, ossUrl: url });
    })
  }
  
  //上传图片
  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, 128],
            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())) {
                  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({
      logo:coverClicpPath
    })
  }

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

  render() {
    const {
      avatar,
      name,
      collegeName,
      logo,
      visible,
      hasImgReady,
      cutImageBlob,
      showError,
    } = 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/fe4NCjr7XF.png" />
          </div>
        </div>
        <div className="breadcrumb-wrap">
          <Breadcrumbs
            navList="创建企学院"
            goBack={() => {
              window.RCHistory.goBack();
            }}
          />
        </div>
        <div className="create-box">
          <div className="image-box">
            <img className="image" src="https://image.xiaomaiketang.com/xm/fe4NCjr7XF.png"/>
            <div className="image-mask">
              <span
                className="icon iconfont"
                onClick={() => this.refs.logoInput.click()}
              >&#xe6f5;</span>
              <span
                className="icon iconfont"
                onClick={() => {
                  this.setState({
                    logo: 'https://image.xiaomaiketang.com/xm/fe4NCjr7XF.png',
                    visible: false,
                  })
                }}
              >&#xe6f6;</span>
            </div>
          </div>
          <span className="tip">建议尺寸702*180px，JPG/PNG格式，图片小于2M。</span>
          <Form>
            <Form.Item validateStatus={showError ? 'error' : 'success'} help={showError ? '请输入学院名称' : ''}>
              <Input
                className="input"
                placeholder="请输入学院名称"
                maxLength={30}
                value={collegeName}
                onChange={(e) => {
                  this.setState({ collegeName: e.target.value, showError: false })
                }}
              ></Input>
            </Form.Item>
          </Form>
          <Button
            className="button"
            type="primary"
            onClick={() => this.submit()}
          >确定创建</Button>
        </div>
        <input
          type="file"
          accept="image/*"
          value={""}
          ref="logoInput"
          style={{ display: "none" }}
          onChange={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:128}}>
                <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>
    )
  }
}