import React from 'react';
import { Input, Button, Switch, 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 {debounce} from 'underscore'
import './CreateCollege.less';
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, // 需要被截取的图片
      auditSwitch:true,
    };
    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} = 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')
        }
      })
    }
  }
  
  onChangeFiledValue = (filed, value) => {
    this.setState({
      [filed]: value,
    });
  };

  render() {
    const {

      collegeName,
      logo,
      visible,
      showError,
      imageFile,
      auditSwitch
    } = 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" alt=''/>
          </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} alt=''/>
            <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.Item label={<div className='label-box'>学员审核 <span className='icon iconfont icon-tip'>&#xe61d;</span></div>} name='auditSwitch' rules={[{ required: true }]}>
                <div className='switch-box'>
                  <Switch checked={auditSwitch } size='small'  onChange={(e) => this.onChangeFiledValue('auditSwitch', e)}/>
                  <Choose>
                    <When condition={auditSwitch}>
                      <div className='switch-desc'>已开启，成为学院学员需要审核</div>
                    </When>
                    <Otherwise>
                      <div className='switch-desc'>已关闭，成为学院学员不需要审核</div>
                    </Otherwise>
                  </Choose>
                </div>
              </Form.Item>
          </Form>
          <Button
            className="button"
            type="primary"
            onClick={debounce(() => this.submit(), 3000, {
              leading: true,
              trailing: false
            })}
          >确定创建</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>
    )
  }
}