import React, { Component } from 'react';
import { connect } from 'dva';
import './less/set.less';
import { Alert, Form, Row, Col, Input, Button, AutoComplete, message, Tabs } from 'antd';

import { selectComAdmin, systemPlatNewsSendVerificationCode, systemPlatNewsVerificationCode } from "../../../services/api";

const FormItem = Form.Item;
const { TabPane } = Tabs;

@connect(state => ({
  profile: state.profile,
  legalRepPhone: state.global.companyInfo.legalRepPhone,
}))

@Form.create()


export default class SetBasic extends Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      administrator: '',
      index: 1,
      confirmDirty: false,
      autoCompleteResult: [],
      phoneValue: '',//验证测试，手机号
      phoneValueHiddenMiddle: '',//验证测试，手机号
      code: '',//测试验证啊，验证码
      getting: false,//获取验证码,判断是否正在获取中,true,正在获取中
      countDown: 60,//倒计时30秒
      textStatus: true,//true时显示“使用法人手机号进行验证”，false显示“使用主管理员手机号进行验证”
    };
  }

  componentWillMount = () => {
    this.getComAdmin();
    // this.setState({
    //   phoneValue: this.state.phoneValue.substring(0, 3) + "****" + this.state.phoneValue.substring(7, 11),
    // });
  };

  checkConfirm = (rule, value, callback) => {
    const form = this.props.form;
    if (value && this.state.confirmDirty) {
      form.validateFields(['confirm'], { force: true });
    }
    callback();
  };

  //获得企业管理员
  getComAdmin = () => {
    selectComAdmin({}).then((data) => {
      let phoneValueHiddenMiddle = data.data[0].mobilePhone;
      phoneValueHiddenMiddle = phoneValueHiddenMiddle.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
      //判断获取数据是否为空
      this.setState({
        administrator: data.data[0].name,
        phoneValue: data.data[0].mobilePhone,
        mainPhone:data.data[0].mobilePhone,
        phoneValueHiddenMiddle,
      });

    });
  };

  timerCount = () => {
    //防止重复计算
    if (this.state.countDown != 60) {
      return;
    }

    this.countDownTimeId = setInterval(() => {
      if (this.state.countDown > 0) {
        // console.log(this.state.countDown);
        this.setState((prevState) => ({
          countDown: prevState.countDown - 1
        }));
        if (this.state.countDown == 0) {
          this.setState({
            getting: false,
            countDown: 60,
          });
          clearInterval(this.countDownTimeId);
        }
      } else {
        clearInterval(this.countDownTimeId);
      }
    }, 1000);

  };

  componentWillUnmount = () => {
    //离开页面时候,清除计时器
    if (this.countDownTimeId != null || this.countDownTimeId != undefined) {
      clearInterval(this.countDownTimeId);
    }
  };

  // 验证码变化
  checkCode = () => {
    const disableStyle = {
      background: "#f7f7f7",
      marginLeft: 16,
      borderColor: '#d9d9d9'
    };
    const style = {
      marginLeft: 16
    };
    //验证通过,没有获取
    if (!this.state.getting) {
      return (<Button type="primary" style={style} onClick={this.onGetCode} >获取验证码</Button>);
      //验证通过,正在获取
    } else {
      this.timerCount();
      return (<Button type="primary"
        className="getValid"
        style={disableStyle}
        disabled
      >{this.state.countDown}S后重新发送</Button>);
    }
  };

  // 获取验证码
  onGetCode = () => {
    systemPlatNewsSendVerificationCode({ "mobile": this.state.phoneValue }).then((res) => {
      console.log('验证码是否发送成功:', res);
    }, (err) => {
      console.log('获取验证码错误信息:', err);
    });
    this.setState({
      getting: true,
    });
  };

  // 点击下一步
  handleSubmit = (e) => {
    e.preventDefault();
    this.props.form.validateFields((err, fieldsValue) => {
      if (!err) {
        systemPlatNewsVerificationCode({ "mobile": this.state.phoneValue, "code": fieldsValue['code'] }).then((data) => {
          console.log('验证码是否正确:', data);
          this.props.setRoute('SetSuccess');
        }, (error) => {
          console.log('验证码是否正确-error:', error);
          // message.error('请填写正确的验证码信息');
        });
      }
    });
  };

  render() {
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 },
        md: { span: 10 },
      },
    };

    const { getFieldDecorator,setFieldsValue } = this.props.form;
    const { previewVisible, previewImage, fileList } = this.state;

    return (
      <div className="set">
        <Tabs defaultActiveKey="1" >
          <TabPane tab="企业设置" key="1" >
            <Alert message="换绑主管理员账号，需要验证当前主管理员账号的身份。" type="warning" showIcon />
            <div className="set-form">
              <Form onSubmit={this.handleSubmit}>
                <FormItem
                  {...formItemLayout}
                  label="当前管理员"
                >
                  <span className="ant-form-text">{this.state.administrator}</span>
                </FormItem>
                <FormItem
                  {...formItemLayout}
                  label="手机号码"
                >
                  <div style={{ display: 'flex', flexFlow:'column' }}>
                    <div style={{ flex: 1 }}>
                      <Input className="set-input" disabled value={this.state.phoneValueHiddenMiddle} style={{ width: 400 }} />
                    </div>
                    <div>
                      {this.state.textStatus&&<span style={{color:'orange'}}>旧主管理员手机号无法接收短信?</span>}
                      <span style={{color:'#40a9ff',cursor:'pointer'}} onClick={()=>{
                        if(this.state.getting){
                          return message.warning("验证码正在发送，请稍后")
                        }
                        if(!this.props.legalRepPhone){
                          return message.warning("暂无法人手机号")
                        }
                        let phone = this.state.textStatus?this.props.legalRepPhone:this.state.mainPhone
                        this.setState({
                          phoneValueHiddenMiddle:phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2'),
                          textStatus:!this.state.textStatus,
                          phoneValue:phone
                        })
                      }}>{this.state.textStatus?'使用法人手机号进行验证':'返回使用主管理员手机号进行验证'}</span>
                    </div>
                  </div>
                </FormItem>
                <FormItem
                  {...formItemLayout}
                  label="验证码"
                >
                  <Row gutter={8}>
                    <Col span={13}>
                      {getFieldDecorator('code', {
                        rules: [{
                          pattern: /^[0-9]{6}$/, message: '请输入正确验证码!',
                        }, {
                          required: true, message: '请输入验证码',
                        }],
                      })(
                        <Input placeholder="请输入" maxLength={6} />
                      )}
                    </Col>
                    <Col span={11}>
                      {this.checkCode()}
                    </Col>
                  </Row>
                </FormItem>
                <FormItem
                  {...formItemLayout}
                  label=" "
                  colon={false}
                >
                  <Button size="large" type="primary" htmlType="submit">
                    下一步
                  </Button>
                </FormItem>
              </Form>
            </div>
          </TabPane>
        </Tabs>
      </div>
    );
  }
}

