import StoreModel from '@/common/model/Store'
import { isWeixinOfficial } from '@/core/platform'
import { isEmptyObject } from '@/utils/util'
// #ifdef H5
import wxofficial from '@/core/wxofficial'
// #endif

// 当前是否存在分享内容
let existShareData = false

/**
 * 获取微信公众号设置 (全部)
 */
const data = () => {
  return new Promise((resolve, reject) => {
    StoreModel.data().then(data => {
      resolve(data.clientData.wxofficial.setting)
    })
  })
}

// 获取微信公众号设置 (指定项)
const item = (key) => {
  return new Promise((resolve, reject) => {
    data().then(setting => resolve(setting[key]))
  })
}

// 是否开启微信公众号链接分享卡片
// #ifdef H5
const isWxofficialLinkShareCard = () => {
  return new Promise((resolve, reject) => {
    item('share').then(data => resolve(Boolean(data.enabled)))
  })
}
// #endif

/**
 * 设置微信公众号链接分享卡片内容(全局)
 * @param {Boolean} force 当已存在存在分享内容时 是否强制写入全局内容(用于页面onUnload事件中)
 */
// #ifdef H5
const setGlobalShareCard = async (force = false) => {
  const setting = await getSetting()
  if (isWeixinOfficial && setting.enabled) {
    // 获取当前页面url (不包含#及其后面部分)
    const url = window.location.href.split('#')[0]
    await wxofficial.setConfig()
    if (!existShareData || force) {
      // 设置分享卡片的内容
      wxofficial.updateShareData(setting)
    }
  }
}
// #endif

// 获取分享设置
const getSetting = async () => {
  return await item('share')
}

// 更新分享卡片内容
// #ifdef H5
const updateShareData = async (param) => {
  // 设置当前已存在分享内容
  existShareData = true
  // 合并用户配置和默认配置
  const setting = await getSetting()
  const options = Object.assign({}, setting, param)
  console.log('options', options)
  // 设置分享卡片的内容
  wxofficial.updateShareData(options)
}
// #endif

export default {
  data,
  item,
  // #ifdef H5
  isWxofficialLinkShareCard,
  updateShareData,
  setGlobalShareCard,
  // #endif
}