import React, {Component} from 'react';
import {get, post} from './request';
import {loggerCors} from './logger';
import 'es6-object-assign/auto';
import Tappable from 'react-tappable/lib/Tappable';
import TimeUtils from '../utils/timeUtils';
import ConfirmModal from '../common/modal/ConfirmModal';
import ResultModal from '../common/modal/ResultModal';
import {showMessage} from '../common/toast/toast';
import * as Styled from './BaseRechargeItem.style';

const RECHARGE_TYPE = {
    WX_JSAPI: 'WX_JSAPI',
    WX_NATIVE: 'WX_NATIVE',
    ALIPAY: 'ALIPAY'
}

/*=============
基础充值逻辑
 ==============*/
export default class BaseRechargeItem extends Component {
    static defaultProps = {
        targetUrl: '',
        siteInfo: {}
    }

    constructor(props) {
        super(props);
        this.state = {
            action: '',
            qrCodeUrl: '',
            messageConfig: {},
            rechargeParams: {},
            consumeVm: 0 //余额充足时，购买VIP需要消耗的阅点
        }
        this.inVipActivity = false; //需要子类去赋值
        this.siteInfo = props.siteInfo;
        this.rechargeTypeMap = {};
        this.rechargeTypeMap[RECHARGE_TYPE.WX_JSAPI] = {value: 6, method: 'jsapiWxPay'};
        this.rechargeTypeMap[RECHARGE_TYPE.WX_NATIVE] = {value: 5, method: 'nativeWxPay'};
        this.interval = '';
        this.loggerData = {dot: '', message: {}}; //预订单成功后打点数据
        this.fromPage = '';

        this.confirmConsume = this.confirmConsume.bind(this);
        this.closeAllModal = this.closeAllModal.bind(this);
        this.closeQrCodeModal = this.closeQrCodeModal.bind(this);
    }

    closeAllModal() {
        this.setState({
            action: '',
            qrCodeUrl: ''
        })
    }

    closeQrCodeModal() {
        this.closeAllModal();
        clearInterval(this.interval);
    }

    /**
     * 组合站点、用户信息以及书籍sourceuuid(如果是从书籍跳转过来的话)等参数
     */
    composeParams(params={}) {
        const {env, kuxuanRootPath, site, ...otherInfo} = this.siteInfo;
        return {...otherInfo, ...params}
    }

    handlePressEvent = () => {
        loggerCors({dot: 'd-19'}, this.siteInfo);
    }

    /**
     * 充值成功回调，展示结果
     * @param  {[type]}  options.hbExpireDays  红包过期天数
     * @param  {[type]}  options.vipExpireTime vip到期时间
     * @param  {[type]}  options.coupons     赠送的优惠券
     * @param  {[type]}  options.amount        实际支付金额
     * @param  {[type]}  options.hongbao       赠送的红包数
     * @param  {[type]}  options.discount      满减折扣的金额
     * @param  {[type]}  options.drawChance    赠送的福袋数
     * @param  {Boolean} isConsume             余额充足直接购买vip
     * @return {[type]}                        [description]
     */
    successCallback({hbExpireDays, vipExpireTime, coupons, amount, hongbao, discount, followCode, drawChance}, isConsume = false) {
        let action = 'showResult';
        if(this.siteInfo.type == 3) {
            loggerCors({dot: 'd-16', message: {value: amount}}, this.siteInfo)
        }
        let callback = () => {
            if(this.props.targetUrl) {
                window.location.href = decodeURIComponent(this.props.targetUrl);
                // 批量购买页已启用
                // if(vipExpireTime && targetUrl.indexOf('/trade/batch.do') > -1) { /*充值vip活动后，不再进入批量购买页面*/
                //     targetUrl = targetUrl.replace('/trade/batch.do', '/book/reader.do');
                // }
            }
            else {
                if(window.location.href.indexOf('/recharge') > -1) {
                    location.reload()
                }else if(window.location.href.indexOf('/cms') > -1) {
                    location.reload()
                }else {
                    window.location.href = '/recharge/pay.do?'+ window.location.href.split('?')[1];
                }
            }
        }

        let message = '';
        if(vipExpireTime) { //包vip才有该字段
            message = `<p class="text">您已成功升级为<em>${decodeURIComponent(this.siteInfo.site) || '本站点'}VIP用户</em>，开始无限免费畅读吧!</p><p class="text-tip">VIP到期时间：${timeUtils.format(vipExpireTime * 1)}</p>`
        }
        else {
            const yd = (amount || 0) * 100 + (discount || 0) * 100;
            message = `<p class="text">获得<em>${yd}</em>阅点</p>`;
            let textArr = [];
            hongbao && (textArr.push(`<em>${hongbao}</em>红包`));
            const couponVal = (coupons || [0]).reduce((acc, cur) =>(acc + cur.giftYuedu), 0);
            if(couponVal > 0) {
                action = 'showResultWithCoupon';
                textArr.push(`<em>${Number.parseInt(couponVal/100)}</em>元优惠券`);
            }
            drawChance && (textArr.push(`<em>福袋X${drawChance}(本页顶部领取)</em>`));
            textArr.length > 0 && (message += `<p class="text">送${textArr.join('和')}</p>`);
            hongbao && hbExpireDays && (message += `<p class="text-tip">*红包有效期：${hbExpireDays}天</p>`);
        }
        let _children = [];
        if(followCode) {
            _children = [(<Tappable onPress={this.handlePressEvent}><img src={followCode} /></Tappable>),
            (<p className="text text-s tip-qrcode">关注公众号，方便您更便捷找到小说</p>)];
        }
        let messageConfig = {
                title: isConsume ? 'VIP购买成功' : '充值成功',
                content: `${message}`,
                _children,
        }
        if(action == 'showResultWithCoupon') {
            messageConfig = {
                ...messageConfig,
                onOk: callback,
                onCancel: () => {
                    loggerCors({dot: 'd-20'}, this.siteInfo);
                    setTimeout(() => {
                        window.location.href = `${this.siteInfo.kuxuanRootPath}/route/coupon.do`;
                    }, 200);
                },
                cancelText: '查看优惠券',
                okText: '知道了',
            }
        }
        else {
            messageConfig = {
                ...messageConfig,
                onClose: callback,
            }
        }
        this.setState({
            action,
            qrCodeUrl: '',
            messageConfig,
        })
    }

    /**
     * [failCallback description]
     * @param  {Boolean} orderVip    充值成功，但vip购买失败
     * @return {[type]}              [description]
     */
    failCallback(orderVip = false) {
        let title = '充值失败',
            message = '因网络异常等原因导致充值失败，请稍后重试！',
            buttonName = '知道了',
            onClose = () => {this.closeAllModal()};
        if(orderVip) {
            title = 'VIP订购失败'
            if(this.inVipActivity) {
                message = '由于VIP生效之前您消费了阅点，导致现有阅点余额不足订购VIP，麻烦您重新充值补足阅点哦~'
                onClose = () => {
                    loggerCors({dot: 'd-14'}, this.siteInfo);
                    setTimeout(() => {
                        window.location.href = this.siteInfo.kuxuanRootPath + '/pay.do'
                    }, 200);

                }
                buttonName = '前往补足余额'
            }
            else {
                message = '由于VIP生效之前您消费了阅点，导致现有阅点余额不足订购VIP，请您联系公众号客服处理。'
            }
        }
        this.setState({
            action: 'showResult',
            qrCodeUrl: '',
            messageConfig: {
                title: title,
                content: `<p>${message}</p>`,
                buttonName: buttonName,
                onClose: onClose
            }
        })
    }

    /**
     * 活动充值项充值超过限制次数
     */
    limitCallback() {
        this.setState({
            action: 'showResult',
            qrCodeUrl: '',
            messageConfig: {
                title: '',
                content: `<p>您已达到上限，本次充值优惠次数有限哦~</p>`,
                buttonName: '确定',
                onClose: () => {this.closeAllModal()}
            }
        })
    }

    //支付状态轮询
    retriveStatus(uuid, params) {
        let repeat = 0;
        this.interval = setInterval(() => {
            if(!repeat){
                get('/recharge/queryOrder.json', this.composeParams({rechargeUuid: uuid})).then(result => {
                    if(result.code === 200) { //充值成功
                        if(result.tradeStatus){
                            repeat = 1;
                            clearInterval(this.interval);
                            if(result.postResult.success != undefined) {
                                if(result.postResult.success) {
                                    const {hongbao, vip, coupons, qrCodeUrl: followCode, drawChance} = result.postResult;
                                    const {amount, discount} = params;
                                    this.successCallback({hbExpireDays: hongbao && hongbao.expireDays, vipExpireTime: vip && vip.expireTime, coupons, amount, discount, hongbao: params.hongbao, followCode, drawChance});
                                }
                                else {  //充值成功，VIP订购失败
                                    this.failCallback(true);
                                }
                            }
                            else {
                                this.successCallback({});
                            }
                        }
                    }
                    else if(result.code === -999) {
                        if(this.fromPage === 'reader' && this.props.targetUrl) {
                            let targetUrl = decodeURIComponent(this.props.targetUrl);
                            window.location.href = targetUrl;
                        }
                        else {
                            location.reload();
                        }
                    }
                    else {
                        repeat = 1;
                        clearInterval(this.interval);
                        this.failCallback();
                    }
                });
            }
            else {
                clearInterval(this.interval);
            }
        }, 500);
    }

    /**
     * 微信JSAPI
     * @param  {[type]} data   充值订单返回的微信签名、订单uuid等
     * @param  {[type]} params 发起充值订单的充值参数
     * @return {[type]}        [description]
     */
    onBridgeReady(data, params) {
        WeixinJSBridge.invoke(
           'getBrandWCPayRequest', {
               "debug" : false,
               "appId" : data.appId,     //公众号名称，由商户传入
               "timeStamp" : data.timeStamp,         //时间戳，自1970年以来的秒数
               "nonceStr" : data.nonceStr, //随机串
               "package" : data.package,
               "signType" : data.signType,         //微信签名方式：
               "paySign" : data.paySign //微信签名
           },
           res => {
                if(res.err_msg == "get_brand_wcpay_request:ok" ) {
                    //开启轮询查看后端订单状态
                    this.retriveStatus(data.rechargeUuid, params);
                }else if(res.err_msg == "get_brand_wcpay_request:cancel") {
                    showMessage({text: '支付取消！'})
                }else {
                    this.nativeWxPay(params);
                }
           }
       );
    }

    //微信JSAPI支付
    jsapiWxPay(params) {
        post('/recharge/confirm.json', this.composeParams(params)).then(result => {
            if(result.code === 200) {
                const {rechargeUuid} = result.data;
                this.loggerData.message.type = RECHARGE_TYPE.WX_JSAPI;
                this.loggerData.message.rechargeUuid = rechargeUuid;
                loggerCors(this.loggerData, this.siteInfo);

                if (typeof WeixinJSBridge == "undefined") {  //会出现WeixinJSBridge尚未加载好的情况
                    document.addEventListener('WeixinJSBridgeReady', () => {
                        this.onBridgeReady(result.data, params);
                    })
                }
                else {
                    this.onBridgeReady(result.data, params);
                }
            }
            else if(result.code === -999) {
                location.reload();
            }
            else if(result.code === 609) { //活动充值项次数达到上限
                this.limitCallback();
            }
            else {
                this.failCallback();
            }
        })
    }

    //微信NATIVE支付
    nativeWxPay(params) {
        const nativeWxParams = Object.assign({}, params, {type: this.rechargeTypeMap[RECHARGE_TYPE.WX_NATIVE].value});
        post('/recharge/confirm.json', this.composeParams(nativeWxParams)).then(result => {
            if(result.code === 200){
                const {rechargeUuid, qr_url} = result.data;
                this.loggerData.message.type = RECHARGE_TYPE.WX_NATIVE;
                this.loggerData.message.rechargeUuid = rechargeUuid;
                loggerCors(this.loggerData, this.siteInfo);
                //展示二维码，同时开启轮询查看订单状态
                this.setState({
                    action: 'showCode',
                    qrCodeUrl: qr_url
                });
                this.retriveStatus(rechargeUuid, params);
            }
            else if(result.code === -999) {
                location.reload();
            }
            else if(result.code === 609) { //活动充值项次数达到上限
                this.limitCallback();
            }
            else {
                this.failCallback();
            }
        })
    }

    //支付宝
    // aliPay() {
    //     const {rechargeParams} = this.state;
    //     post('/recharge/confirm.json', this.composeParams(rechargeParams)).then(result => {
    //         if(result.code === 200){
    //             location.href = result.url;
    //         }else{
    //             this.failCallback();
    //         }
    //     })
    // }

    //余额充足，直接购买VIP
    confirmConsume() {
        const {rechargeParams} = this.state;
        post('/recharge/consume.json', this.composeParams(rechargeParams)).then(result => {
            if(result.code === 200){
                this.successCallback({vipExpireTime: result.expireTime, amount: rechargeParams.amount}, true)
            }
            else if(result.code === -999) {
                location.reload();
            }
            else {
                this.failCallback();
            }
        })
    }

     /**
      * 充值请求
      * @param  {[type]} product 充值项 (product.productType: 0 正常充值项，1 VIP活动等)
      * @param  {[type]} type   充值类型
      * @return {[type]}         [description]
      */
    handleRecharge(product, type, index = 0) {
        const {price, needPay, configId, productAmount, couponId, discount, hongbao, fromPage, referrer} = product;
        this.fromPage = product.fromPage;
        this.loggerData = ({dot: 'd-17', message: {isVip: (product.productType == 1), rechargeUuid: '', couponId, price, needPay, productAmount, fromPage, referrer}});
        let rechargeType = this.rechargeTypeMap[type];
        let typeVal = rechargeType.value;
        let typeMethod = rechargeType.method;
        let _rechargeParams = Object.assign({}, this.state.rechargeParams, {
            type: typeVal,
            amount: needPay,
            configId,
            couponId: (couponId && couponId != 'null') ?  couponId : '',
            discount: (discount && discount != 'null') ?  discount : 0,
            hongbao: parseInt(hongbao) || 0,
            index
        });
        this.setState({
            rechargeParams: _rechargeParams
        }, () => { //从章节充值跳转过来needPay为0的时候，值为string格式的，所以用==
            if(product.productType && product.productType == 1 && product.needPay == 0) {
                this.setState({
                    action: 'confirmConsume',
                    consumeVm: price*100 || 0
                })
            }
            else {
                this[typeMethod](_rechargeParams);
            }
        });
    }

    /**
     * 获取vip订购失败消息
     * @return {[type]} [description]
     */
    getMessage() {
        if(!localStorage.getItem('N_recharge_viptip')) { //只提示一次
            post('/getMessage.json', this.composeParams()).then(result => {
                if(result.code === 200){ //VIP购买交易未完成
                    (result.messages || []).map(msgItem => {
                        if(msgItem.code == 0) {
                            this.failCallback(true);
                            localStorage.setItem('N_recharge_viptip', true);
                        }
                    })
                }
            })
        }
    }

    componentDidMount() {
      !this.props.parentProps.isEdit && this.getMessage();
        // this.successCallback({hbExpireDays: 5, vipExpireTime: 0, amount: 26, discount: 3, hongbao: 1000});
    }

    render() {
        const {action, qrCodeUrl, messageConfig, consumeVm} = this.state;
        const {_children, ...otherConfig} = messageConfig;
        return (<Styled.BaseRechargeItem>
                {action == 'showCode' && (<div className="m-mask" onClick={this.closeQrCodeModal}>
                    <div className="m-qr-pay">
                        <h4>请让他人扫码支付</h4>
                        <div className="inner">
                            <img src={qrCodeUrl} />
                        </div>
                        <p className="tip">暂不支持长按二维码支付方式</p>
                        <p className="PS">注:充值到您的账户，扣款发生在扫码人账户</p>
                    </div>
                </div>)}
                {action == 'confirmConsume' && (<ConfirmModal config={{content: `<p>确认消耗${consumeVm}阅点购买VIP？</p>`, onOk: this.confirmConsume, onCancel: this.closeAllModal}}/>)}
                {action == 'showResult' && (<ResultModal config={otherConfig}>{_children}</ResultModal>)}
                {action == 'showResultWithCoupon' && (<ConfirmModal config={otherConfig}>{_children}</ConfirmModal>)}
            </Styled.BaseRechargeItem>)
    }
}

BaseRechargeItem.defaultProps = {
    targetUrl: '',
    siteInfo: {}
}
