// 添加就诊人 --- 宝安人民医院
import React from 'react';
import { $http } from "containers/config/https";
import { createForm } from 'rc-form';
import { Modal, List, InputItem, Picker, Button, Toast } from 'antd-mobile';
import { Util } from 'tools';
import store from "store";
import registrationNo from "../../assets/images/registration-no.png"

import './style/index.less';

class NewAddPatient extends React.Component {
  constructor({ history }) {
    super();
    this.state = {
      cardType: [],
      selectData: {},
      cardTypeID: '',
      effectTime: 0,
      mobile: "",
      visible: false,
      improveInformation: false,
      cardDetails: {},
      interfaceSource: "",
      credTypeID: ""
    };
    this.history = history;
  }

  componentDidMount() {
    let interfaceSource = this.props.location && this.props.location.state ? this.props.location.state : "";
    this.setState({ interfaceSource }, () => {
      this.getSelectData(); // 获取下拉框接口数据
    })
  }

  componentWillUnmount() {
    this.setState = (state, callback) => {
      return;
    };
  }

  // 获取绑卡界面下拉框数据
  getSelectData = () => {
    let data = {
      params: [{}]
    }
    $http.post("urlS", this, {
      code: "01030011",
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          this.setState({ selectData: res, cardTypeID: res.cardType instanceof Array && res.cardType.length > 0 ? res.cardType[0].value : '' })
        }
      }
    });
  }

  // 身份证号验证
  handleVerificationIDCardNo = (rule, code, callback) => {
    let { credTypeID } = this.state;
    if (credTypeID !== "1" || !code) {
      callback();
      return;
    }
    //身份证号合法性验证
    //支持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();
  }

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

  // 获取验证码
  getVerificationCode = () => {
    let patMobile = this.props.form.getFieldValue("patMobile");
    if (patMobile && (/^1[3456789]\d{9}$/.test(patMobile.replace(/\s*/g, '')))) {
      this.setState({ effectTime: -1 })
      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.props.form.setFieldsValue({ verificationCode: undefined })
            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, 3, () => { }, false)
          })
        }
      });
    } else {
      this.setState({ effectTime: 0 }, () => {
        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);
    }
  }

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

  // 卡类型change事件
  handleCardTypeChange = (val) => {
    let credTypeID = val instanceof Array && val.length > 0 ? val[0] : val;
    this.setState({ credTypeID })
    // let obj = this.props.form.getFieldsValue();
    // let cardTypeID = val instanceof Array && val.length > 0 ? val[0] : val;
    // this.setState({ cardTypeID }, () => {
    //   if (obj.EContactCredTypeID[0] !== this.state.cardTypeID) {
    //     this.props.form.setFieldsValue({ patIDCardNo: undefined });
    //   }
    // })
  };

  // 绑卡
  handleBindCard = () => {
    let { improveInformation, cardDetails } = this.state;
    this.props.form.validateFields((error, values) => {
      if (!error) {
        if (!improveInformation) {
          this.getPatientInformation()
          return;
        } else {
          if (cardDetails.patName !== values.patName) {
            Toast.info("姓名不匹配，请重新输入。", 3, () => { }, false);
            return;
          }
          this.verifyPhoneNumber(values);
        }
      } else {
        console.log(error)
        Toast.info("请完善相关必填信息", 3, () => { }, false);
      }
    });
  }

  // 提交表单
  handleSubmit = (formData) => {
    let data = {
      params: [{
        ...formData,
        patMobile: Util.removeSpacesFromString(formData.patMobile),
        patSexID: formData && formData.sexID instanceof Array && formData.sexID.length > 0 ? formData.sexID[0] : "",
        patCredTypeID: formData && formData.EContactCredTypeID instanceof Array && formData.EContactCredTypeID.length > 0 ? formData.EContactCredTypeID[0] : ""
      }]
    }
    $http.post("urlS", this, {
      code: "01030004",
      data: data,
      success: function (res) {
        Toast.info(res.errorMessage, 3, () => { }, false)
        if (+res.errorCode === 0) {
          if (this.state.interfaceSource === "home") {
            let userData = localStorage.getItem("userData") ? JSON.parse(localStorage.getItem("userData")) : {};
            window.localStorage.setItem('userData', JSON.stringify({ ...userData, patID: res.result.patID }));
            this.history.push("/0001/00000001");
          } else {
            this.history.push("/0001/0001");
          }
          window.sessionStorage.setItem('admSelectData', []);
          store.dispatch({
            type: "isAddAdm",
            value: true
          });
        }
      },
      error: function (error) {
        Toast.info(error, 3, () => { }, false)
      }
    });
  }

  // 根据登记号获取就诊人信息
  getPatientInformation = () => {
    let { selectData } = this.state;
    let credTypeSelectData = selectData && selectData.credType ? selectData.credType : [];
    let patNo = this.props.form.getFieldValue("patNo");
    let patName = this.props.form.getFieldValue("patName");
    let data = {
      params: [{
        patNo,
        patName
      }]
    }
    $http.post("urlS", this, {
      code: "01020019",
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          this.props.form.setFieldsValue({ patName: res.result && res.result.patName ? res.result.patName : undefined });
          let credTypeID = res.result && res.result.credTypeID ? res.result.credTypeID + '' : credTypeSelectData[0].value
          this.setState({ improveInformation: true, cardDetails: res.result, credTypeID })
        } else {
          Toast.info(res.errorMessage, 3, () => { }, false);
        }
      },
      error: function (error) {
        Toast.info(error, 3, () => { }, false);
      }
    });
  }

  // 验证手机号
  verifyPhoneNumber = (formData) => {
    let data = {
      params: [{
        mobile: formData && formData.patMobile ? Util.removeSpacesFromString(formData.patMobile) : "",
        verifyCode: formData && formData.verificationCode ? Util.removeSpacesFromString(formData.verificationCode) : "",
      }]
    }
    $http.post("urlS", this, {
      code: "01020015",
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          this.handleSubmit(formData)
        } else {
          Toast.info(res.errorMessage, 3, () => { }, false);
        }
      },
      error: function (error) {
        console.log(error)
        // Toast.info(error, 3, () => { }, false);
      }
    });
  }

  handleShowGuide = () => {
    this.setState({ visible: true })
  }

  // 关闭指引弹出
  handleClose = () => {
    this.setState({ visible: false })
  }

  // 验证表单信息
  handleModileOnChange = () => {
    let { mobile } = this.state;
    let patMobile = this.props.form.getFieldValue("patMobile");
    if (patMobile !== mobile) {
      this.setState({ effectTime: 0 }, () => {
        clearInterval(this.countTimer);
      });
    }
  }

  render() {
    let { effectTime, visible, improveInformation, cardDetails, selectData } = this.state;
    const { getFieldProps, getFieldError } = this.props.form;
    let sex = selectData && selectData.sex ? selectData.sex : []; // 性别
    let credTypeSelectData = selectData && selectData.credType ? selectData.credType : [];
    // let cardTitle = cardTypeID === "1" ? "身份证" : (cardTypeID === "2" ? "就诊卡" : (cardTypeID === "3" ? "手机号" : (cardTypeID === "4" ? "病人ID" : "身份证")))
    return (
      <div className="new-add-patient">
        <form>
          <List>
            <InputItem
              error={!!getFieldError('patName')}
              placeholder="请输入就诊人的姓名"
              onErrorClick={() => {
                Toast.info(getFieldError('patName').join('、'), 3, () => { }, false);
              }}
              {...getFieldProps('patName', {
                initialValue: cardDetails && cardDetails.patName ? cardDetails.patName : undefined,
                rules: [
                  { required: true, message: '姓名不能为空' },
                ],
              })}
            >姓名</InputItem>
            <InputItem
              error={!!getFieldError('patNo')}
              type="number"
              placeholder="请输入就诊人登记号"
              onErrorClick={() => {
                Toast.info(getFieldError('patNo').join('、'), 3, () => { }, false);
              }}
              {...getFieldProps('patNo', {
                initialValue: cardDetails && cardDetails.patNo ? cardDetails.patNo : undefined,
                rules: [
                  { required: true, message: '登记号' },
                ],
              })}
            >登记号</InputItem>
            {improveInformation ? <Picker data={sex} cols={1}
              error={!!getFieldError('sexID')}
              onErrorClick={() => {
                Toast.info(getFieldError('sexID').join('、'), 3, () => { }, false);
              }}
              title="选择性别"
              {...getFieldProps('sexID', {
                onChange: this.handleVerification,
                initialValue: cardDetails && cardDetails.sexID ? [cardDetails.sexID + ''] : undefined,
                rules: [
                  { required: true, message: '请选择' },
                ],
              })}
            >
              <List.Item arrow="horizontal">性别</List.Item>
            </Picker> : ""}
            {improveInformation ? <div className="region-flex-basis">
              <Picker data={credTypeSelectData} cols={1}
                error={!!getFieldError('EContactCredTypeID')}
                onErrorClick={() => {
                  Toast.info(getFieldError('EContactCredTypeID').join('、'), 3, () => { }, false);
                }}
                title="选择证件类型"
                {...getFieldProps('EContactCredTypeID', {
                  onChange: this.handleCardTypeChange,
                  initialValue: cardDetails && cardDetails.credTypeID ? [cardDetails.credTypeID + ''] : [credTypeSelectData[0].value],
                  rules: [
                    { required: true, message: '请选择证件类型' },
                  ],
                })}
              >
                <List.Item arrow="horizontal">证件类型</List.Item>
              </Picker>
            </div> : ""}
            {improveInformation ? <InputItem
              error={!!getFieldError('patIDCardNo')}
              type="number"
              placeholder="请输入就诊人身份证号"
              onErrorClick={() => {
                Toast.info(getFieldError('patIDCardNo').join('、'), 3, () => { }, false);
              }}
              {...getFieldProps('patIDCardNo', {
                initialValue: cardDetails && cardDetails.idCardNo ? cardDetails.idCardNo : undefined,
                rules: [
                  { validator: this.handleVerificationIDCardNo }
                ],
              })}
            >身份证号</InputItem> : ""}
            {improveInformation ? <InputItem
              error={!!getFieldError('patMobile')}
              type="phone"
              placeholder="请输入就诊人手机号"
              onErrorClick={() => {
                Toast.info(getFieldError('patMobile').join('、'), 3, () => { }, false);
              }}
              {...getFieldProps('patMobile', {
                onChange: this.handleModileOnChange,
                initialValue: cardDetails && cardDetails.mobile ? Util.phoneAddGap(cardDetails.mobile) : undefined,
                rules: [
                  { validator: this.handleVerificationMobile }
                ],
              })}
            >手机号</InputItem> : ""}
            {improveInformation ? <InputItem
              error={!!getFieldError('verificationCode')}
              onErrorClick={() => {
                Toast.info(getFieldError('verificationCode').join('、'), 3, () => { }, false);
              }}
              {...getFieldProps('verificationCode', {
                initialValue: undefined,
                rules: [
                  { required: true, message: '请输入验证码' },
                ],
              })}
              // placeholder="0.00"
              extra={<span className={effectTime > 0 ? "font16" : "font12"} style={{ color: effectTime > 0 ? "#999" : "#0079FE" }}>{effectTime <= 0 ? (effectTime === -1 ? '获取中...' : <span onClick={this.getVerificationCode}>获取验证码</span>) : effectTime}</span>}
            >短信验证码</InputItem> : ""}
          </List>
          {/* <div style={{marginTop: '6px'}}>
            {improveInformation ? <InputItem
              error={!!getFieldError('EContact')}
              placeholder=""
              onErrorClick={() => {
                Toast.info(getFieldError('EContact').join('、'), 3, () => { }, false);
              }}
              {...getFieldProps('EContact', {
                initialValue: cardDetails && cardDetails.EContact ? cardDetails.EContact : undefined,
              })}
            >监护人姓名</InputItem> : ""}
            {improveInformation ? <InputItem
              error={!!getFieldError('EContactIDNo')}
              type="number"
              placeholder=" "
              onErrorClick={() => {
                Toast.info(getFieldError('EContactIDNo').join('、'), 3, () => { }, false);
              }}
              {...getFieldProps('EContactIDNo', {
                initialValue: cardDetails && cardDetails.EContactIDNo ? cardDetails.EContactIDNo : undefined,
              })}
            >监护人证件号</InputItem> : ""}
          </div> */}
          {!improveInformation ? <div className="nap-btn-guide">
            <span onClick={this.handleShowGuide}>不知道登记号是啥？</span>
          </div> : ""}
          <div className="nap-btn">
            <Button type="primary" onClick={this.handleBindCard}>{improveInformation ? '绑卡' : '查询'}</Button>
          </div>
        </form>
        <Modal
          visible={visible}
          onClose={this.handleClose}
          className="new-add-patient-modal"
          transparent
        >
          <div className="new-add-patient-modal-content">
            <h3>请使用登记号（下面红色框为绑定的卡号）</h3>
            <img src={registrationNo} alt="登记号" />
            <p>注：如绑定不成功，请核对卡号与姓名是否对应，如有信息错误或遗忘请去医院窗口修改。</p>
          </div>
          <Button type="primary" onClick={this.handleClose}>我知道了</Button>
        </Modal>
      </div>
    )
  }
};
const NewAddPatientForm = createForm()(NewAddPatient);
export default NewAddPatientForm;
