// 基本信息
import React from 'react';
import { InputItem, Toast } from 'antd-mobile';
import { createForm } from 'rc-form';
import { Util } from 'tools';
import { $http } from "containers/config/https";

class EssentialInformation extends React.Component {
  constructor() {
    super();
    this.state = {
      errorData: {},
      locationData: {}, //传过来的数据
      effectTime: 0,
      mobile: "",
      loading: false
    };
    this.countTimer = null;
  }

  componentDidMount = () => {
    this.setState({ locationData: this.props.locationData })
    this.props.onRef(this)
  }

  componentWillUnmount() {
    clearInterval(this.countTimer); // 关闭定时器
    this.setState = (state, callback) => {
      return;
    };
  }

  // 重置倒计时时间
  modifyEffectTime = () => {
    this.setState({effectTime: 0})
  }

  // 获取form表单信息
  getFormData = () => {
    let obj = {}
    this.props.form.validateFields((error, values) => {
      if (!error) {
        obj = { ...values };
        obj.patMobile = obj.patMobile ? Util.removeSpacesFromString(obj.patMobile) : "";
        obj.errorCode = 0;
      } else {
        obj.errorCode = -100;
      }
    });
    return obj
  }

  // 验证表单信息
  handleVerification = (e, type) => {
    let {mobile} = this.state;
    setTimeout(() => {
      let obj = this.props.form.getFieldsValue();
      if (type === "patMobile"&&(obj.patMobile !== mobile)) {
        this.setState({ effectTime: 0 }, () => {
          clearInterval(this.countTimer);
        });
      }
      if (obj.patName && obj.patIDCardNo && obj.patMobile && obj.verificationCode) {
        this.props.handleNextStepStatus(false);
      } else {
        this.props.handleNextStepStatus(true);
      }
    })
  }

  // 身份证号验证
  handleVerificationIDCardNo = (rule, code, callback) => {
    //身份证号合法性验证
    //支持15位和18位身份证号
    //支持地址编码、出生日期、校验位验证
    var city = { 11: "北京", 12: "天津", 13: "河北", 14: "山西", 15: "内蒙古", 21: "辽宁", 22: "吉林", 23: "黑龙江 ", 31: "上海", 32: "江苏", 33: "浙江", 34: "安徽", 35: "福建", 36: "江西", 37: "山东", 41: "河南", 42: "湖北 ", 43: "湖南", 44: "广东", 45: "广西", 46: "海南", 50: "重庆", 51: "四川", 52: "贵州", 53: "云南", 54: "西藏 ", 61: "陕西", 62: "甘肃", 63: "青海", 64: "宁夏", 65: "新疆", 71: "台湾", 81: "香港", 82: "澳门", 91: "国外 " };
    if (!code || !/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|[xX])$/.test(code)) {
      callback(new Error("身份证号格式错误"));
      return;
    } else if (!city[code.substr(0, 2)]) {
      callback(new Error("身份证号地址编码错误"));
      return;
    } else {
      //18位身份证需要验证最后一位校验位
      if (code.length === 18) {
        code = code.split('');
        //∑(ai×Wi)(mod 11)
        //加权因子
        var factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
        //校验位
        var parity = [1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2];
        var sum = 0;
        var ai = 0;
        var wi = 0;
        for (var i = 0; i < 17; i++) {
          ai = code[i];
          wi = factor[i];
          sum += ai * wi;
        }
        if (String(parity[sum % 11]) !== String(code[17].toUpperCase())) {
          callback(new Error("身份证号校验位错误"));
          return;
        }
      }
    }
    callback();
  }

  // 点击显示错误信息
  onErrorClick = (key) => {
    let { errorData } = this.state;
    if (errorData[key]) {
      let errorMessage = errorData[key].errors[0].message;
      Toast.info(errorMessage, 3, () => {}, false);
    }
  }

  // 手机号验证
  handleVerificationMobile = (rule, value, callback) => {
    if (value && (/^1[3456789]\d{9}$/.test(value.replace(/\s*/g, '')))) {
      callback();
    } else {
      callback(new Error("手机号码有误，请重填"));
    }
  }

  // 获取验证码
  getVerificationCode = () => {
    this.setState({loading: true})
    let patMobile = this.props.form.getFieldValue("patMobile");
    if (patMobile && (/^1[3456789]\d{9}$/.test(patMobile.replace(/\s*/g, '')))) {
      let data = {
        params: [{
          mobile: Util.removeSpacesFromString(patMobile)
        }]
      }
      $http.post("urlS", this, {
        code: "01020014",
        data: data,
        success: function (res) {
          Toast.info(res.errorMessage, 3, () => {}, false);
          if (+res.errorCode === 0) {
            this.setState({mobile: patMobile, effectTime: res.result&&res.result.effectTime ? res.result.effectTime : 0, loading: false}, () => {
              this.countDown();
            });
          } else {
            this.setState({ effectTime: 0, loading: false });
          }
        },
        error: function (error) {
          this.setState({ effectTime: 0, loading: false }, () => {
            Toast.info(error, 3, () => {}, false)
          })
        }
      });
    } else {
      this.setState({ effectTime: 0, loading: false }, () => {
        Toast.info("请输入正确的手机号。", 3, () => {}, false);
      })
    }
  }

  // 验证倒计时
  countDown = () => {
    let {effectTime} = this.state;
    if (effectTime >= 0) {
      this.countTimer = setInterval(() => {
        let time = --effectTime
        this.setState({effectTime: time});
      }, 1000);
    } else {
      clearInterval(this.countTimer);
    }  
  }

  render() {
    let { locationData, effectTime, loading } = this.state;
    const { getFieldProps, getFieldError } = this.props.form;
    return (
      <div>
        <form>
          <InputItem
            error={!!getFieldError('patName')}
            onErrorClick={() => {
              Toast.info(getFieldError('patName').join('、'), 3, () => {}, false);
            }}
            {...getFieldProps('patName', {
              onChange: this.handleVerification,
              initialValue: locationData.patName ? locationData.patName : undefined,
              rules: [
                { required: true, message: '姓名不能为空' },
              ],
            })}
          >姓名</InputItem>
          <InputItem
            error={!!getFieldError('patIDCardNo')}
            onErrorClick={() => {
              Toast.info(getFieldError('patIDCardNo').join('、'), 3, () => {}, false);
            }}
            {...getFieldProps('patIDCardNo', {
              onChange: this.handleVerification,
              initialValue: locationData.IDCardNo ? locationData.IDCardNo : undefined,
              rules: [
                { validator: this.handleVerificationIDCardNo }
              ],
            })}
          // placeholder="0.00"
          // extra={<i className="iconfont icon-zhaoxiangji"></i>}
          >身份证号</InputItem>
          <InputItem
            error={!!getFieldError('patMobile')}
            onErrorClick={() => {
              Toast.info(getFieldError('patMobile').join('、'), 3, () => {}, false);
            }}
            {...getFieldProps('patMobile', {
              onChange: (e) => this.handleVerification(e, "patMobile"),
              initialValue: locationData.mobile ? Util.phoneAddGap(locationData.mobile) : undefined,
              rules: [{ validator: this.handleVerificationMobile }],
            })}
            type="phone"
            placeholder=""
          >手机号码</InputItem>
          <InputItem
            error={!!getFieldError('verificationCode')}
            onErrorClick={() => {
              Toast.info(getFieldError('verificationCode').join('、'), 3, () => {}, false);
            }}
            {...getFieldProps('verificationCode', {
              initialValue: undefined,
              onChange: this.handleVerification,
              rules: [
                { required: true, message: '请输入验证码' },
              ],
            })}
            // placeholder="0.00"
            extra={<span className={effectTime > 0 ? "font16" : "font12"} style={{ color: effectTime > 0 ? "#999" : "#0079FE"}}>{effectTime <= 0 ? (loading ? '获取中...' : <span onClick={this.getVerificationCode}>获取验证码</span>) : effectTime}</span>}
          >短信验证码</InputItem>
        </form>
      </div>
    )
  }
};
const EssentialInformationForm = createForm()(EssentialInformation);
export default EssentialInformationForm;
