// 添加电子健康卡
import React from 'react';
import { List, Button, InputItem, Picker, Checkbox, Flex, Toast } from 'antd-mobile';
import { $http } from "containers/config/https";
import store from "store";
import { Util } from 'tools';
import './style/index.less';
import EssentialInformation from './component/EssentialInformation.jsx'; // 基本信息
import EmergencyContactInformation from './component/EmergencyContactInformation.jsx'; // 联系人
import OtherInformation from './component/OtherInformation.jsx'; // 其他信息
var setTime = null;
const AgreeItem = Checkbox.AgreeItem;

export default class BindingCard extends React.Component {
  constructor({ history }) {
    super();
    this.state = {
      tabActive: "left",
      district: [],
      childActive: "1",
      isShowContacts: false,
      newChildActive: 1, // 最新到的位置
      isNextStep: true, // 下一步是否为不可点
      formData: {}, // 所有表单数据
      agreeLeftCheckbox: false,
      agreeRightCheckbox: false,
      bindLeftCardDisabled: true,
      bindRightCardDisabled: true,
      selectData: {},
      admVisible: false,
      typeID: '',//卡类型
      InputItem: '',//卡号
      inputName: '',//名字
      showContact: false, //右是否显示联系人
      verificationCode:'', //验证码'
      sendState: true, //验证码可点状态
      verificationState: '', //验证码状态
      interfaceSource: ''
    }
    this.history = history;
  }

  componentDidMount() {
    let interfaceSource = this.props.location && this.props.location.state ? this.props.location.state : "";
    this.setState({interfaceSource}, () => {
      this.getSelectData(); // 获取下拉框接口数据
    })
    // var location = this.props.location;
    // if (location.state !== undefined) {
    //   if (location.state.tabActive === "right") {
    //     this.handleSpanChange(location.state.tabActive, "已有本院就诊卡")
    //   } else {
    //     this.handleSpanChange(location.state.tabActive, "无就诊卡")
    //   }
    // }
  }
  componentWillUnmount() {
    clearInterval(setTime); // 关闭定时器
    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, typeID: res.cardType ? [res.cardType[0].value] : '' })
        }
      }
    });
  }

  // 修改下一步操作状态
  handleNextStepStatus = (status) => {
    this.setState({ isNextStep: status })
  }

  // 点击无就诊卡
  handleSpanChange = (active) => {
    this.setState({ tabActive: active }, () => {

    })
  }

  // 查询是否有这个病人
  getHavePatient = (basicFormData) => {
    let data = {
      params: [{
        idCardNo:basicFormData.patIDCardNo,
        mobile:basicFormData&&basicFormData.patMobile ? Util.removeSpacesFromString(basicFormData.patMobile) : "",
        name:basicFormData.patName,
        verificationCode:basicFormData&&basicFormData.verificationCode ? Util.removeSpacesFromString(basicFormData.verificationCode) : ""
      }]
    }
    $http.post("urlS", this, {
      code: "01030008",
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          this.history.push("/0001/00010006"); // 跳转到绑卡成功界面
        }else if(+res.errorCode === 100){
          if (basicFormData.errorCode === 0) { // 如果验证成功
            this.verifyCellPhoneNumber(basicFormData)
          } else {
            Toast.info("请完善相关信息。", 3, () => {}, false)
          }
        }else {
          Toast.info(res.errorMessage);
        }
      }
    });
  }

  // 下一步
  handleNextStep = () => {
    let { childActive } = this.state;
    if (childActive === "1") { // 为基本信息中的下一步
      let basicFormData = this.basicChild.getFormData();
      this.getHavePatient(basicFormData);
      // if (basicFormData.errorCode === 0) { // 如果验证成功
      //   this.verifyCellPhoneNumber(basicFormData)
      // } else {
      //   Toast.info("请完善相关信息。", 3, () => {}, false)
      // }
    } else if (childActive === "2") { // 紧急联系人的下一步
      let contactsFormData = this.contactsChild.getFormData();
      if (contactsFormData.errorCode === 0) { // 如果验证成功
        this.setState({ formData: { ...this.state.formData, ...contactsFormData }, childActive: "3", newChildActive: 3, isNextStep: true })
      } else {
        Toast.info("请完善相关信息。", 3, () => {}, false)
      }
    }
  }

  // 校验手机号
  verifyCellPhoneNumber = (basicFormData) => {
    let {childActive, newChildActive} = this.state;
    let data = {
      params: [{
        mobile: basicFormData&&basicFormData.patMobile ? Util.removeSpacesFromString(basicFormData.patMobile) : "",
        verifyCode: basicFormData&&basicFormData.verificationCode ? Util.removeSpacesFromString(basicFormData.verificationCode) : "",
      }]
    }
    $http.post("urlS", this, {
      code: "01020015",
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          this.setState({ formData: { ...basicFormData } });
          let age = Util.calculateAge(basicFormData && basicFormData.patIDCardNo ? basicFormData.patIDCardNo : "");
          if (age < 14) { // 如果年龄小于14岁则需要填写紧急联系人信息
            let isNextStep = +newChildActive > +childActive ? false : true;
            this.setState({ childActive: "2", newChildActive: 2, isShowContacts: true, isNextStep })
          } else {
            this.setState({ childActive: "3", newChildActive: 3, isShowContacts: false, isNextStep: true })
          }
        } else {
          Toast.info(res.errorMessage, 3, () => {}, false);
        }
      },
      error: function (error) {
        Toast.info(error, 3, () => {}, false);
      }
    });
  }

  // 通过页签跳转
  handleGotoNextStep = (tab) => {
    let { newChildActive } = this.state;
    if (parseInt(tab) <= newChildActive && (newChildActive !== 1)) {
      this.setState({ childActive: tab, isNextStep: false })
    } else {
      return
    }
  }

  validateDatePicker = (rule, date, callback) => {
    if (date && date.getMinutes() !== 15) {
      callback();
    } else {
      callback(new Error('15 is invalid'));
    }
  }

  // 跳转到关联电子健康卡
  handleGoAssociatedCard = () => {
    this.history.push("/0001/0019")
  }

  // 基本信息ref
  handleBasicRef = ref => {
    this.basicChild = ref;
  }

  // 联系人ref
  handleContactsRef = ref => {
    this.contactsChild = ref;
  }

  // 其他ref
  handleOtherRef = ref => {
    this.otherChild = ref;
  }

  // 同意并阅读
  handleCheckboxChange = e => {
    if (this.state.tabActive === "left") {
      this.setState({ agreeLeftCheckbox: e.target.checked }, () => {
        this.otherChild.handleVerification()
      })
    } else {
      this.setState({ agreeRightCheckbox: e.target.checked })
      if (this.state.typeID && this.state.InputItem && this.state.inputName) {
        this.setState({ bindRightCardDisabled: !e.target.checked })
      }else {
        this.setState({ bindRightCardDisabled: true })
      }
    }
  }

  // 修改绑卡按钮状态
  modifyBindCardButtoStatus = (status) => {
    let { tabActive, agreeLeftCheckbox, agreeRightCheckbox } = this.state;
    if (tabActive === "left") {
      if (agreeLeftCheckbox) {
        this.setState({ bindLeftCardDisabled: status })
      } else {
        this.setState({ bindLeftCardDisabled: true })
      }
    } else if (tabActive === "right" && agreeRightCheckbox) {
      this.setState({ bindRightCardDisabled: status })
    }
  }

  // 绑卡/立即绑卡
  handleBindCard = () => {
    let { tabActive, agreeLeftCheckbox, formData } = this.state;
    if (tabActive === "left") {
      let otherFormData = this.otherChild.getFormData();
      if (otherFormData.errorCode === 0 && agreeLeftCheckbox) { // 如果验证成功,则调用绑卡接口
        this.handleBindingCard({ ...formData, ...otherFormData })
      }
    } else if (tabActive === "right") {
      this.CaptchaCheck();
    }
  }

  // 绑卡
  handleBindingCard = (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) {
          let bingingData = {
            params: [{
              ...formData
            }]
          }
          $http.post("urlS", this, {
            code: "01030004",
            data: bingingData,
            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)
            }
          });
        } else {
          Toast.info(res.errorMessage, 3, () => {}, false);
        }
      },
      error: function (error) {
        Toast.info(error, 3, () => {}, false);
      }
    });

  };

  //验证验证码
  CaptchaCheck=()=>{
    let typeID = this.state.typeID&&this.state.typeID.length > 0 ? this.state.typeID[0] : "";
    if(typeID === "3"){
      if (!this.state.verificationCode) {
        Toast.info('验证码有误', 3, () => {}, false);
        return;
      }
      let data = {
        params: [{
          verifyCode:this.state.verificationCode,
          mobile: this.state.InputItem
        }]
      }
      $http.post("urlS", this, {
        code: "01020015",
        data: data,
        success: function (res) {
          if (+res.errorCode === 0) {
            clearInterval(setTime);
            this.setState({verificationState: false});
            this.immediatelyTiedCard()
          } else {
            Toast.info(res.errorMessage, 3, () => {}, false)
          }
        }
      });
    } else {
      this.immediatelyTiedCard();
    }
  }

  //立即绑卡
  immediatelyTiedCard = () => {
    let data = {
      params: [{
        cardTypeID: this.state.typeID ? this.state.typeID[0] : '',
        cardNo: this.state.InputItem,
        name: this.state.inputName,
        verificationCode: this.state.verificationCode
      }]
    }
    $http.post("urlS", this, {
      code: "01030008",
      data: data,
      success: function (res) {
        Toast.info(res.errorMessage, 3, () => {}, false)
        if (+res.errorCode === 0) {
          store.dispatch({
            type: "isAddAdm",
            value: true
          });
          this.history.goBack(); // 跳转到绑卡成功界面
        }
      }
    });
  };

  // 选择就诊卡类型
  handleSelectChange = (val) => {
    this.setState({ typeID: val[0] })
  };

  //卡类型id
  onOKData = (v) => {
    this.setState({ typeID: v, verificationCode: '' },()=>{
      if (this.state.typeID && this.state.InputItem && this.state.inputName&&this.state.agreeRightCheckbox) {
        this.setState({ bindRightCardDisabled: false })
      }else {
        this.setState({ bindRightCardDisabled: true })
      }
    });
    if (this.state.selectData.cardType) {
      let data = this.state.selectData.cardType.filter(item => item.value === v[0]);
      if (data.length > 0 && data[0].label === '手机号') {
        this.setState({
          showContact: true
        })
      } else {
        this.setState({
          showContact: false
        })
      }
    }
  };

  //卡号
  onChangeInputItem = (v) => {
    this.setState({ InputItem: v },()=>{
      if (this.state.typeID && this.state.InputItem && this.state.inputName&&this.state.agreeRightCheckbox) {
        this.setState({ bindRightCardDisabled: false })
      }else {
        this.setState({ bindRightCardDisabled: true })
      }
    })
  };

  //姓名
  onChangeName = (v) => {
    this.setState({ inputName: v },()=>{
      if (this.state.typeID && this.state.InputItem && this.state.inputName&&this.state.agreeRightCheckbox) {
        this.setState({ bindRightCardDisabled: false })
      }else {
        this.setState({ bindRightCardDisabled: true })
      }
    });
  };

  verificationCode = (v) => {
    this.setState({
      verificationCode: v
    },()=>{
      if (this.state.verificationCode && this.state.InputItem && this.state.inputName&&this.state.agreeRightCheckbox) {
        this.setState({ bindRightCardDisabled: false })
      }else {
        this.setState({ bindRightCardDisabled: true })
      }
    })
  };

  // 手机号验证
  handleVerificationMobile = (value,) => {
    if (value && (/^1[3456789]\d{9}$/.test(value.replace(/\s*/g, '')))) {
      return false;
    }else {
      return true
    }
  }

  //获取验证码验证
  sendVerification=()=>{
    if( this.handleVerificationMobile(this.state.InputItem)){
      Toast.info('手机号有误', 3, () => {}, false);
      return
    }
    if(this.state.sendState){
      // let a = 20;
      // setTime = setInterval(()=>{
      //   a--;
      //   if(a>0){
      //     this.setState({verificationState: a,sendState: false})
      //   }else {
      //     this.setState({verificationState: '',sendState: true});
      //     clearInterval(setTime)
      //   }
      // }, 1000)
      let data = {
        params: [{
          mobile:this.state.InputItem
        }]
      }
      $http.post("urlS", this, {
        code: "01020014",
        data: data,
        success: function(res) {
          if (+res.errorCode === 0) {
            let a = res.result ? res.result.effectTime : 60;
            setTime = setInterval(()=>{
              a--;
             if(a>0){
                this.setState({verificationState: a,sendState: false})
              }else {
                this.setState({verificationState: '',sendState: true});
                clearInterval(setTime)
              }
            }, 1000)
          }else {
            Toast.info(res.errorMessage, 3, () => {}, false)
          }
        }
      });
    }
  };

  render() {
    let { tabActive, childActive, isShowContacts, isNextStep, formData, agreeLeftCheckbox, agreeRightCheckbox, selectData, typeID, bindLeftCardDisabled, bindRightCardDisabled } = this.state;
    let cardType = selectData && selectData.cardType ? selectData.cardType : []; // 卡类型
    return (
      <div className="electronic-health-card">
        {/*<div className="margintop10 tabs-switch">*/}
          {/*<span className={tabActive === "left" ? "span-active span-left" : "span-left"} onClick={() => this.handleSpanChange("left", "无就诊卡")}>无就诊卡</span>*/}
          {/*<span className={tabActive === "right" ? "span-active span-right" : "span-right"} onClick={() => this.handleSpanChange("right", "已有本院就诊卡")}>已有本院就诊卡</span>*/}
        {/*</div>*/}
        <div className={childActive === "1" ? "binding-card top0" : "binding-card top0"}>
          <div className="margintop10 binding-form" style={{ display: tabActive === "left" ? "block" : "none" }}>
            <div className="binding-form-tabs">
              <span className={childActive === "1" ? "binding-form-tabs-active borderright" : "borderright"} onClick={() => this.handleGotoNextStep("1")}><i className="triangle-line"></i>基本信息</span>
              <span className={childActive === "2" ? "binding-form-tabs-active borderright borderleft" : "borderright borderleft"} style={{ display: isShowContacts ? "inline-block" : "none" }} onClick={() => this.handleGotoNextStep("2")}><i className="triangle-line"></i>联系人</span>
              <span className={childActive === "3" ? "binding-form-tabs-active borderright borderleft" : "borderright borderleft"} onClick={() => this.handleGotoNextStep("3")}><i className="triangle-line"></i>其他信息</span>
              <span className={childActive === "4" ? "binding-form-tabs-active borderleft" : "borderleft"}>成功</span>
            </div>
            <div>
              <List className="form-list font14">
                <div style={{ display: childActive === "1" ? "block" : "none" }}>
                  <EssentialInformation locationData={this.props.location.query ? this.props.location.query : {}} onRef={this.handleBasicRef} handleNextStepStatus={this.handleNextStepStatus} />
                </div>
                <div style={{ display: childActive === "2" ? "block" : "none" }}>
                  <div className="form-two-base">
                    <p>你正在添加的就诊人未满14岁，为保障就诊人权益，请添加紧急联系人信息</p>
                    <p>{formData && formData.patName ? formData.patName : "--"}</p>
                    <p>身份证：<span>{formData && formData.patIDCardNo ? formData.patIDCardNo : "--"}</span></p>
                  </div>
                  <EmergencyContactInformation onRef={this.handleContactsRef} handleNextStepStatus={this.handleNextStepStatus} selectData={selectData} />
                </div>
                <div style={{ display: childActive === "3" ? "block" : "none" }}>
                  <OtherInformation onRef={this.handleOtherRef} modifyBindCardButtoStatus={this.modifyBindCardButtoStatus} patIDCardNo={formData && formData.patIDCardNo ? formData.patIDCardNo : ""} selectData={selectData} />
                </div>
              </List>
            </div>
          </div>
          <div style={{ display: tabActive === "right" ? "block" : "none" }}>
            <List className="right-list">
              <InputItem
                placeholder="请输入"
                // ref={el => this.labelFocusInst = el}
                onChange={this.onChangeName}
              ><div>姓名</div></InputItem>
              <div className="select-input">
                <div className='select'>
                  <Picker
                      data={cardType}
                      value={typeID}
                      cols={1}
                      onOk={v => this.onOKData(v)}
                  >
                    <List.Item arrow="horizontal">卡类型</List.Item>
                  </Picker>
                </div>
                <div className='input'>
                  <InputItem
                    placeholder="请输入"
                    onChange={this.onChangeInputItem}
                  >
                  </InputItem>
                </div>
                {
                  this.state.showContact &&
                  <div className='verification'>
                    <InputItem
                        placeholder="请输入"
                        extra={<span className="font12" style={{color: "#0079FE"}} onClick={this.sendVerification}>{this.state.verificationState ? this.state.verificationState+'秒重新发送' : '获取验证码'}</span>}
                        onChange={this.verificationCode}
                    >短信验证码</InputItem>
                  </div>
                }
              </div>
            </List>
          </div>
        </div>
        <div className="binding-footer">
          <div className="form-agreement" style={{ display: (childActive === "3" || tabActive === "right") ? "block" : "none" }}>
            <Flex className="form-checkbox">
              <Flex.Item>
                <AgreeItem data-seed="logId" checked={tabActive === "left" ? agreeLeftCheckbox : agreeRightCheckbox} onChange={this.handleCheckboxChange}>
                  阅读并同意 <span style={{ cursor: "pointer" }}> 《用户协议》</span>
                </AgreeItem>
              </Flex.Item>
            </Flex>
            <Button type="primary" onClick={this.handleBindCard} disabled={tabActive === "left" ? bindLeftCardDisabled : bindRightCardDisabled}>{tabActive === "left" ? "绑卡" : "立即绑卡"}</Button>
          </div>
          <div className="padding0-18 marginbottom15" style={{ display: ((childActive === "1" || childActive === "2") && tabActive === "left") ? "block" : "none" }}>
            <Button type="primary" onClick={this.handleNextStep} disabled={isNextStep}>下一步</Button>
          </div>
          <span onClick={this.handleGoAssociatedCard}>已有健康卡，快速绑定</span>
        </div>
      </div>
    )
  }
};
