import React, { Component } from 'react';
import { connect } from 'dva';
import {
  Alert,
  Form,
  Row,
  Col,
  Input,
  Button,
  AutoComplete,
  message,
  Breadcrumb
} from 'antd';
import bcx_utils from '../../../common/bcx_utils';
import $perModal from '../../../utils/modal/perModal';
import {
  systemPlatNewsSendVerificationCode,
  systemPlatNewsVerificationCode,
  selectComAdmin,
  changeComAdmin
} from '../../../services/api';

import PartmentButton from '../../../components/PartmentButton';
import './less/set.less';

const FormItem = Form.Item;
const userdata = [
  {
    title: '测试一部',
    key: 'a',
    treeType: '1',
    clildren: [
      {
        title: '测试一部',
        key: '393412400792993801',
        treeType: '1',
        clildren: null
      },
      {
        title: '李四',
        key: '393412400792993802',
        treeType: '2',
        clildren: null
      },
      {
        title: '测试人员3',
        key: '394807930752335903',
        treeType: '2',
        clildren: null
      }
    ]
  },
  {
    title: '测试二部',
    key: 'b',
    treeType: '1',
    clildren: [
      {
        title: '测试一部',
        key: '395241451308449804',
        treeType: '2',
        clildren: null
      },
      {
        title: '李四',
        key: '393412400792993805',
        treeType: '2',
        clildren: null
      },
      {
        title: '测试人员3',
        key: '394807930752335906',
        treeType: '2',
        clildren: null
      }
    ]
  },
  {
    title: '测试三部',
    key: 'c',
    treeType: '1',
    clildren: [
      {
        title: '李娜',
        key: '394807930752335907',
        treeType: '2',
        clildren: null
      }
    ]
  },
  {
    title: '测试人员1',
    key: '394807930752335908',
    treeType: '2',
    clildren: null
  },
  {
    title: '测试人员2',
    key: '394807930752335909',
    treeType: '2',
    clildren: null
  },
  {
    title: '测试人员3',
    key: '3948079307523359010',
    treeType: '2',
    clildren: null
  }
];

@connect(state => ({
  profile: state.profile
}))
@Form.create()
export default class SetSuccess extends Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      administrator: '',
      index: 1,
      confirmDirty: false,
      autoCompleteResult: [],
      phoneValue: '', //验证测试，手机号
      code: '', //测试验证啊，验证码
      getting: false, //获取验证码,判断是否正在获取中,true,正在获取中
      countDown: 60, //倒计时30秒
      changeBeforePerId: '',//变更前管理员ID
      changeAfterPerId: '',//变更后管理员ID
    };
  }

  componentWillMount = () => {
    this.getComAdmin();
  };

  //获得企业管理员
  getComAdmin = () => {
    selectComAdmin({}).then((data) => {
      console.log("获得企业管理员", data);
      //判断获取数据是否为空
      this.setState({
        // phoneValue: data.data[0].userName,
        changeBeforePerId: data.data[0].perId,
      });

    });
  };

  // handleSubmit = e => {
  //   e.preventDefault();
  //   this.props.form.validateFieldsAndScroll((err, values) => {
  //     if (!err) {
  //       console.log('Received values of form: ', values);
  //     }
  //   });
  // };

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

  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 = () => {
    const mobile = this.state.phoneValue;
    if (!mobile) { return; }
    systemPlatNewsSendVerificationCode({ mobile }).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) {
      //   return;
      // }
      // const name = fieldsValue['username'];
      // if (rangeValue != this.state.code) {
      //   message.error('请填写正确的验证码信息');
      //   return;
      // } else {
      //   message.success(
      //     '已变更新管理员（' + name + this.state.phoneValue + '）'
      //   );
      // }

      if (!err) {
        // const { code } = fieldsValue['code'];
        const code = this.props.form.getFieldValue('code');
        const mobile = this.state.phoneValue;
        systemPlatNewsVerificationCode({ mobile, code })
          .then(res => {
            if (res.retType === '0') {
              console.log('手机号码未注册');

              bcx_utils.preventRepeatAsync(callback =>
                callback(resolve => {

                  const { changeBeforePerId, changeAfterPerId } = this.state;
                  console.log("changeBeforePerId", changeBeforePerId, changeAfterPerId);
                  changeComAdmin({ changeBeforePerId, changeAfterPerId }).then((data) => {
                    console.log("更改主管理员", data);
                    this.props.dispatch({
                      type: 'user/fetchCurrent'
                    });
                    resolve(false);
                    // //判断获取数据是否为空
                    // this.setState({
                    //   administrator: data.data[0].name,
                    //   phoneValue: data.data[0].userName,
                    // });

                  })
                    .catch(dd => {
                      resolve(false);
                      console.log(dd, 'dd');
                    });
                })
              );
            }
          })
          .catch(errs => {
            // message.error(aa);
            console.log(errs);
          });
      }
    });
  };

  setUrl = () => {
    console.log(this.props.setRoute('SetBasic'));
  };
  render() {
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 },
        md: { span: 10 }
      }
    };

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

    return (
      <div className="set">
        <Breadcrumb
          style={{
            margin: '10px 0px 10px 0px',
            paddingBottom: '10px',
            borderBottom: '1px solid #e8e8e8'
          }}
        >
          <Breadcrumb.Item>
            <a onClick={this.setUrl}> 企业设置 </a>
          </Breadcrumb.Item>
          <Breadcrumb.Item>新管理员设置</Breadcrumb.Item>
        </Breadcrumb>
        <Alert message="更换新管理员账号。" type="warning" showIcon />
        <div className="set-form">
          <Form onSubmit={this.handleSubmit}>
            <FormItem {...formItemLayout} label="新管理员姓名">
              {getFieldDecorator('username', {
                rules: [{ required: true, message: '请选择新管理员姓名!' }]
              })(
                <Input
                  placeholder="请选择"
                  onClick={() => {
                    $perModal({
                      title: "选择新管理员",
                      value: this.state.changeAfterPerId,
                      type: 'radio',
                      onOk: (value, close) => {
                        if(value[0]) {
                          this.setState({
                            changeAfterPerId: value[0].perId,
                            phoneValue: value[0].mobilePhone
                          });
                          
                          this.props.form.setFieldsValue({
                            username: value[0].name,
                          });
                        }
                        close();
                      }
                    });
                  }}
                  readOnly="true"
                />
              )}
            </FormItem>
            <FormItem {...formItemLayout} label="手机号码">
              {getFieldDecorator('phoneValue', {
                initialValue: this.state.phoneValue,
                rules: [
                  {
                    required: false
                  }
                ]
              })(
                <div style={{ display: 'flex' }}>
                  <div style={{ flex: 1 }}>
                    <Input className="set-input" disabled value={this.state.phoneValue} />
                  </div>
                  {this.checkCode()}
                </div>
              )}
            </FormItem>
            <FormItem {...formItemLayout} label="验证码">
              {getFieldDecorator('code', {
                rules: [
                  {
                    pattern: /^[0-9]{6}$/, message: '请输入正确验证码!',
                  },
                  {
                    required: true,
                    message: '请输入验证码'
                  }
                ]
              })(<Input placeholder="请输入" maxLength={6} />)}
            </FormItem>
            <FormItem {...formItemLayout} label=" " colon={false}>
              <Button size="large" type="primary" htmlType="submit">
                确认
              </Button>
            </FormItem>
          </Form>
        </div>
      </div>
    );
  }
}
