/**
 * Request WeChat Mini Program Subscription Message
 * Template ID: iG5GYMPQAgKxIE9zZNOgKS6tCURhM9p9AC8iZ3Uj3uA
 */
const DEFAULT_TEMPLATE_ID = 'iG5GYMPQAgKxIE9zZNOgKS6tCURhM9p9AC8iZ3Uj3uA';

export const requestSubscription = (tmplIds = [DEFAULT_TEMPLATE_ID], silent = false) => {
    return new Promise((resolve) => {
        if (!wx.requestSubscribeMessage) {
            if (!silent) console.warn('Current version does not support subscribe message');
            resolve({ success: false, errMsg: 'Not supported' });
            return;
        }

        wx.requestSubscribeMessage({
            tmplIds: tmplIds,
            success(res) {
                // If any of the requested IDs are accepted
                const isAccepted = tmplIds.some(id => res[id] === 'accept');
                resolve({ success: isAccepted, res });
            },
            fail(err) {
                if (!silent) console.error('Subscription failed', err);

                // 20004: User closed main switch in settings
                if (err.errCode === 20004 && !silent) {
                    wx.showModal({
                        title: '提示',
                        content: '请在设置中开启订阅消息通知',
                        confirmText: '去开启',
                        success: (modalRes) => {
                            if (modalRes.confirm) {
                                wx.openSetting();
                            }
                        }
                    });
                }
                resolve({ success: false, error: err });
            }
        });
    });
};

export const checkSubscriptionSettings = (tmplId = DEFAULT_TEMPLATE_ID) => {
    return new Promise((resolve) => {
        if (!wx.getSetting) {
            resolve(undefined);
            return;
        }

        wx.getSetting({
            withSubscriptions: true,
            success(res) {
                const itemSettings = (res.subscriptionsSetting && res.subscriptionsSetting.itemSettings) || {};
                resolve(itemSettings[tmplId]);
            },
            fail() {
                resolve(undefined);
            }
        });
    });
};
