// 添加家庭成员
import React from 'react';
import {InputItem, Toast, Button, Picker, List} from 'antd-mobile';
import { createForm } from 'rc-form';
import { $http } from "containers/config/https";
import {Util} from 'tools';
import './style/index.less';

class AddParient extends React.Component {
  constructor({history}) {
    super();
    let userData = localStorage.getItem("userData") ? JSON.parse(localStorage.getItem("userData")) : {};
    this.state = {
      userInfo: {},
      userData,
      mobile: "",
      effectTime: 0,
      selectData: {},
      iNSUNoreQuired: true
    };
    this.history = history;
    this.countTimer = null;
  }

  componentDidMount = () => {
    this.getSelectData();
    let userInfo = this.props.location&&this.props.location.state ? this.props.location.state : {};
    if (userInfo&&userInfo.ID) {
      document.title="修改家庭成员";
      this.setState({userInfo});
    } else {
      document.title="新增家庭成员";
    }
    
  }

	componentWillUnmount() { 
		// 组件销毁前将静止让setState修改state的状态
		this.setState = (state,callback)=>{ return; }
  }

  // 家庭成员界面初始化接口
  getSelectData = () => {
    let data = {
      params: []
    }
    $http.post("urlS", this, {
      code: "03070085",
      data,
      namespace: "HIS",
      success: function(res) {
        if (+res.errorCode === 0) {
          this.setState({selectData: res.result});
        } else {
          this.setState({selectData: {}});
        }
      }
    });
  }

  // 身份证号验证
  handleVerificationidCardNo = (rule, code, callback) => {
    //身份证号合法性验证
    //支持15位和18位身份证号
    //支持地址编码、出生日期、校验位验证
    if (!code) {
      callback();
      return;
    }
    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(!/^\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();
  }

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

  handleVerification = (type, e) => {
    setTimeout(() => {
      if (type === "iDCardNo"&&e&&e.length >= 16) {
        this.getAnalysisIdCard(e)
      }
    })
  }

  // 校验手机号
  // verifyCellPhoneNumber = (values) => {
  //   let data = {
  //     params: [{
  //       mobile: values&&values.mobile ? Util.removeSpacesFromString(values.mobile) : "",
  //       verifyCode: values&&values.verifyCode ? Util.removeSpacesFromString(values.verifyCode) : "",
  //     }]
  //   }
  //   $http.post("urlS", this, {
  //     code: "01020015",
  //     data: data,
  //     success: function (res) {
  //       if (+res.errorCode === 0) {
  //         this.setState({mobile: values.mobile})
  //         this.handleSubmit(values)
  //       } else {
  //         Toast.info(res.errorMessage);
  //       }
  //     },
  //     error: function (error) {
  //       Toast.info(error);
  //     }
  //   });
  // }

  handleSubmit = (values) => {
    console.log(values)
    let {userInfo, userData} = this.state;
    let formData = {
      params: [{
        ...values,
        ID: userInfo&&userInfo.ID ? userInfo.ID : "",
        sexID: values.sexID instanceof Array&&values.sexID.length > 0 ? values.sexID[0] : values.sexID,
        relationID: values.relationID instanceof Array&&values.relationID.length > 0 ? values.relationID[0] : values.relationID,
        iNSUTypeID: values.iNSUTypeID instanceof Array&&values.iNSUTypeID.length > 0 ? values.iNSUTypeID[0] : values.iNSUTypeID,
        classificationID: values.classificationID instanceof Array&&values.classificationID.length > 0 ? values.classificationID[0] : values.classificationID,
        phone: Util.removeSpacesFromString(values.phone),
        patID: userData&&userData.hisPatID ? userData.hisPatID : "",
        contactFlag: values.contactFlag ? "Y" : "N"
      }]
    }
    $http.post("urlS", this, {
      code: "03070008",
      data: formData,
      namespace: "HIS",
      success: function(res) {
        if (+res.errorCode === 0) {
          Toast.info(res.errorMessage, 3, () => {}, false);
          this.history.goBack();
        } else {
          Toast.info(res.errorMessage, 3, () => {}, false);
        }
      },
      error: function(error) {
        Toast.info(error, 3, () => {}, false);
      }
    });
  }

  // 保存
  handleSave = () => {
    this.props.form.validateFields((error, values) => {
      if (!error) {
        this.handleSubmit(values);
      } else {
        if (!values.name || !values.phone) {
          Toast.info("请完善相关信息。", 3, () => {}, false);
        } else if (!values.relationID) {
          Toast.info("请选择关系。", 3, () => {}, false);
        }
      }
    });
  }

  // 获取验证码
  // getVerificationCode = () => {
  //   let patMobile = this.props.form.getFieldValue("mobile");
  //   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);
  //         if (+res.errorCode === 0) {
  //           this.setState({mobile: patMobile, effectTime: res.result&&res.result.effectTime ? res.result.effectTime : 0}, () => {
  //             this.countDown();
  //           });
  //         } else {
  //           this.setState({ effectTime: 0 });
  //         }
  //       },
  //       error: function (error) {
  //         this.setState({ effectTime: 0 }, () => {
  //           Toast.info(error)
  //         })
  //       }
  //     });
  //   } else {
  //     this.setState({ effectTime: 0 }, () => {
  //       Toast.info("请输入正确的手机号。");
  //     })
  //   }
  // }

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

  // 根据身份证号获取性别年龄以及出生日期
  getAnalysisIdCard = (card) => {
    //获取性别
    if (parseInt(card.substr(16, 1)) % 2 === 1) {
      //男
      this.props.form.setFieldsValue({sexID: ['1']});
    } else {
      //女
      this.props.form.setFieldsValue({sexID: ['2']});
    }
  }

  iNSUTypeIDChange = e => {
    if (e instanceof Array&&e.length > 0) {
      this.setState({iNSUNoreQuired: e[0] === "1" ? false : true});
    }
  }

  render() {
    let {userInfo, selectData} = this.state;
    const { getFieldProps, getFieldError } = this.props.form;
    return (
      <div className="add-parient">
        <List>
          <form>
            <InputItem
              placeholder="家庭成员姓名"
              error={!!getFieldError('name')}
              onErrorClick={() => {
                Toast.info(getFieldError('name').join('、'), 3, () => {}, false);
              }}
              {...getFieldProps('name', {
                initialValue: userInfo&&userInfo.name ? userInfo.name : undefined,
                rules: [
                  { required: true, message: '请输入' },
                ],
              })}
            >姓名</InputItem>
            <InputItem
              placeholder="家庭成员身份证号"
              maxLength={18}
              // error={!!getFieldError('iDCardNo')}
              // onErrorClick={() => {
              //   Toast.info(getFieldError('iDCardNo').join('、'), 3, () => {}, false);
              // }}
              {...getFieldProps('iDCardNo', {
                initialValue: userInfo&&userInfo.iDCardNo ? userInfo.iDCardNo : undefined,
                onChange: (e) => this.handleVerification("iDCardNo", e),
                rules: [
                  { validator: this.handleVerificationidCardNo }
                ],
              })}
              // placeholder="0.00"
              // extra={<i className="iconfont icon-zhaoxiangji"></i>}
            >身份证号</InputItem>
            <InputItem
              placeholder="家庭成员手机号码"
              error={!!getFieldError('phone')}
              onErrorClick={() => {
                Toast.info(getFieldError('phone').join('、'), 3, () => {}, false);
              }}
              {...getFieldProps('phone', {
                initialValue: userInfo&&userInfo.phone ?  Util.phoneAddGap(userInfo.phone) : undefined,
                // onChange: (e) => this.handleVerification("phone", e),
                rules: [ 
                  { validator: this.handleVerificationMobile },
                ],
              })}
              type="phone"
              // placeholder="186 1234 1234"
            >手机号码</InputItem>
            {/* <InputItem
              error={!!getFieldError('verifyCode')}
              onErrorClick={() => {
                Toast.info(getFieldError('verifyCode').join('、'));
              }}
              {...getFieldProps('verifyCode', {
                initialValue: undefined,
                rules: [
                  { required: true, message: '请输入验证码' },
                ],
              })}
              // placeholder="0.00"
              extra={<span className={effectTime > 0 ? "font16" : "font12"} style={{ color: effectTime > 0 ? "#999" : "#0079FE"}}>{effectTime <= 0 ? <span onClick={this.getVerificationCode}>获取验证码</span> : effectTime}</span>}
            >短信验证码</InputItem> */}
            <Picker data={selectData&&selectData.sex ? selectData.sex : []} cols={1} 
              error={!!getFieldError('sexID')}
              onErrorClick={() => {
                Toast.info(getFieldError('sexID').join('、'), 3, () => {}, false);
              }}
              title="请选择性别"
              {...getFieldProps('sexID', {
                initialValue: userInfo&&userInfo.sexID ? [userInfo.sexID] : undefined,
              })}
            >
              <List.Item arrow="horizontal">性别</List.Item>
            </Picker>
            <Picker data={selectData&&selectData.relation ? selectData.relation : []} cols={1} 
              error={!!getFieldError('relationID')}
              onErrorClick={() => {
                Toast.info(getFieldError('relationID').join('、'), 3, () => {}, false);
              }}
              title="请选择关系"
              {...getFieldProps('relationID', {
                initialValue: userInfo&&userInfo.relationID ? [userInfo.relationID] : undefined,
                rules: [
                  { required: true, message: '请选择' },
                ],
              })}
            >
              <List.Item arrow="horizontal">关系</List.Item>
            </Picker>

            {/* <Picker data={selectData&&selectData.crowdClassifyData ? selectData.crowdClassifyData : []} cols={1} 
              error={!!getFieldError('classificationID')}
              onErrorClick={() => {
                Toast.info(getFieldError('classificationID').join('、'), 3, () => {}, false);
              }}
              title="请选择关系"
              {...getFieldProps('classificationID', {
                initialValue: userInfo&&userInfo.classificationID ? [userInfo.classificationID] : undefined,
                rules: [
                  { required: true, message: '请选择' },
                ],
              })}
            >
              <List.Item arrow="horizontal">人群分类</List.Item>
            </Picker>
            <Picker data={selectData&&selectData.healthCareTypeData ? selectData.healthCareTypeData : []} cols={1} 
              error={!!getFieldError('iNSUTypeID')}
              onErrorClick={() => {
                Toast.info(getFieldError('iNSUTypeID').join('、'), 3, () => {}, false);
              }}
              title="请选择关系"
              {...getFieldProps('iNSUTypeID', {
                initialValue: userInfo&&userInfo.iNSUTypeID ? [userInfo.iNSUTypeID] : undefined,
                onChange: this.iNSUTypeIDChange,
                rules: [
                  { required: true, message: '请选择' },
                ],
              })}
            >
              <List.Item arrow="horizontal">医保类型</List.Item>
            </Picker>
            <InputItem
              placeholder=""
              error={!!getFieldError('iNSUNo')}
              onErrorClick={() => {
                Toast.info(getFieldError('iNSUNo').join('、'), 3, () => {}, false);
              }}
              {...getFieldProps('iNSUNo', {
                initialValue: userInfo&&userInfo.iNSUNo ? userInfo.iNSUNo : undefined,
                rules: [
                  { required: iNSUNoreQuired, message: '请输入' },
                ],
              })}
            >医保卡号</InputItem> */}
            {/* <List.Item
              extra={<Switch
                {...getFieldProps('contactFlag', {
                  initialValue: userInfo&&userInfo.contactFlag === "Y" ? true : false,
                  valuePropName: 'checked',
                })}
                // onClick={(checked) => {
                //   // set new value
                //   this.props.form.setFieldsValue({
                //     Switch1: checked,
                //   });
                // }}
              />}
            >设为联系人</List.Item> */}
          </form>
        </List>
        <div className="ap-footer">
          <Button type="primary" onClick={this.handleSave} >保存</Button>
        </div>
      </div>
    )
  }
};
const AddParientForm = createForm()(AddParient);
export default AddParientForm;