import React, { Component } from 'react';
import './index.less';
import { Checkbox, Icon } from 'antd';
import Assets from '@src/components/Assets';
import { formatDate } from '@src/services/Tools';
import Tabs from '../Tabs';
import Modal from '../Modal';
import QrCode from '../QrCode';

import { Order } from '../../stores/order';
import { Main } from '../../stores/main';
import { My } from '../../stores/my';
import { User } from '../../stores/user';

export class PayModal extends Component {
  constructor(props) {
    super(props);
    this.state = { show: true };
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.user.needPay && !this.init) {
      this.init = true;
      Main.getContract('course')
        .then((result) => {
          this.setState({ contract: result });
        });
    }
  }

  changePay(key) {
    const { order } = this.props.user;
    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':
        handler = Order.alipayQr(order.id)
          .then((result) => {
            this.setState({ payInfo: result });
          });
        break;
      default:
        return;
    }
    handler.then(() => {
      this.queryPay();
    });
  }

  queryPay(force) {
    const { order, needPay } = this.props.user;
    if (this.time) {
      clearTimeout(this.time);
    }
    if (force) {
      this.times = 0;
    } else {
      this.times = (this.times || 0) + 1;
    }
    this.time = setTimeout(() => {
      Order.query(order.id)
        .then(result => {
          if (result) {
            // 支付成功
            this.paySuccess();
          } else if (needPay) {
            this.queryPay();
          } else {
            this.setState({ select: null, pay: null, order: null, info: null });
          }
        });
    }, 1000);
  }

  paySuccess() {
    const { order } = this.props.user;
    const { info } = this.props.user;
    Order.getOrder(order.id).then(result => {
      User.formatOrder(result);
      // 确保开通用的是record记录id
      const [checkout] = result.checkouts;
      checkout.info.result = checkout.info.result.replace('{email}', info.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'));
          this.setState({ show: false, showVipEnd: true, order: result, checkout });
        });
      } else if (order.checkouts.length === 1 && checkout.productType === 'data') {
        this.setState({ show: false, showDataEnd: true, order: result, checkout });
      } else if (order.checkouts.length === 1) {
        this.setState({ show: false, showEnd: true, order: result, checkout });
      } else {
        User.closePay();
      }
    });
  }

  confirm() {
    const { pay } = this.state;
    if (pay === 'bank') {
      this.setState({ showBank: true, show: false });
    } else {
      //
    }
  }

  open() {
    const { checkout } = this.state;
    Order.useRecord(checkout.id)
      .then(() => {
        User.closePay();
        this.setState({ show: true, pay: null });
      });
  }

  read() {
    User.closePay();
    linkTo('/my/data');
  }

  close() {
    const { showEnd, showBank } = this.state;
    User.closePay(showEnd || showBank ? null : new Error('支付失败'));
    this.setState({ show: true, pay: null, showEnd: false, showBank: false });
  }

  render() {
    const { needPay, order } = this.props.user;
    const { show, showBank, showEnd, showDataEnd, showVipEnd, contract, payInfo } = this.state;
    if (!needPay) return [];
    return [
      showBank && <PayKBankModal
        show
        order={order}
        checkout={order.checkouts[0]}
        onConfirm={() => this.close()}
      />,
      showEnd && <PayMEndModal
        show
        order={order}
        checkout={order.checkouts[0]}
        onCancel={() => this.close()}
        onClose={() => this.close()}
        onConfirm={() => this.open()}
      />,
      showDataEnd && <PayMDataEndModal
        show
        order={order}
        checkout={order.checkouts[0]}
        onCancel={() => this.close()}
        onClose={() => this.close()}
        onConfirm={() => this.read()}
      />,
      showVipEnd && <PayMVipEndModal
        show
        order={order}
        checkout={order.checkouts[0]}
        onConfirm={() => this.close()}
      />,
      show && (order.checkouts.length > 1 || order.checkouts[0].productType === 'course_package') && <PayMutilModal
        show
        contract={contract}
        order={order}
        payInfo={payInfo}
        onChangePay={(key) => this.changePay(key)}
        onCancel={() => this.close()}
        onClose={() => this.close()}
        onConfirm={() => this.confirm()}
      />,
      show && (order.checkouts.length === 1 && order.checkouts[0].productType !== 'course_package') && <PayMModal
        show
        contract={contract}
        order={order}
        payInfo={payInfo}
        checkout={order.checkouts[0]}
        productType={order.productTypes[0]}
        onChangePay={(key) => this.changePay(key)}
        onCancel={() => this.close()}
        onClose={() => this.close()}
        onConfirm={() => this.confirm()}
      />,
    ];
  }
}

export class PayMModal extends Component {
  constructor(props) {
    super(props);
    const payList = [{ key: 'alipay', title: '支付宝' }, { key: 'wechatpay', title: '微信' }];
    if (props.productType === 'course') {
      payList.push({ key: 'bank', title: '银行转账' });
    }
    this.state = { pay: 'alipay', payList, checked: true, showChecked: props.productType === 'course' };
    setTimeout(() => {
      props.onChangePay('alipay');
    }, 100);
  }

  render() {
    const { show, checkout, onClose, onConfirm, onChangePay, order, payInfo = {}, contract = {}, productType } = this.props;
    const { info } = checkout;
    const { pay, payList, checked, showChecked } = this.state;
    return (
      <Modal
        className="pay-modal"
        show={show}
        width={760}
        title={`购买${checkout.title}`}
        confirmText={pay === 'bank' ? '确认' : '支付成功'}
        onConfirm={pay === 'bank' ? onConfirm : null}
        // cancelText="稍后开通"
        // onCancel={onCancel}
        onClose={onClose}
      >
        <div className="pay-modal-wrapper">
          <div className="info-layout">
            <div className="desc">
              商品: {productType === 'data' ? info.title : checkout.title}<br />
              {productType !== 'course' && `服务: ${productType === 'data' ? checkout.title : info.description}`}{productType === 'course' && <span>服务: 见<a href={`/contract/${contract.key}`} target="_blank">{contract.title}</a></span>}<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 className="pay-layout">
            <Tabs
              border
              size="small"
              active={pay}
              width={80}
              tabs={payList}
              render={item => <Assets name={item.key} />}
              onChange={key => {
                this.setState({ pay: key });
                onChangePay(key);
              }}
            />
            <div hidden={pay === 'bank'} className="pay">
              <div className="qrcode">
                <QrCode width={140} height={140} qrCode={payInfo.qr} vague={!checked} />
              </div>
              <div className="t">请使用手机微信或支付宝扫码付款</div>
              <div className="t">支付金额: ¥ {order.money}</div>
            </div>
            <div hidden={pay !== 'bank'} className="bank">
              <div className="t">汇款银行:中国工商银行上海市浦东支行</div>
              <div className="t">汇款账号:6100 0000 0000 000</div>
            </div>
            <div className="agree" hidden={!showChecked}>
              <Checkbox className="m-r-1" checked={checked} onClick={() => {
                this.setState({ showChecked: checked, checked: !checked });
              }} />
              我已阅读并同意<a href={`/contract/${contract.key}`} target="_blank">《{contract.title}》</a>
            </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>
      </Modal>
    );
  }
}

export class PayMutilModal extends Component {
  constructor(props) {
    super(props);
    this.state = { pay: 'alipay', checked: true, showChecked: true };

    setTimeout(() => {
      props.onChangePay('alipay');
    }, 100);
  }

  render() {
    const { show, onConfirm, onClose, onChangePay, order, payInfo = {}, contract = {} } = this.props;
    const { pay, checked, showChecked } = this.state;
    return (
      <Modal
        className="pay-modal"
        show={show}
        width={760}
        title={'购物车结账'}
        confirmText={pay === 'bank' ? '确认' : '支付成功'}
        onConfirm={pay === 'bank' ? onConfirm : null}
        // onCancel={onCancel}
        onClose={onClose}
      >
        <div className="pay-modal-wrapper">
          <div className="info-layout">
            <div className="desc">
              商品: {order.checkouts.map(row => (row.productType === 'course_package' ? row.children.map(r => r.title).join(' ') : row.title)).join(' ')}<br />
              服务: 见<a href={`/contract/${contract.key}`} target="_blank">{contract.title}</a><br />
              开通有效期: 见订单详情
              <br />
              使用有效期: 见订单详情
              <br />
              退款政策: 本商品为虚拟产品,购买成功后不支持退款。<br />
              版权说明: 本商品为虚拟产品,购买成功后不支持退款。
            </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 className="pay-layout">
            <Tabs
              border
              size="small"
              active={pay}
              width={80}
              tabs={[
                { key: 'alipay', title: '支付宝' },
                { key: 'wechatpay', title: '微信' },
                { key: 'bank', title: '银行转账' },
              ]}
              render={item => <Assets name={item.key} />}
              onChange={key => {
                this.setState({ pay: key });
                onChangePay(key);
              }}
            />
            <div hidden={pay === 'bank'} className="pay">
              <div className="qrcode">
                <QrCode width={140} height={140} qrCode={payInfo.qr} vague={!checked} />
              </div>
              <div className="t">请使用手机微信或支付宝扫码付款</div>
              <div className="t">支付金额: ¥ {order.money}</div>
            </div>
            <div hidden={pay !== 'bank'} className="bank">
              <div className="t">汇款银行:中国工商银行上海市浦东支行</div>
              <div className="t">汇款账号:6100 0000 0000 000</div>
            </div>
            <div className="agree" hidden={!showChecked}>
              <Checkbox className="m-r-1" checked={checked} onClick={() => {
                this.setState({ showChecked: checked, checked: !checked });
              }} />
              我已阅读并同意<a href={`/contract/${contract.key}`} target="_blank">《{contract.title}》</a>
            </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>
      </Modal>
    );
  }
}

export class PayKBankModal extends Component {
  render() {
    const { show, onConfirm } = this.props;
    return (
      <Modal
        show={show}
        width={630}
        title="银行汇款"
        btnAlign="center"
        confirmText="好的,知道了"
        onConfirm={onConfirm}
      >
        <div style={{ width: 400 }} className="t-2 t-s-18 m-b-2">
          汇款成功后,请添加微信号XXX或扫描二维码联系小助手,进行核实。
        </div>
        <div className="p-a" style={{ right: 0, top: 50 }}>
          <Assets name="qrcode" />
        </div>
      </Modal>
    );
  }
}

export class PayMEndModal extends Component {
  render() {
    const { show, onConfirm, onCancel, checkout = {} } = this.props;
    const { info } = checkout;
    return (
      <Modal
        show={show}
        width={630}
        title="付款成功"
        confirmText="立即开通"
        cancelText="稍后开通"
        onConfirm={onConfirm}
        onCancel={onCancel}
      >
        <div className="t-2 ws-pl">
          <Icon className="t-5 m-r-5" type="check" />{info.result}
        </div>
        {info.tips && <div style={{ bottom: 10, left: 0 }} className="p-a t-3 t-s-14">
          *{info.tips}
        </div>}
      </Modal>
    );
  }
}

export class PayMDataEndModal extends Component {
  render() {
    const { show, onConfirm, onCancel, checkout = {} } = this.props;
    const { info } = checkout;
    return (
      <Modal
        show={show}
        width={630}
        title="付款成功"
        confirmText="立即查看"
        cancelText="暂不查看"
        onConfirm={onConfirm}
        onCancel={onCancel}
      >
        <div className="t-2 ws-pl">
          <Icon className="t-5 m-r-5" type="check" />{info.result}
        </div>
        {info.tips && <div style={{ bottom: 10, left: 0 }} className="p-a t-3 t-s-14">
          *{info.tips}
        </div>}
      </Modal>
    );
  }
}

export class PayMVipEndModal extends Component {
  render() {
    const { show, onConfirm, checkout = {} } = this.props;
    const { info } = checkout;
    return (
      <Modal
        show={show}
        width={630}
        title="付款成功"
        confirmText="知道了"
        // cancelText="稍后开通"
        onConfirm={onConfirm}
      // onCancel={onCancel}
      >
        <div className="t-2 ws-pl">
          <Icon className="t-5 m-r-5" type="check" />{info.result}
        </div>
        {info.tips && <div style={{ bottom: 10, left: 0 }} className="p-a t-3 t-s-14">
          *{info.tips}
        </div>}
      </Modal>
    );
  }
}