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 ImgClipModal from '@/components/ImgClipModal'
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(),
      imageFile: null, // 需要被截取的图片
    };
    this.loginInputRef = React.createRef()
  }

  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.setState({
        visible: true,
        imageFile:{ folderName: imageFile.name, ossUrl: url }
      });
      // this.uploadImage({ folderName: imageFile.name, ossUrl: url });
    })
  }
  

  //获取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,
      imageFile
    } = 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={logo}/>
            <div className="image-mask">
              <span
                className="icon iconfont"
                onClick={() => this.loginInputRef.current.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={this.loginInputRef}
          style={{ display: "none" }}
          onChange={this.handleSelectCover}
        />
        { visible &&
          <ImgClipModal visible={visible} imgUrl={imageFile.ossUrl}  aspectRatio='125/32' cropBoxHeight='128' onConfirm={this.getSignature} onClose={()=>{this.setState({ visible: false });}}/>
        }
      </div>
    )
  }
}