<template>
    <div>
        <pay_success
            v-if="isZeroPaySuccess || (!isZeroBack && isShowPaySuccess)"
            :store_code="store_code"
            :store_name="store_name"
            :is_show_code="isShowCode"
            :pay_gift_list="payGiftList"
            :right_type="rightType"
        >
        </pay_success>

        <team_buy_back v-if="is_team_buy"></team_buy_back>
    </div>
</template>
<style></style>
<script>
import pay_success from '~publicAsset/modules/teamBuy/pay_success.vue'
import team_buy_back from '~publicAsset/modules/teamBuy/teamBuyPayBack.vue'
import jsTools from '@xiaoe/js-tools'
// import EventBus from '~publicAsset/libs/eventbus';
import pay_data_handle from '~publicAsset/libs/pay_data_handle.js'
import pay_back_utils from '~publicAsset/libs/pay_back_utils.js'
import { getQueryString } from '~publicAsset/libs/utils.js'
import { reportRecords } from '~publicAsset/libs/studyRecordReport.js'

export default {
    props: {
        data: {
            default: {},
        },
        reqType: {
            type: String,
            default: '',
        },
    },
    data() {
        return {
            isZeroPaySuccess: false,
            store_code: '',
            store_name: '',
            subscribe: true, //是否已关注公众号
            is_team_buy: false, //这个支付是否拼团支付
            rightType: '', //支付有礼的权益类型
            payGiftList: [], //支付有礼权益列表
            isShowCode: false, //是否显示二维码
            isZeroBack: false, // 标记是否是0元订单返回
        }
    },
    components: {
        pay_success,
        team_buy_back,
    },
    created: function() {
        /**
         * 资源页关注二维码弹窗显示
         * */
        // let that = this;
        // EventBus.$on('showAttentionInfo',function(order_id)){};
    },
    computed: {
        /**
             * 引导加群没有关注过，并且二维码地址不为空则显示购买成功弹框
                支付有礼有权益数据返回，则显示购买成功弹框
            */
        isShowPaySuccess() {
            if (this.isShowCode || (this.payGiftList && this.payGiftList.length > 0)) {
                return true
            } else {
                return false
            }
        },
    },
    mounted: function() {
        /**
         *支付成功页面返回
         * */
        let that = this
        // 含有paySuccess参数，属于非0元订单的回调，无paySuccess参数属于非0元订单
        if (pay_back_utils.is_payback()) {
            let pay_save_data = pay_data_handle.loadData()
            if (pay_save_data && pay_save_data.team_buy_id) {
                // that.is_team_buy = true;
                pay_data_handle.clearData()

                let params = window.localStorage.getItem('team_buy_task_id')
                // location.href = location.pathname + '?task_id=' + params
            } else {
                let payOrderid = getQueryString('order_id')
                let order_id = payOrderid ? payOrderid : ''
                // 调用引导加群及支付有礼
                that.attentionInfo(order_id, function() {
                    if (that.isShowPaySuccess) {
                        that.isZeroPaySuccess = true
                    }
                })

                // 学习中心上报
                try {
                    that.reportLearningLog()
                } catch (error) {
                    console.log(error)
                }
            }
        }
    },
    watch: {
        data: {
            handler(newval) {
                // 0元回调触发,没有paySucess参数
                if (newval && !pay_back_utils.is_payback()) {
                    this.isZeroBack = true
                    // 抛出零元订单回调事件
                    this.$emit('zeroPayBack', this.zero_pay_back)
                    this.$emit('reportLog', this.reportLearningLog)
                }
            },
            deep: true,
        },
    },
    methods: {
        /** 0元订单回调事件
         * order_id 订单id
         * back_url 支付后跳转地址
         */
        zero_pay_back(order_id) {
            let that = this
            that.attentionInfo(order_id, function() {
                console.log('0元订单回调')
                //如果业务侧有传入支付后的跳转url,那么指向支付后的跳转
                let date = new Date()
                if (that.data.availableInfo.back_url) {
                    let jump_url = that.data.back_url
                    if (jump_url.indexOf('?') === -1) {
                        jump_url = jump_url + `?${date.getTime()}`
                    } else {
                        jump_url = jump_url + `&${date.getTime()}`
                    }
                    eJump(`${jump_url}&isFirstDistributor=1`, true)
                } else if (that.isShowPaySuccess) {
                    //显示购买成功页弹框
                    that.isZeroPaySuccess = true
                } else {
                    let urlFlag = location.href

                    if (urlFlag.indexOf('?') > -1) {
                        urlFlag = urlFlag + `&${date.getTime()}`
                    } else {
                        urlFlag = urlFlag + `?&${date.getTime()}`
                    }
                    eJump(`${urlFlag}&isFirstDistributor=1`, true)
                }
            })
        },
        /**
         * 关注微信公众号弹窗  会根据传入参数判断到底弹出哪一种二维码
         * @param callback
         * */
        attentionInfo: function(order_id, callback) {
            let that = this
            console.log('传入参数', that.data)
            let url = 'getSubscribedQr'
            if (this.reqType === 'alive') {
                url = '_alive/getSubscribedQr'
            }
            let params = {
                app_id: window.APPID,
                type: 1, //支付和邀请码页面传0  顶部传1
                resourceType: that.data.availableInfo.resource_type,
                resourceId: that.data.availableInfo.productId,
            }
            jsTools.request({ url, params }).then(data => {
                if (data && data.code == 0 && data.data) {
                    let subscribeConfig = data.data
                    that.store_code = subscribeConfig.wx_qr_url
                    that.store_name = subscribeConfig.wx_app_name
                    that.subscribe = subscribeConfig.subscribe
                    if (subscribeConfig.subscribe) {
                        that.isShowCode = false //关注过不弹窗
                    } else if (subscribeConfig.wx_qr_url) {
                        //没关注过且有二维码就弹窗
                        that.isShowCode = true
                    } else {
                        that.isShowCode = false
                    }
                    that.getPayGiftInfo(order_id, callback)
                } else {
                    that.getPayGiftInfo(order_id, callback)
                }
            })
        },
        /**
         * 1. 目前支付都跳空白页进行支付，因此支持学习中心的记录支持的时候，需要在购买成功后上报，学习进度
         * 2. 学习记录上报单品和专栏，且单品关联上级仅到专栏一级，专栏上报改目录展示下的一个资源
         * 3. 接口上报同学习记录上报接口。只是所有学习进度均为0
         * 4. 专栏目录为空不上报
         * */
        reportLearningLog() {
            let params_report = {
                resource_id: '',
                resource_type: '',
                learn_progress: 0,
                org_learn_progress: 0,
                product_id: '',
                // stay_time: reportData.stayTime
            }

            let { resource_type, productId, resourceId } = this.data.availableInfo

            // 单品的处理方式(单品类型) // 目前只有电子书在此项目，专栏在其他项目
            if (['1', '2', '3', '4', '20'].indexOf(resource_type.toString()) > -1) {
                params_report['resource_type'] = resource_type
                params_report['resource_id'] = resourceId
                params_report['product_id'] = productId || ''
                // 单品发送学习记录请求
                reportRecords(params_report, true)
            }
        },
        /**
         * 获取支付有礼数据，控制购买成功页的显示
         */
        getPayGiftInfo(order_id, callback) {
            let that = this
            let params = {
                permit_id: order_id,
            }
            try {
                jsTools.request({ url: 'pay_gift/get_receive_detail', params }).then(data => {
                    if (data && data.code == 0 && data.data) {
                        let res = data.data
                        that.rightType = res.right_type || ''
                        that.payGiftList = res.list || []
                        if (callback && typeof callback === 'function') {
                            callback()
                        }
                    } else {
                        if (callback && typeof callback === 'function') {
                            callback()
                        }
                        console.log(data.msg)
                    }
                })
            } catch (error) {
                console.log(error)
            }
        },
    },
}
</script>
