import React, { PureComponent } from 'react';
import { connect } from 'dva';
// import { routerRedux, Link } from 'dva/router';
import {
  Form,
  Select,
  Input,
  Button,
  Row,
  Col,
  Cascader,
  Steps,
  message,
  Checkbox,
  Alert
} from 'antd';
import bcx_utils from '../../common/bcx_utils';
import {
  getDistrictData, //省市区选择
  publicCommonDictGetDictByCodeTypes, //公共信息
  systemRoleIsCharge, //联系人手机验证接口
  systemPlatNewsSendVerificationCode, //获取验证码接口
  systemPlatNewsVerificationCode, //验证短信验证码接口
  systemComBaseInfoSave, //注册接口
  publicCommonDictGetInstitutionTypeByIndustryType // 根据行业类型获取机构
} from '../../services/api';
import IconS from '../../components/IconS';
import PCascader from '../../components/Pro/PCascader';

import './EnterpriseRegistration.less';

const FormItem = Form.Item;
const { Option } = Select;
const { Step } = Steps;

@connect(state => ({
  register: state.register
}))
@Form.create()
export default class EnterpriseRegistration extends PureComponent {
  constructor(props, context) {
    super(props, context);
    this.state = {
      count: 0,
      // areas: [], //省市区
      industryType: [], //行业类型
      institutionType: [], //机构类型
      economicType: [], //经济类型
      comType: [], //企业类型
      currentInstitutionTypeValue: '' //机构类型所选择值，条件判断下面备注信息使用
    };
  }

  /******************************生命周期******************************/

  componentDidMount = () => {
    this.getAllType(); //获取所有类型
    // this.getDistrict(); //省市区选择
  };
  componentWillUnmount = () => {
    //this.interval && clearInterval(this.interval);
    clearInterval(this.interval);
  };
  /******************************ajax请求******************************/
  // //省市区
  // getDistrict = () => {
  //   getDistrictData().then(data => {
  //     const areas = data.data.map(val => {
  //       return {
  //         value: val.regionId,
  //         label: val.regionName,
  //         children: val.childs.map(valChild => {
  //           return {
  //             value: valChild.regionId,
  //             label: valChild.regionName,
  //             children: valChild.childs.map(valChildChild => {
  //               return {
  //                 value: valChildChild.regionId,
  //                 label: valChildChild.regionName
  //               };
  //             })
  //           };
  //         })
  //       };
  //     });
  //     this.setState({ areas });
  //   });
  // };

  //获取验证码
  getMobileVerificationCode = () => {
    const mobile = this.props.form.getFieldValue('mobile');
    if (!mobile || mobile === null) {
      message.error('联系手机不能为空！');
    }
    if (mobile && mobile !== null && mobile.length === 11) {
      systemRoleIsCharge({ mobile }).then(
        () => {
          let count = 59;
          this.setState({ count });
          this.interval = setInterval(() => {
            count -= 1;
            this.setState({ count });
            if (count === 0) {
              clearInterval(this.interval);
            }
          }, 1000);

          systemPlatNewsSendVerificationCode({ mobile }).then(
            res => {
              console.log('验证码是否发送成功:', res);
            },
            err => {
              console.log('获取验证码错误信息:', err);
            }
          );
        },
        err => {
          console.log('验证码处手机号码是否被注册:', err);
          // message.error("该手机已经注册成为个人用户,不能再注册");
          message.error(err);
        }
      );
    }
  };
  /******************************相关事件******************************/
  onGetCaptcha = () => {
    this.getMobileVerificationCode();
  };

  //获得行业类型,经济类型,机构类型,企业类型
  getAllType = () => {
    publicCommonDictGetDictByCodeTypes({
      codeTypes: ['industryType', 'economicType', 'comType']
    }).then(res => {
      //判断获取数据是否为空
      if (res.data) {
        const allTypeData = res.data;
        this.setState({
          industryType: allTypeData.industryType,
          economicType: allTypeData.economicType,
          // institutionType: allTypeData.institutionType,
          comType: allTypeData.comType
        });
      }
    });
  };

  //行业类型选择
  renderIndustry = () => {
    return this.state.industryType.map((val, key) => {
      return (
        <Option key={key} value={val.codeValue + ''}>
          {val.label}
        </Option>
      );
    });
  };
  // 根据行业类型获取机构
  changeIndustry = val => {
    const { setFieldsValue } = this.props.form;
    setFieldsValue({ institutionType: undefined });
    publicCommonDictGetInstitutionTypeByIndustryType({
      industryType: val
    }).then(res => {
      if (res.data) {
        this.setState({
          institutionType: res.data
        });
      }
    });
  };
  //机构类型选择
  renderInstitution = () => {
    return this.state.institutionType.map((val, key) => {
      return (
        <Option key={key} value={val.codeValue + ''}>
          {val.label}
        </Option>
      );
    });
  };

  //经济类型选择
  renderEconomic = () => {
    return this.state.economicType.map((val, key) => {
      return (
        <Option key={key} value={val.codeValue + ''}>
          {val.label}
        </Option>
      );
    });
  };

  //企业类型选择
  renderCompany = () => {
    return this.state.comType.map((val, key) => {
      return (
        <Option key={key} value={val.codeValue + ''}>
          {val.label}
        </Option>
      );
    });
  };

  handleSubmit = e => {
    e.preventDefault();

    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        const {
          comName,
          regAddress,
          economicType,
          industryType,
          comType,
          institutionType
        } = values;

        //验证手机号码是否被注册
        const mobile = this.props.form.getFieldValue('mobile');
        const code = this.props.form.getFieldValue('code');
        // const verificationCodeData = { mobile, code };

        if (mobile && mobile.length === 11) {
          systemPlatNewsVerificationCode({ mobile, code })
            .then(res => {
              if (res.retType === '0') {
                const residence = this.props.form.getFieldValue('residence');
                const legalRepPhone = this.props.form.getFieldValue('mobile');
                let regprovince;
                let regcity;
                let area;
                if (residence) {
                  [regprovince, regcity, area] = [
                    residence[0],
                    residence[1],
                    residence[2]
                  ];
                }
                const comBaseInfoDto = {
                  comName,
                  regProvince: regprovince,
                  regCity: regcity,
                  regArea: area,
                  regAddress,
                  economicType,
                  industryType,
                  comType,
                  institutionType,
                  legalRepPhone
                };
                bcx_utils.preventRepeatAsync(callback =>
                  callback(resolve => {
                    systemComBaseInfoSave(comBaseInfoDto)
                      .then(submitRes => {
                        resolve(false);
                        // message.success('注册成功！');
                        this.props.history.push(
                          `EnterpriseRegistrationResult?institution=${
                            this.state.currentInstitutionTypeValue
                          }`
                        );
                      })
                      .catch(dd => {
                        resolve(false);
                      });
                  })
                );
              }
            })
            .catch(errs => {
              // message.error(aa);
              console.log(errs);
            });
        }
      }
    });
  };

  /******************************render******************************/

  render() {
    const { count } = this.state;
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: {
        xs: { span: 6 },
        sm: { span: 6 }
      },
      wrapperCol: {
        xs: { span: 18 },
        sm: { span: 18 }
      }
    };
    const tailFormItemLayout = {
      wrapperCol: {
        xs: {
          span: 24,
          offset: 4
        },
        sm: {
          span: 20,
          offset: 4
        }
      }
    };

    return (
      <div className='EnterpriseRegistration'>
        <div className='enroll-header'>
          <div className='head-portrait'>
            <IconS type='logo-' />
            <span className='head-portrait-text'>
              <span style={{ fontSize: '18px' }}>百保盾</span>
              <br />
              <span style={{ fontSize: '12px' }}>改变工作 改变你</span>
            </span>
          </div>
          <div className='head-portrait-register'>
            <span
              style={{ cursor: 'pointer' }}
              onClick={() => this.props.history.push('LogOn')}
            >
              登录{' '}
            </span>
          </div>
        </div>
        <div className='enroll-content'>
          <div className='main'>
            <h3>企业注册</h3>
            <div
              className='progress-bar'
              style={{ marginLeft: '45px', marginRight: '36px' }}
            >
              <Steps>
                <Step title='填写注册资料' />
                <Step title='开始体验' />
              </Steps>
            </div>
            <Form onSubmit={this.handleSubmit} style={{ marginTop: '40px' }}>
              <FormItem {...formItemLayout} label='行业类型'>
                {getFieldDecorator('industryType', {
                  rules: [
                    {
                      required: true,
                      message: '请输入行业类型！'
                    }
                  ]
                })(
                  <Select
                    placeholder='请选择'
                    onSelect={val => this.changeIndustry(val)}
                  >
                    {this.renderIndustry()}
                  </Select>
                )}
              </FormItem>
              <FormItem {...formItemLayout} label='机构类型'>
                {getFieldDecorator('institutionType', {
                  rules: [
                    {
                      required: true,
                      message: '请输入机构类型！'
                    }
                  ]
                })(
                  <Select
                    onChange={value => {
                      this.setState({
                        currentInstitutionTypeValue: value
                      });
                    }}
                    placeholder='请选择'
                  >
                    {this.renderInstitution()}
                  </Select>
                )}
                {this.state.currentInstitutionTypeValue !== '0201' && (
                  <Alert
                    message='请确保⾏业及机构类型填写正确，提交后将不可修改。'
                    type='error'
                  />
                )}
                {this.state.currentInstitutionTypeValue === '0201' && (
                  <Alert
                    message='风评机构入驻需要公安机关的认可，否则将无法开通风险评估服务，有疑问请咨询400-662-9696。'
                    type='error'
                  />
                )}
              </FormItem>
              <FormItem {...formItemLayout} label='经济类型'>
                {getFieldDecorator('economicType', {
                  rules: [
                    {
                      required: true,
                      message: '请输入经济类型！'
                    }
                  ]
                })(
                  <Select placeholder='请选择'>{this.renderEconomic()}</Select>
                )}
              </FormItem>
              <FormItem {...formItemLayout} label='企业类型'>
                {getFieldDecorator('comType', {
                  rules: [
                    {
                      required: true,
                      message: '请输入企业类型！'
                    }
                  ]
                })(
                  <Select placeholder='请选择'>{this.renderCompany()}</Select>
                )}
              </FormItem>
              <FormItem {...formItemLayout} label='公司名称'>
                {getFieldDecorator('comName', {
                  rules: [
                    {
                      pattern: /^.{1,50}$/,
                      message: '最大50位!'
                    },
                    {
                      required: true,
                      message: '请输入公司名称！'
                    }
                  ]
                })(<Input placeholder='校验通过内容' maxLength={50} />)}
              </FormItem>
              <FormItem {...formItemLayout} label='注册地址'>
                {getFieldDecorator('residence', {
                  // initialValue: ['浙江', '杭州', '西湖'],
                  rules: [
                    {
                      type: 'array',
                      required: true,
                      message: '请选择你的注册地址!'
                    }
                  ]
                })(
                  // <Cascader
                  //   showSearch
                  //   options={this.state.areas}
                  //   placeholder='请选择'
                  // />
                  <PCascader showSearch placeholder="请选择"/>
                )}
              </FormItem>
              <FormItem {...formItemLayout} label='详细地址'>
                {getFieldDecorator('regAddress', {
                  rules: [
                    {
                      required: true,
                      message: '请输入详细地址！'
                    }
                  ]
                })(
                  <div>
                    <Input placeholder='请输入' maxLength={100} />
                  </div>
                )}
              </FormItem>
              <FormItem {...formItemLayout} label='管理员手机号'>
                <Row gutter={8}>
                  <Col span={24}>
                    {getFieldDecorator('mobile', {
                      rules: [
                        {
                          required: true,
                          message: '请输入联系手机！'
                        },
                        {
                          pattern: /^1[0-9]{10}$/,
                          message: '手机号格式错误！'
                        }
                      ]
                    })(
                      <div>
                        {/*<Input placeholder="请输入" maxLength={11} />*/}
                        <Input placeholder='请输入' maxLength={20} />
                      </div>
                    )}
                  </Col>
                </Row>
              </FormItem>
              <FormItem {...formItemLayout} label='验证码'>
                <Row gutter={8}>
                  <Col span={17}>
                    {getFieldDecorator('code', {
                      rules: [
                        {
                          pattern: /^[0-9]{6}$/,
                          message: '请输入正确验证码!'
                        },
                        {
                          required: true,
                          message: '请输入验证码!'
                        },
                        {
                          // validator: (rule, value, cb) => {
                          //     if (value === undefined) {
                          //         cb('手机号码不能为空');
                          //     } else if (!(/^1[3456789]\d{9}$/.test(value))) {
                          //         cb('请输入正确手机号码!');
                          //     }
                          //     cb();
                          // }
                        }
                      ]
                    })(
                      <div>
                        <Input placeholder='请输入' maxLength={6} />
                      </div>
                    )}
                  </Col>
                  <Col span={7}>
                    <Button
                      type='primary'
                      disabled={count}
                      className='getCaptcha'
                      onClick={this.onGetCaptcha}
                    >
                      {count ? `${count} s` : '获取验证码'}
                    </Button>
                  </Col>
                </Row>
              </FormItem>
              <FormItem {...tailFormItemLayout}>
                {getFieldDecorator('remember', {
                  rules: [
                    {
                      required: true,
                      message: '请同意协议'
                    }
                  ]
                })(
                  <div>
                    <Checkbox />
                    <span
                      style={{
                        marginTop: -38,
                        display: 'block',
                        marginLeft: 14
                      }}
                    >
                      勾选即同意
                      <a
                        className='login-form-forgot'
                        target='_blank'
                        onClick={() => {
                          if (window.top === window.self) {
                            const url = window.location.href.split('#')[0];
                            window.open(url + '#/user/UserAgreement', '_blank');
                          } else {
                            const url = window.location.href.split('#')[0];
                            window.top.location = url + '#/user/UserAgreement';
                          }
                        }}
                      >
                        《用户服务协议》
                      </a>
                      和
                      <a
                        className='login-form-forgot'
                        target='_blank'
                        onClick={() => {
                          if (window.top === window.self) {
                            const url = window.location.href.split('#')[0];
                            window.open(url + '#/user/UserPlicy', '_blank');
                          } else {
                            const url = window.location.href.split('#')[0];
                            window.top.location = url + '#/user/UserPlicy';
                          }
                        }}
                      >
                        《隐私策略》
                      </a>
                    </span>
                  </div>
                )}
              </FormItem>
              <FormItem {...tailFormItemLayout}>
                <Button
                  onClick={() => this.props.history.push('Enroll')}
                  style={{ marginRight: '16px' }}
                >
                  取消
                </Button>
                <Button className='submit' type='primary' htmlType='submit'>
                  确定
                </Button>
                {/* <Link className="login" to="/user/login">使用已有账户登录</Link> */}
              </FormItem>
            </Form>
          </div>
        </div>
      </div>
    );
  }
}
