import React, { Component } from 'react';
import './index.less';
import Assets from '@src/components/Assets';
import { formatMoney, formatDate } from '@src/services/Tools';
import Modal from '../Modal';
import Tabs from '../Tabs';
import { SpecialRadioGroup } from '../Radio';
import Invite from '../Invite';
import Button from '../Button';
import QrCode from '../QrCode';
import { PayMVipEndModal } from '../PayModal';
import { Main } from '../../stores/main';
import { Order } from '../../stores/order';
import { My } from '../../stores/my';
import { User } from '../../stores/user';

import { ServiceParamMap } from '../../../Constant';

export default class extends Component {
  constructor(props) {
    super(props);
    this.state = { tab: '2', pay: '', select: null };
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.show && !this.init) {
      this.init = true;
      Main.getService('vip')
        .then(result => {
          result.package = result.package.map((row, index) => {
            row.label = `${row.title}: ¥${formatMoney(row.price)}`;
            row.value = ServiceParamMap.vip[index].value;
            return row;
          });
          this.setState({ service: result });
        });
    }
  }

  changeTab(key) {
    if (key === '1') {
      // 自动选择第一个
      this.select(ServiceParamMap.vip[0].value);
    }
    this.setState({ tab: key });
  }

  select(key) {
    Order.speedPay({ productType: 'service', service: 'vip', param: key }).then(result => {
      User.formatOrder(result);
      const [checkout] = result.checkouts;
      this.setState({ order: result, checkout });
      this.changePay('alipay');
    });
    this.setState({ select: key });
  }

  changePay(key) {
    const { order } = this.state;
    if (!order) return;
    this.setState({ payInfo: {}, pay: key });
    let handler = null;
    switch (key) {
      case 'wechatpay':
        handler = Order.wechatQr(order.id)
          .then((result) => {
            result.qr = Main.qrCode(result.request);
            this.setState({ payInfo: result });
          });
        break;
      case 'alipay':
      default:
        handler = Order.alipayQr(order.id)
          .then((result) => {
            result.qr = Main.qrCode(result.request);
            this.setState({ payInfo: result });
          });
    }
    handler.then(() => {
      this.queryPay();
    });
  }

  queryPay() {
    const { onClose, show } = this.props;
    const { order } = this.state;
    if (this.time) {
      clearTimeout(this.time);
    }
    this.time = setTimeout(() => {
      Order.query(order.id)
        .then(result => {
          if (result) {
            // 支付成功
            this.paySuccess();
            onClose();
          } else if (show) {
            this.queryPay();
          } else {
            this.setState({ tab: '2', select: null, pay: null, order: {}, checkout: {} });
          }
        });
    }, 1000);
  }

  paySuccess() {
    const { order } = this.state;
    const { data } = this.props;
    Order.getOrder(order.id).then(result => {
      User.formatOrder(result);
      // 确保开通用的是record记录id
      const [checkout] = result.checkouts;
      checkout.info.result = checkout.info.result.replace('{email}', data.email).replace('{useExpireDays}', checkout.useExpireDays).replace('{title}', checkout.title);
      if (checkout.service === 'vip') {
        // 查询最后有效期
        My.getVipInfo().then(vip => {
          checkout.info.result = checkout.info.result.replace('{endTime}', formatDate(vip.expireTime, 'YYYY-MM-DD'));
          User.refreshToken();
          this.setState({ show: false, showEnd: true, order: result, checkout });
        });
      } else {
        this.setState({ show: false, showEnd: true, order: result, checkout });
      }
    });
  }

  close() {
    const { onClose } = this.props;
    const { showEnd } = this.state;
    this.setState({ tab: '2', showEnd: false, select: null, pay: null, order: {}, checkout: {} });
    onClose(showEnd);
  }

  render() {
    const { show } = this.props;
    const { order, checkout, showEnd } = this.state;
    const { tab } = this.state;
    return [
      <Modal className="vip-renew-modal" show={show && !showEnd} width={630} title="VIP续期" onClose={() => this.close()}>
        <div className="vip-renew-wrapper">
          <Tabs
            border
            size="small"
            active={tab}
            width={80}
            tabs={[{ key: '1', title: '购买' }, { key: '2', title: '免费领取' }]}
            onChange={key => this.changeTab(key)}
          />
          {this[`renderTab${tab}`]()}
        </div>
      </Modal>,
      showEnd && <PayMVipEndModal show={showEnd} order={order} checkout={checkout} onConfirm={() => this.close()} />,
    ];
  }

  renderTab1() {
    const { pay, select, service = {}, order = {}, checkout = {}, payInfo = {} } = this.state;
    const { info = {} } = checkout;
    return (
      <div className="tab-1-layout">
        <div className="pay-modal-wrapper">
          <div className="select-layout">
            <SpecialRadioGroup
              list={service.package || []}
              value={select}
              width={100}
              space={10}
              onChange={key => this.select(key)}
            />
            <div className="info-layout">
              <div className="desc">
                服务: {info.description}
                <br />
                开通有效期: {checkout.expireDays ? `${checkout.expireDays}天` : '付款后立即生效'}
                <br />
                使用有效期: {checkout.useExpireDays ? `${checkout.useExpireDays}天` : '永久'}
                <br />
                退款政策: {info.refund_policy}
                <br />
                版权说明: {info.copyright_notes}
              </div>
              <div className="money">
                <div className="t-2">应付金额:</div>
                <div className="t-1 f-w-b t-s-24">¥ {order.money}</div>
              </div>
            </div>
          </div>
          <div className="pay-layout">
            <Tabs
              border
              size="small"
              active={pay}
              width={80}
              tabs={[{ key: 'alipay', title: '支付宝' }, { key: 'wechatpay', title: '微信' }]}
              render={item => <Assets name={item.key} />}
              onChange={key => this.changePay(key)}
            />
            <div className="qrcode">
              <QrCode width={140} height={140} qrCode={payInfo.qr} refresh onRefresh={() => this.changePay(pay)} />
            </div>
            <div className="t">请使用手机微信或支付宝扫码付款</div>
            {order && <div className="t">支付金额: ¥ {order.money}</div>}
          </div>

          <div style={{ bottom: 20, left: 0 }} className="p-a t-3 t-s-14">
            *若在购买过程中遇到问题
          </div>
          <div style={{ bottom: 0, left: 0 }} className="p-a t-3 t-s-14">
            请联系千行小助手:0193191safad 协助解决。
          </div>
        </div>
      </div>
    );
  }

  renderTab2() {
    const { data, onReal, onPrepare } = this.props;
    const { showInvite } = this.state;
    return (
      <div className="tab-2-layout">
        <div className="list">
          <div className="item">
            {data.bindReal && <span className="over">已完成</span>}
            <Assets className="icon" name={`realname2${data.bindReal ? '' : '_gray'}`} />
            <div className="t">
              <Assets name={data.bindReal ? 'gift_active' : 'gift'} />
              6个月
            </div>
            <Button size="small" radius disabled={data.bindReal} onClick={() => {
              onReal();
            }}>
              实名认证
            </Button>
          </div>
          <div className="item">
            <Assets className="icon" name={`invite${data.inviteNumber > 0 ? '' : '_gray'}`} />
            <div className="t">
              <Assets name={data.inviteNumber > 0 ? 'gift_active' : 'gift'} />
              {data.inviteNumber > 0 ? `7天 X ${data.inviteNumber}位好友` : '7天/每位好友'}
            </div>
            <Button size="small" radius onClick={() => {
              this.setState({ showInvite: true });
            }}>
              邀请好友
            </Button>
          </div>
          <div className="item">
            {data.bindPrepare && <span className="over">已完成</span>}
            <Assets className="icon" name={`information2${data.bindPrepare ? '' : '_gray'}`} />
            <div className="t">
              <Assets name={data.bindPrepare ? 'gift_active' : 'gift'} />
              1个月
            </div>
            <Button size="small" radius disabled={data.bindPrepare} onClick={() => {
              onPrepare();
            }}>
              完善信息
            </Button>
          </div>
        </div>
        {showInvite && <Invite data={data} />}
      </div>
    );
  }
}