/*
 * @Description: 这是输入mobile和code页面，可用于登录、绑定
 * @Author: zhoupeng
 * @Date: 2020-04-22 15:29:53
 * @LastEditTime: 2020-07-22 18:48:54
 */

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Toast, List, Checkbox, Flex } from 'antd-mobile';

import router from 'umi/router';
import styles from './index.less';

import Config from '../../../utils/config';
import {
  mobileType,
  sysMobileNum,
  isMobileNumber,
  getQueryVariableBy,
} from '../../../utils/helper';
import { sendCode, loginByMobile, identical } from '../services/index';
import { goIndex, goScannerPage } from '../common/route';
//import { identical } from '../common/common';

// 倒计时
const NUM = 60;
const CheckboxItem = Checkbox.CheckboxItem;
const AgreeItem = Checkbox.AgreeItem;
@connect(({ mobileCodeModule }) => ({ ...mobileCodeModule }))
class Index extends Component {
  constructor(props) {
    super(props);
    this.state = {
      mobile: '',
      code: '',
      num: NUM,
      canTouch: true,
      canSubmit: false,

      loading: false,
      codeLoading: false,

      bindMobile: false, //是否让微信绑定手机号

      onlyLogin: false, //只做登录
    };
    this.timer = null;
    this.date = null;
  }

  componentDidMount = () => {
    console.log('this.props', this.props);
    console.info('-------------------/ckuh5/index');
    if (getQueryVariableBy(window.location.href, 'need') === 'noOpenId') {
      this.setState({
        onlyLogin: true,
      });
    }
  };
  componentWillUnmount() {
    this.timer && clearInterval(this.timer);
  }

  //通过Input修改state
  changeState = ({ stateType, e }) => {
    let value = e.target.value;

    if (!this.checkCanInput({ stateType, value })) {
      return;
    }
    this.setState(
      {
        [stateType]: value,
      },
      () => {
        this.checkSubmit();
      },
    );
  };

  //check是否可以提交了
  checkCanInput = ({ stateType, value }) => {
    if (stateType === 'mobile') {
      if (value && value.length > 11) {
        return false;
      }
      return true;
    }

    if (stateType === 'code') {
      if (value && value.length > 4) {
        return false;
      }
      return true;
    }
  };

  //check是否可以提交了
  checkSubmit = () => {
    const { code, mobile } = this.state;
    if (mobile && mobile.length === 11 && code && code.length === 4) {
      this.setState({
        canSubmit: true,
      });
    } else {
      this.setState({
        canSubmit: false,
      });
    }
  };

  //发送验证码
  sendCode = async () => {
    const { mobile } = this.state;

    //手机号合法性验证
    if (!isMobileNumber(mobile)) {
      Toast.info('手机号不合法', 1);
      return;
    }
    //开始发送验证码
    const params = {
      codeType: 1,
      mobile,
      mobileType,
      sysMobileNum,
    };

    this.setState({ codeLoading: true });
    const { rc, msg } = await sendCode({ ...params });
    if (rc === Config.constant.codeSuccess) {
      Toast.info('发送成功', 1);
      this.startTime();
    } else {
      Toast.info(msg, 1);
    }
    this.setState({ codeLoading: false });
  };

  //提交
  onSubmit = async () => {
    console.log('提交');
    const { code, mobile, bindMobile, onlyLogin } = this.state;

    //手机号合法性验证
    if (!isMobileNumber(mobile)) {
      Toast.info('手机号不合法', 1);
      return;
    }
    if (code && code.length !== 4) {
      Toast.info('验证码为4位数字', 1);
      return;
    }

    var openId = '';

    if (!getQueryVariableBy(window.location.href, 'need')) {
      openId = sessionStorage.getItem('openId');
    }
    if (!bindMobile) {
      openId = '';
    }

    const params = {
      code,
      codeType: 1,
      mobile,
      mobileType,
      sysMobileNum,
      openId: openId || '',
    };

    this.setState({ loading: true });
    const { rc, msg, data } = await loginByMobile({ ...params });

    if (rc === Config.constant.codeSuccess) {
      const ckuUserVo = data && data.thirdUser && data.thirdUser.cku ? data.thirdUser.cku : null;

      //没有cku账户,创建一个
      if (!ckuUserVo) {
        router.push(`/ckuh5/memberType?mobile=${mobile}&openId=${openId}`);
      } else {
        //1，查询会员和犬舍有效期是否相同 （拉平有效期）
        const { rc: identicalRc, msg: identicalMsg, data: identicalData } = await identical();
        if (!identicalRc) {
          if (identicalData && identicalData.requiredExpireIdentical) {
            router.replace('index');
            Toast.offline('查询会员和犬舍有效期不相同，请在APP中操作完成后，再登录', 5);
          } else {
            if (ckuUserVo.authentication === '0') {
              router.push('/ckuh5/authentication');
            } else {
              //存储用户信息
              window.sessionStorage.setItem(
                'access-user',
                ckuUserVo ? JSON.stringify(ckuUserVo) : JSON.stringify({}),
              );
              goScannerPage();
            }
          }
        } else {
          Toast.info('拉平接口有误', 1);
        }
      }
    } else {
      Toast.info(msg, 1);
    }
    this.setState({ loading: false });
  };

  //开始计时
  startTime = () => {
    this.setState({
      canTouch: false,
    });
    this.date = new Date().getTime();

    this.timer = setInterval(() => {
      const nowDate = new Date().getTime();

      const longTime = nowDate - this.date;
      const miao = parseInt(longTime / 1000);
      this.date = new Date().getTime();

      if (miao >= 3) {
        if (miao < this.state.num) {
          this.setState({
            num: this.state.num - miao,
          });
        } else {
          this.setState({
            canTouch: true,
            num: NUM,
          });

          this.timer && clearInterval(this.timer);
          this.timer = null;
          this.date = null;
        }
      } else {
        this.setState({
          num: this.state.num - 1,
        });
        if (this.state.num <= 0) {
          this.setState({
            canTouch: true,
            num: NUM,
          });

          this.timer && clearInterval(this.timer);
          this.timer = null;
          this.date = null;
        }
      }
    }, 1000);
  };

  onChangeMobile = () => {
    const { bindMobile } = this.state;
    this.setState({
      bindMobile: !bindMobile,
    });
  };

  //render发送验证码按钮
  renderCodeButton = () => {
    const { codeLoading, canTouch, num } = this.state;
    if (codeLoading) {
      return (
        <div className={styles.code_button}>
          <span className={styles.code_text_gray}>发送中···</span>
        </div>
      );
    }

    if (!canTouch) {
      return (
        <div className={styles.code_button}>
          <span className={styles.code_text_gray}>重新发送（{num}）</span>
        </div>
      );
    }

    return (
      <div className={styles.code_button} onClick={this.sendCode}>
        <span className={styles.code_text_blue}>发送验证码</span>
      </div>
    );
  };

  //render提交按钮
  renderSubmitButton = () => {
    const { loading, canSubmit } = this.state;

    if (loading) {
      return (
        <div
          className={`${styles.submit_button} ${styles.submit_button_gray}`}
          onClick={this.onSubmit}
        >
          <span>提交中···</span>
        </div>
      );
    }

    if (!canSubmit) {
      return (
        <div className={`${styles.submit_button} ${styles.submit_button_gray}`}>
          <span>提交</span>
        </div>
      );
    }
    return (
      <div
        className={`${styles.submit_button} ${styles.submit_button_blue}`}
        onClick={this.onSubmit}
      >
        <span>提交</span>
      </div>
    );
  };

  render() {
    const { mobile, code, onlyLogin } = this.state;
    const codeButton = this.renderCodeButton();
    return (
      <div className={styles.login}>
        <div className={styles.title_content}>{onlyLogin ? '手机号登录' : '手机号登录/注册'}</div>

        <div>
          <Input
            type="number"
            max={99999999999}
            min={10000000000}
            placeholder="请输入手机号码"
            value={mobile}
            onChange={e => {
              this.changeState({ stateType: 'mobile', e });
            }}
          ></Input>
        </div>

        <div>
          <Input
            type="number"
            max={9999}
            min={0}
            value={code}
            placeholder="请输入验证码"
            onChange={e => {
              this.changeState({ stateType: 'code', e });
            }}
            rightComponent={codeButton}
          ></Input>
        </div>
        {!onlyLogin ? (
          <div className={styles.agreement_content}>
            <Flex>
              <Flex.Item>
                <AgreeItem data-seed="logId" onChange={() => this.onChangeMobile()}>
                  同意将会员帐号与当前微信绑定
                </AgreeItem>
              </Flex.Item>
            </Flex>
          </div>
        ) : (
          <div></div>
        )}

        {this.renderSubmitButton()}
      </div>
    );
  }
}

export const Input = ({
  text,
  placeholderText,

  centerComponent,
  textStyle,
  containerStyle,
  leftComponent,
  rightComponent,
  ...props
}) => {
  return (
    <div className={[styles.input_container]}>
      {leftComponent}
      <input className={styles.input_box} {...props} />
      {rightComponent ? rightComponent : null}
    </div>
  );
};

export default Index;
