import React, { Component } from "react";
import { message, Icon, Input, Form, Upload} from "antd";
import axios from 'axios'
import ModalWrapper from "../../courses/common/ModalWrapper"
import { City, getUploadActionUrl, getImageUrl, ImageLayerHook } from 'educoder'
import '../account/common.css'

import authImg from '../../../images/account/auth.png'
import jobImg from '../../../images/account/job.png'

const { TextArea } = Input;
const Dragger = Upload.Dragger;
function getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
}
function beforeUpload(file) {
  const isJPG = file.type === 'image/jpeg';
  if (!isJPG) {
    message.error('You can only upload JPG file!');
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error('Image must smaller than 2MB!');
  }
  return isJPG && isLt2M;
}
class RealNameCertificationModal extends Component{
  constructor(props){
    super(props);
    this.state={
    }
  }

  componentDidMount() {
    
  }
  setVisible = (visible) => {
    this.refs.modalWrapper.setVisible(visible)
  }

  onSendOk = () => {
    this.props.form.validateFieldsAndScroll((err, values) => {
      console.log(values);
      if(!err){
        let{imageUrl2}=this.state;
        let{current_user,basicInfo}=this.props;
        if(imageUrl2){
          let { certification } = this.props;
          if(certification == 1){
            // 实名认证
            let url = `/users/accounts/${current_user && current_user.login}/authentication_apply.json`
            axios.post((url),{
              name:basicInfo.name,
              id_number:values.credentials
            }).then((result)=>{
              if(result){
                this.props.showNotification("申请已提交，请等待审核!");
                this.props.getBasicInfo();
                this.setVisible(false);
              }
            }).catch((error)=>{
              console.log(error);
            })
          }else{
            // 职业认证
            let url = `/users/accounts/${current_user && current_user.login}/professional_auth_apply.json`
            axios.post((url),{
              school_id:basicInfo && basicInfo.school_id,
              department_id:basicInfo && basicInfo.department_id,
              identity:basicInfo && basicInfo.identity,
              extra:basicInfo && basicInfo.identity == "student" ? basicInfo.student_id:basicInfo.technical_title 
            }).then((result)=>{
              if(result){
                this.props.showNotification("申请已提交，请等待审核!");
                this.props.getBasicInfo();
                this.setVisible(false);
              }
            }).catch((error)=>{
              console.log(error);
            })
          }
        }else{
          this.props.showNotification("请先上传照片！");
        }
      }
    })
  }

  onOk = () => {
    const { course_lists, checkBoxValues } = this.state
    this.onSendOk()
  }

  handleChange = (info) => {
    if (info.file.status === 'uploading') {
      this.setState({ loading: true });
      return;
    }
    if (info.file.status === 'done') {
      // Get this url from response in real world.
      getBase64(info.file.originFileObj, imageUrl => this.setState({
        imageUrl,
        loading: false,
      }));
    }
  }
  handleChange2 = (info) => {
    if (info.file.status === 'uploading') {
      this.setState({ loading: true });
      return;
    }
    if (info.file.status === 'done') {
      // Get this url from response in real world.
      getBase64(info.file.originFileObj, imageUrl2 => this.setState({
        imageUrl2,
        loading: false,
      }));
    }
  }

  render(){
    const { course_lists, checkBoxValues, searchValue, loading, imageUrl, imageUrl2 } = this.state
    const { moduleName } = this.props
    const { getFieldDecorator } = this.props.form;
    let {certification}=this.props;
    
    const uploadProps2 = {
      name: 'image',
      data:{type:certification == 1 ? "real_name" : "professional"},      
      multiple: true,
      showUploadList: false,
      // https://newweb.educoder.net
      action: this.props.current_user ? `/api/users/accounts/${this.props.current_user.login}/auth_attachment.json` : '',
      className: 'idPic-uploader',
      onChange: this.handleChange2,
    };
    return(
      <ModalWrapper
        ref="modalWrapper"
        title={
          certification && certification==1? 
          <span><i className="iconfont icon-shenfenrenzheng font-18 color-blue mr5" style={{fontWeight:"normal"}}></i>实名认证</span>:
          <span><i className="iconfont icon-zhiyerenzheng font-18 color-blue mr5" style={{fontWeight:"normal"}}></i>职业认证</span>
        }
        {...this.props }
        onOk={this.onOk}
        okText="保存"
        className="applyForModal certificationModal courseNormalForm"
        bottomRender={
          certification && certification == 1?
          <div className="bottomRender">
            <p>认证须知：</p>
            <p>
              1.你需要准备有效的身份证正面（人像面）的证件照照片，请确保证件照片清晰可见，严禁PS；
            </p><p>
              2.我们将在你提交认证信息后的24小时（不包含节假日）内完成审核，审核结果将会以系统消息的形式发送给你； 
            </p><p>
              3.实名认证审核完成后，无法删除，请谨慎填写；
            </p><p>
              4.实名认证审核完成后，系统将自动发放500个金币作为奖励；
            </p><p>
              5.我们会确保你所提供的信息均处于严格的保密状态，不会泄露；
            </p><p>
              6.如存在恶意乱填写姓名，证件号，及上传与实名认证证件无关图片者，一经发现将冻结EduCoder账号。
            </p>
          </div>:
          <div className="bottomRender">
            <p>认证须知：</p>
            <p>
            1.根据职业上传相应的证件照：教师（教师证），专业人士（员工证）、学生（学生证），请确保证件照内容完整并且清晰可见，严禁PS；
            </p><p>
            2.我们将在你提交职业证信息后的24小时（不包含节假日）内完成审核，审核结果将会以系统消息的形式发送给你； 
            </p><p>
            3.职业认证审核完成后，无法删除，请谨慎填写；职业变更请选择重新认证；
            </p><p>
            4.职业认证审核完成后，系统将自动发放500个金币作为奖励；
            </p><p>
            5.我们会确保你所提供的信息均处于严格的保密状态，不会泄露；
            </p><p>
            6.如存在恶意乱填写姓名，学号，及上传与职业证件无关图片者，一经发现将冻结EduCoder账号。
            </p>
          </div>
          }
        >
        <style>{`
          .applyForModal .ant-form-item{
            margin-bottom:18px;
          }
          .applyForModal .ant-form-item-label {
            width: 100px;
            padding-right: 10px;
          }
          .applyForModal .ant-form-item-label label {
            color: #979797
          }          
          .applyForModal .ant-upload.ant-upload-drag .ant-upload {
            padding: 0px;
          }

          .certificationModal .ant-modal-body{
            padding:20px;
          }
          .certificationModal .formItemInline .ant-form-item-control-wrapper {
            width: 448px;
          }
          span.idPic-uploader {
            margin-right:20px;
            height:110px;
          }
          .idPic-uploader > .ant-upload {
            width: 160px;
            height: 110px;
          }
          .idPic-uploader .ant-upload.ant-upload-drag p.ant-upload-drag-icon {
            margin-bottom: 0px;
          }
          .idPic-uploader .ant-upload.ant-upload-drag p.ant-upload-drag-icon i{
            font-size:42px!important;
            color:#4B667F
          }
          .idPic-uploader .ant-upload.ant-upload-drag p.ant-upload-text a{
            font-size: 12px;
            color:#4B667F;
            border-bottom:1px solid #4B667F
          }
          .idPic-uploader .ant-upload.ant-upload-drag {
            padding: 0px;
            border:1px solid rgba(218,218,218,1)!important;
          }
          .idPic-uploader img {
            width:100%
          }
          .first_uploader {
            margin-left: 42px;
          }
          .certificationModal .marginauto{
            margin-top:20px!important;
          }
          .bottomRender {
            padding: 19px;
            background: rgb(245,245,245);
            margin-top: 20px;
            color: #656565;
          }

          span.idPic-uploader.demoImg {
            width:160px;
            background:rgba(240,240,240,1);
            border:1px solid rgba(218,218,218,1);
            border-radius:4px;
            padding:0px 5px;
            justify-content: center;
            align-items: center;
            display: -webkit-flex;
          }
          .formItemInline .ant-form-explain{
            position:absolute;
            bottom:-20px;
            left:0px;
            width:100%;
          }
        `}</style>
        <Form onSubmit={this.handleSubmit}>
          {
            certification && certification ==1 &&
            <Form.Item
              label="证件号："
              className="formItemInline"
            >
              {getFieldDecorator('credentials', {
                rules: [{
                  // initialValue: this.state.cityDefaultValue,
                  required: true, 
                  message: '请输入证件号',
                }],
              })(
                <Input placeholder="请输入证件号" ></Input>
              )}
            </Form.Item>
          }
          <div style={{ marginLeft: '18px' }}>
            <div>
              <span style={{color: '#999999'}}>{ certification && certification == 1 ? "身份证（人像面）上传":"职业证照片上传" }</span>
              <span style={{color: '#FF6800'}}>（png/jpg/bmp格式，不超过2MB）</span>
            </div>

            <div className="df mt20" style={{ justifyContent: 'center' }} >
              <span className="idPic-uploader demoImg">
                <img src={`${certification == 1 ? authImg : jobImg}`} alt="avatar" style={{ maxHeight: '110px'}}/>
              </span>
              <Dragger {...uploadProps2}>
                {imageUrl2 ? 
                  // <a href={imageUrl2} target="_blank" title="点击重新上传图片"></a>
                    <img src={imageUrl2} alt="avatar" style={{ maxHeight: '110px'}}/>
                   : 
                  <React.Fragment>
                    <p className="ant-upload-drag-icon">
                      <i className="iconfont icon-cuban2shangchuanyunduan" style={{color:"#4B667F",font:"42px"}}></i>
                    </p>
                    <p className="ant-upload-text mt20"><a>点击或拖拽上传图片</a></p>
                    {/* <p className="ant-upload-hint">Support for a single or bulk upload. Strictly prohibit from uploading company data or other band files</p> */}
                  </React.Fragment>
                }
              </Dragger>
            </div>
            <div className="df mt10 color-grey-9" style={{ justifyContent: 'center' }} >
              <span className="fl mr20 edu-txt-center" style={{width:"160px"}}>示例图片</span>
              <span className="fl edu-txt-center mr20" style={{width:"160px"}}>
                <ImageLayerHook parentSel={'#imageLayerBtn'} parentSel={'#imageLayerBtn'}
                ></ImageLayerHook>
                <a href="javascript:void(0)" id="imageLayerBtn" src={imageUrl || imageUrl2} className="color-orange" style={{borderBottom:"1px solid #ff6800"}}>查看大图</a>
                </span>
            </div>
          </div>

          
        </Form>
        

      </ModalWrapper>
    )
  }
}
const WrappedRealNameCertificationModal = Form.create({ name: 'RealNameCertificationModal' })(RealNameCertificationModal);

export default WrappedRealNameCertificationModal;


