<template>
    <view>
        <view
            v-if="!isNeedAuth"
            @tap="onTap">{{ item.linkText }}</view>
        <form
            v-else
            report-submit
            :report-type="isAuth ? 'subscribe' : 'default'"
            skip-subscribe-authorize
            template-id="BD0108"
            subscribe-id="wz"
            @submit="onSubmit"
            class="auth-form">
            <view>{{ item.linkText }}</view>
            <button form-type="submit" class="auth-btn"></button>
        </form>
    </view>
</template>

<script>
/**
 * @file 问诊-手百消息授权
 * @author haoyan
 */
import {getQueryObject} from '../../utils/core';
import {request} from '../../utils/request';

export default {
    config: {
        component: true
    },
    props: {
        item: { // 按钮对象
            type: Object,
            default: {}
        },
        authUrl: {  // 授权url
            type: String,
            default: ''
        },
        isAuth: { // 用户选择可授权
            type: Boolean,
            default: true
        }
    },
    data() {
        return {
            isNeedAuth: false,
            callbackUrl: ''
        }
    },
    created() {
        // 获取 swanid
        this.$api.getSwanId().then(d => {
            // 校验是否需要调用授权组件
            request({
                url: this.authUrl,
                data: {
                    swanId: d.data.swanid
                }
            }).then(resp => {
                // 需要判断是否支持静默授权
                this.isNeedAuth =  resp.data.needAuth === 1;
                this.callbackUrl = resp.data.authConfirmUrl;
                if (this.$api.canIUse('form.skip-subscribe-authorize')) {
                    this.$emit('onAuth', {
                        isNeedAuth: this.isNeedAuth,
                        tip: resp.data.tip
                    });
                }
            });
        });
    },
    methods: {
        // 点击[提交]类型的按钮
        onSubmit(e) {
            request({
                url: this.callbackUrl,
                data: {
                    auth: this.isAuth ? 1 : 0,
                    formId: e.detail.formId
                }
            }).then(resp => {
                this.onTap();
            });
        },
        // 点击[普通]类型的按钮
        onTap () {
            this.$emit('tapBtn');
        }
    }
};
</script>

<style scoped>
.auth-form {
    position: absolute;
    top: 0;
    bottom: 0;
    right: 0;
    left: 0;
}
.auth-form .auth-btn {
    position: absolute;
    top: 0;
    bottom: 0;
    right: 0;
    left: 0;
    opacity: 0;
}
</style>
