import { ComponentClass } from 'react';
import Taro, { Component, Config } from '@tarojs/taro';
import { View, Text, Image, Button, Input } from '@tarojs/components';

import Vcode from '../../components/Vcode/Vcode';

import baseIcon from '../../images/login/icon_jibenxinxi@2x.png';
import pwdIcon from '../../images/login/icon_passworld@2x.png';
import areaIcon from '../../images/login/icon_quyu@2x.png';
import pwdHideIcon from '../../images/login/setting_invisible_icon@2x.png';
import pwdShowIcon from '../../images/login/setting_see_icon@2x.png';
import radioIcon from '../../images/login/pc_nor_icon@2x.png';
import radioCheckIcon from '../../images/login/pc_sel_icon@2x.png';
import './Register.scss';
import agreeIcon from '../../images/login/icon_zhuce_sel@2x.png';
import agreeNotIcon from '../../images/login/icon_zhuce_nor@2x.png';
import { connect } from '@tarojs/redux';
import { UserState, updateUserInfo } from '../../store/rootReducers/userinfo';
import { wxUserRegister } from '../../api/customer';
import { replaceIllegalPwd } from '../../utils/pwd';
import { Customer } from '@/types/Customer/Customer';
import { ANN_LINK_URL } from '@/constants';
import { shareHandle } from '@/common/shareMethod';

type PageStateProps = {
  userinfo: Customer;
};
type PageDispatchProps = {
  updateUserInfo: (e: UserState) => void;
};

type PageState = {
  fetching: boolean;
  name: string;
  cellphone: string;
  vcode: string;
  pwd: string;
  checkPwd: string;
  sex: string;
  agree: boolean;
  showPwd: boolean;
  showCheckPwd: boolean;
};

type IProps = PageStateProps & PageDispatchProps;
interface Register {
  props: IProps;
  state: PageState;
}

@connect(
  ({ userinfo }) => ({
    userinfo,
  }),
  dispatch => ({
    updateUserInfo(entity: UserState) {
      dispatch(updateUserInfo(entity));
    },
  }),
)
class Register extends Component {
  config: Config = {
    navigationBarTitleText: '注册',
  };

  constructor(props: IProps) {
    super(props);
    const { customerPhone } = props.userinfo;
    this.state = {
      fetching: false,
      name: '',
      cellphone: customerPhone,
      vcode: '',
      pwd: '',
      checkPwd: '',
      sex: '1',
      agree: false,
      showPwd: false,
      showCheckPwd: false,
    };
  }
  onShareAppMessage = shareHandle;

  setSex(value: string) {
    this.setState({
      sex: value,
    });
  }

  setPwdValue(key: string, value: string) {
    let val = replaceIllegalPwd(value);
    this.setState({
      [key]: val,
    });
    return val;
  }

  validateRegisterEntity(): boolean {
    const { name, cellphone, vcode, pwd, checkPwd } = this.state;
    const {
      userinfo: { areaId },
    } = this.props;
    if (!name) {
      Taro.showToast({
        title: '请输入姓名',
        icon: 'none',
      });
      return false;
    }
    if (!cellphone || cellphone.length !== 11) {
      Taro.showToast({
        title: '请输入手机号码',
        icon: 'none',
      });
      return false;
    }
    if (!vcode || vcode.length !== 6) {
      Taro.showToast({
        title: '请输入6位验证码',
        icon: 'none',
      });
      return false;
    }
    if (!pwd || pwd.length < 6) {
      Taro.showToast({
        title: '请输入大于6位密码',
        icon: 'none',
      });
      return false;
    }
    if (!checkPwd || checkPwd.length < 6) {
      Taro.showToast({
        title: '请输入确认密码',
        icon: 'none',
      });
      return false;
    }
    if (pwd != checkPwd) {
      Taro.showToast({
        title: '两次密码不一致',
        icon: 'none',
      });
      return false;
    }
    if (!areaId) {
      Taro.showToast({
        title: '请选择所属校区',
        icon: 'none',
      });
      return false;
    }
    return true;
  }

  getRegister() {
    if (this.state.fetching) return;
    if (this.validateRegisterEntity()) {
      this.setState({
        fetching: true,
      });
      const { name, cellphone, pwd, sex, vcode } = this.state;
      const {
        userinfo: { areaId, areaName },
        updateUserInfo,
      } = this.props;
      Taro.login()
        .then(res => res.code)
        .then(code => {
          wxUserRegister({
            code: code,
            areaId: areaId,
            areaName: areaName,
            customerName: name,
            customerPhone: cellphone,
            customerSex: sex,
            password: pwd,
            verificationCode: vcode,
          })
            .then(res => {
              const data = res.data;
              console.log(data);
              updateUserInfo(data);
              Taro.showToast({
                title: '注册成功',
              });
              setTimeout(() => {
                Taro.reLaunch({
                  url: '/pages/Home/Home',
                });
              }, 2000);
            })
            .catch(err => {
              console.log(err);
              this.setState({
                fetching: false,
              });
            });
        })
        .catch(console.log);
    }
  }

  navToCampus() {
    Taro.navigateTo({
      url: '/pages/SelectCampus/SelectCampus',
    });
  }

  togglePwdBox() {
    this.setState(({ showPwd }: PageState) => ({
      showPwd: !showPwd,
    }));
  }

  togglePwdCheckBox() {
    this.setState(({ showCheckPwd }: PageState) => ({
      showCheckPwd: !showCheckPwd,
    }));
  }

  toggleAgreeState() {
    this.setState(({ agree }: PageState) => ({
      agree: !agree,
    }));
  }

  goAgreementPage(e) {
    e.stopPropagation();
    Taro.navigateTo({
      url:
        '/pages/WebPage/WebPage?url=' +
        encodeURIComponent(ANN_LINK_URL + '/agreement.html'),
    });
  }

  render() {
    const {
      name,
      sex,
      showPwd,
      showCheckPwd,
      agree,
      cellphone,
      vcode,
      pwd,
      checkPwd,
    } = this.state;
    const { userinfo } = this.props;
    return (
      <View className='Register topBr'>
        <View className='registerBox'>
          <View className='registerBox-title'>
            <Image className='registerBox-icon' src={baseIcon} />
            <Text className='registerBox-text'>基本信息</Text>
          </View>
          <View className='registerBox-item'>
            <Input
              className='loginBox-input'
              placeholderClass='loginBox-placeholder'
              placeholder='输入您的姓名'
              value={name}
              onInput={({ detail: { value } }) => {
                this.setState({
                  name: value.trim(),
                });
                return value.trim();
              }}
              maxLength={20}
            />
            <View className='loginBox-input sexBox'>
              <View className='sexBox-item' onClick={() => this.setSex('2')}>
                {sex === '2' ? (
                  <Image className='sexBox-icon' src={radioCheckIcon} />
                ) : (
                  <Image className='sexBox-icon' src={radioIcon} />
                )}
                <Text>女</Text>
              </View>
              <View className='sexBox-item' onClick={() => this.setSex('1')}>
                {sex === '1' ? (
                  <Image className='sexBox-icon' src={radioCheckIcon} />
                ) : (
                  <Image className='sexBox-icon' src={radioIcon} />
                )}
                <Text>男</Text>
              </View>
            </View>
          </View>
          <View className='registerBox-item'>
            <Input
              className='loginBox-input'
              placeholderClass='loginBox-placeholder'
              placeholder='请输入注册的手机号码'
              type='number'
              value={cellphone}
              onInput={({ detail: { value } }) => {
                this.setState({
                  cellphone: value,
                });
                return value;
              }}
              maxLength={11}
            />
          </View>
          <View className='registerBox-item'>
            <Input
              className='loginBox-input'
              placeholderClass='loginBox-placeholder'
              placeholder='请输入验证码'
              maxLength={6}
              value={vcode}
              onInput={({ detail: { value } }) => {
                this.setState({
                  vcode: value,
                });
                return value;
              }}
            />
            <Vcode
              vcode-classname='registerBox-getVcode'
              positionNum='2'
              ref='Vcode'
              cellphone={cellphone}
            />
          </View>
          <View className='registerBox-title'>
            <Image className='registerBox-icon' src={pwdIcon} />
            <Text className='registerBox-text'>密码设置</Text>
          </View>
          <View className='registerBox-item'>
            <Input
              className='loginBox-input'
              placeholderClass='loginBox-placeholder'
              password={!showPwd}
              placeholder='密码由6-20位组成'
              maxLength={20}
              value={pwd}
              onInput={({ detail: { value } }) =>
                this.setPwdValue('pwd', value)
              }
            />
            <Image
              className='registerBox-pwdIcon'
              src={showPwd ? pwdShowIcon : pwdHideIcon}
              onClick={this.togglePwdBox}
            />
          </View>
          <View className='registerBox-item'>
            <Input
              className='loginBox-input'
              placeholderClass='loginBox-placeholder'
              password={!showCheckPwd}
              placeholder='确认密码'
              maxLength={20}
              value={checkPwd}
              onInput={({ detail: { value } }) =>
                this.setPwdValue('checkPwd', value)
              }
            />
            <Image
              className='registerBox-pwdIcon'
              src={showCheckPwd ? pwdShowIcon : pwdHideIcon}
              onClick={this.togglePwdCheckBox}
            />
          </View>
          <View className='registerBox-title'>
            <Image className='registerBox-icon' src={areaIcon} />
            <Text className='registerBox-text'>区域信息</Text>
          </View>
          <View className='registerBox-item' onClick={this.navToCampus}>
            {userinfo.areaId ? (
              <Text>{userinfo.areaName}</Text>
            ) : (
              <Text className='noVlaue'>请填写真实区域信息</Text>
            )}
          </View>
        </View>
        <View className='registerBox-agreeBox' onClick={this.toggleAgreeState}>
          {agree ? (
            <Image className='registerBox-agreeCheck' src={agreeIcon} />
          ) : (
            <Image className='registerBox-agreeCheck' src={agreeNotIcon} />
          )}
          <Text>同意条款</Text>
          <Text className='service-deal' onClick={this.goAgreementPage}>
            《多彩校园服务协议》
          </Text>
        </View>
        {agree ? (
          <Button className='registerBox-button' onClick={this.getRegister}>
            确 认
          </Button>
        ) : (
          <Button className='registerBox-button' disabled>
            确 认
          </Button>
        )}
      </View>
    );
  }
}

export default Register as ComponentClass<IProps, PageState>;
