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

import React, { Component } from 'react';
import { connect } from 'react-redux';

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

import { Modal, Toast } from 'antd-mobile';
import Config from '../../../utils/config';
import { mobileType, getQuery } from '../../../utils/helper';
import { register, upgrade } from '../services/index';
import { getCardTypeCZ, getMemberTypeCZ } from '../common/common';
const alert = Modal.alert;

//俱乐部类型
const ClubType = 'cku';
// cku会员类型
const memberType = [
  {
    name: '普卡',
    value: 0,
    key: '0',
    price: '0',
    img: require('../assets/memberType/base_card.png'),
  },
  {
    name: '银卡',
    value: 10,
    key: '10',
    price: '120',
    img: require('../assets/memberType/silver_card.png'),
  },
  {
    name: '金卡',
    value: 20,
    key: '20',
    price: '440',
    img: require('../assets/memberType/golden_card.png'),
  },
  {
    name: '铂金卡',
    value: 30,
    key: '30',
    price: '1120',
    img: require('../assets/memberType/platinum_card.png'),
  },
  {
    name: '紫金卡',
    value: 40,
    key: '40',
    price: '4240',
    img: require('../assets/memberType/zijin_card.png'),
  },
];

@connect(({}) => ({}))
class Index extends Component {
  constructor(props) {
    super(props);
    this.state = {
      type: '', //upgrade 升级 ，否者为注册
      userInfo: {},
      canTouch: true,
      canSubmit: false,
    };
  }

  componentWillMount = () => {
    this.initData();
  };

  componentDidMount = () => {};

  componentWillUnmount = () => {
    Toast.hide();
  };

  //判断是升级还是续费
  //type=upgrade
  initData = () => {
    const { location } = this.props;
    const type = getQuery(location, 'type') || '';

    let userInfoStr = window.sessionStorage.getItem('access-user');
    let userInfo = userInfoStr ? JSON.parse(userInfoStr) : {};
    this.setState({
      type: type,
      userInfo,
    });
  };

  /**
   *注册流程
   */
  //选择会员类型
  onSelect = item => {
    alert('提示', `确定开通${item && item.name ? item.name : ''}?`, [
      { text: '取消', onPress: () => console.log('cancel') },
      {
        text: '确定',
        onPress: () => {
          console.log('ok');
          this.onSubmit(item);
        },
      },
    ]);
  };

  //立即开通
  onSubmit = async item => {
    const { location } = this.props;

    //获取注册参数
    const mobile = getQuery(location, 'mobile') || '';
    const cardType = item && item.value ? item.value : 0;
    const memberType = cardType && [30, 40].includes(cardType) ? 20 : 10;
    const openId = getQuery(location, 'openId') || '';

    const params = {
      club: ClubType,
      cardType,
      memberType,
      mobile,
      mobileType,
    };
    if (openId) {
      params.openId = openId;
    }

    //
    this.props.dispatch({
      type: 'register/clearState',
      payload: {},
    });
    //保存注册前，所有输入注册的数据
    window.sessionStorage.setItem('registerInfo', JSON.stringify(params));
    router.push('/ckuh5/register');
  };

  /**
   *升级流程
   */
  onUpgrade = item => {
    alert('提示', `确定升级${item && item.name ? item.name : ''}?`, [
      { text: '取消', onPress: () => console.log('cancel') },
      {
        text: '确定',
        onPress: () => {
          console.log('ok');
          this.upgrade(item);
        },
      },
    ]);
  };

  //立即升级
  upgrade = async item => {
    //获取注册参数
    const cardType = item && item.value ? item.value : 0;
    const memberType = cardType && [30, 40].includes(cardType) ? 20 : 10;

    let params = {
      cardType,
      memberType,
    };
    //记录升级到专繁会员跳转， 犬舍信息编辑页
    const { userInfo } = this.state;
    window.sessionStorage.setItem('access-user', JSON.stringify({}));
    if (
      (memberType === '20' || memberType === 20) &&
      (userInfo.memberType === '10' || userInfo.memberType === 10)
    ) {
      //保存注册前，所有输入注册的数据
      window.sessionStorage.setItem('upgradeInfo', JSON.stringify(params));
      router.push('/ckuh5/upgradeInfo');
    } else {
      if (userInfo.memberType === '20' || userInfo.memberType === 20) {
        params.kennelFciName = userInfo.kennelFciName ? userInfo.kennelFciName : '';
        params.kennelFciNameBackup = userInfo.kennelFciNameBackup
          ? userInfo.kennelFciNameBackup
          : '';
        params.kennelNameCn = userInfo.kennelNameCn ? userInfo.kennelNameCn : '';
        params.kennelNameEn = userInfo.kennelNameEn ? userInfo.kennelNameEn : '';
      }

      const { rc, msg, data } = await upgrade({ ...params });
      if (rc === Config.constant.codeSuccess) {
        //保存支付信息在sessionStroage中
        this.savePayInfo({
          title: 'CKU',
          detail: `升级业务`,
          cardType,
          memberType,
          orderId: data.orderId,
          orderAmount: data.orderAmount,
        });
        router.replace('pay');
      } else {
        Toast.info(msg, 2);
      }
    }
  };
  //savePayInfo
  savePayInfo = data => {
    var obj = {};
    if (data && (data.orderAmount || data.orderAmount === 0)) {
      obj.orderAmount = data.orderAmount;
    }

    obj.orderId = data && data.orderId ? data.orderId : '';

    obj.title = data && data.memberType ? `CKU${getMemberTypeCZ(data.memberType)}` : '';
    obj.detail =
      data && (data.cardType || data.cardType === 0) ? `${getCardTypeCZ(data.cardType)}会员` : '';
    window.sessionStorage.setItem('payInfo', JSON.stringify(obj));
  };

  //渲染button
  renderButton = item => {
    const { type, userInfo } = this.state;
    //如果是升级功能
    if (type === 'upgrade') {
      if (item && item.value <= userInfo.cardType) {
        return <div></div>;
      }
      return (
        <div className={styles.item_container} key={item.key}>
          <img src={item.img}></img>
          <div className={styles.item_content}>
            <div
              className={styles.button_content}
              onClick={() => {
                this.onUpgrade(item);
              }}
            >
              立即升级
            </div>
          </div>
        </div>
      );
    } else {
      return (
        <div className={styles.item_container} key={item.key}>
          <img src={item.img}></img>
          <div className={styles.item_content}>
            <div className={styles.price_content}>
              <div className={styles.price_label}>¥</div>
              <div className={styles.price_text}>{item.price}</div>
            </div>
            <div
              className={styles.button_content}
              onClick={() => {
                this.onSelect(item);
              }}
            >
              立即开通
            </div>
          </div>
        </div>
      );
    }
  };

  render() {
    return (
      <div className={styles.member_type}>
        <div className={styles.title_content}>选择会员类型</div>
        <div className={styles.scroll_container}>
          {memberType.map(item => {
            return this.renderButton(item);
          })}
        </div>
      </div>
    );
  }
}

export default Index;
