/**
 * File: index.jsx
 * Author: insane (luojie@doctorwork.com)
 * Last: insane (luojie@doctorwork.com>)
 * Date: 2018-06-09 03:46:53
 * Copyright 2018 - 2018 © Doctorwork
 *
 *  type: 1 妙健康 , 2 健康计划, 3 会员, type: 4
 *  id: skuCode
 */

import React, { PureComponent } from 'react';
import FootBtn from 'react-easy/components/Form/FootBtn';
import OrderInfo from 'react-easy/components/Purchase/OrderInfo';
import { get, post } from '@doctorwork/write-easy/lib/api';
import styles from './style.module.styl';

/**
 * 生成订单商品
 * @param {object} product 商品
 * @param {number} type 类型
 */
function getItem(product) {
    const { skuCode } = product;
    return {
        skuCode,
        num: 1
    };
}

interface CheckoutProps {
    onPay: Function;
    create: boolean;
    btnTitle: string;
    info: any;
}

class Checkout extends PureComponent<CheckoutProps, any> {
    constructor(props: any) {
        super(props);
        this.state = {
            creatingOrder: false,
            product: {}
        };
    }

    static navigationOptions = {
        title: '确认购买',
        headerTintColor: '#000',
        headerStyle: {
            backgroundColor: '#ffffff'
        }
    };

    async componentWillMount() {
        const { skuCode } = this.props;
        // 获取相关商品信息
        const product = await get('/product/detail?skuCode=' + skuCode);
        this.setState({ product });
    }

    handleConfirm = async () => {
        if (this.props.create) {
            return this.props.onPay();
        }
        const order = {
            orderType: this.props.type,
            orderItems: [getItem(this.state.product)],
            payMethod: 1,
            orderOwner: 1,
            orderSource: 2
        };
        // 保存extra
        if (this.props.extra) {
            order.extra = this.props.extra;
        }
        // 1、生成订单
        const res = await post('/order/submitForWeChat', order);
        // 2、调用props onPay
        this.props.onPay(res);
    };

    render() {
        const { product } = this.state;

        const {
            info = {
                productPrice: product.salePrice,
                totalPrice: product.salePrice
            }
        } = this.props;

        return (
            <div className={styles.ConfirmOrder}>
                <OrderInfo product={product} info={info} />
                <FootBtn>
                    <div className={styles.actual}>
                        实付款:
                        <span className={styles.price}>{info.totalPrice}</span>
                    </div>
                    <div className={styles.btn} onClick={this.handleConfirm}>
                        {this.props.btnTitle || '立即支付'}
                    </div>
                </FootBtn>
            </div>
        );
    }
}

export default Checkout;
