<template>
  <web-view :src="src" @message="onMessage"/>
</template>

<script setup lang="ts">
import {ref, watch, nextTick} from "vue";
import {onLoad, onShow, onShareAppMessage, onShareTimeline} from "@dcloudio/uni-app";
import {useGlobalStore} from "../../stores/global";
import {useUserStore} from "../../stores/user";
import {jump, JumpType} from "../../utils";

const userStore = useUserStore();
const globalStore = useGlobalStore()

function getRegistered() {
  return !!(userStore.userInfo && userStore.userInfo?.memberId !== "not_login")
}

const pageOptions = ref({})
const src = ref("")
const registered = ref(undefined)

const urlMap = {
  //'main': 'http://192.168.0.5:8001/#/page',
  'main': 'https://momclub.feihe.com/h5/#/page',
  //'main': 'https://momclub-test.feihe.com/h5/#/page',
  //'main': 'https://momclub-uat.feihe.com/h5/#/page',
};

const shareData = ref(null)

const handleBack = () => {
  try {
    uni.navigateBack({
      delta: 1,
      fail: () => {
        // 如果返回失败，跳转到首页
        uni.redirectTo({
          url: '/pages/index/index'
        })
      }
    })
  } catch (error) {
    console.log('返回失败:', error)
    uni.redirectTo({
      url: '/pages/index/index'
    })
  }
}

async function ensureAutoLogin() {
  //debugger
  //if (!globalStore.cuk) {
    await userStore.normalAutoLogin()
  //}
}

onShow(async () => {
  const oldVal = registered.value

  await ensureAutoLogin()
  await userStore.loadUserInfo()

  registered.value = getRegistered()

  if (oldVal === undefined) {
    if (pageOptions.value.needLogin && !registered.value) {
      jump({
        type: JumpType.INNER,
        url: '/pages/activity/register',
      })
    }
  } else {
    if (registered.value === false) {
      uni.showToast({
        title: "授权失败，即将返回",
        icon: "none",
      });
      setTimeout(() => {
        handleBack()
      }, 1000)
    }
  }
})

function joinUrlAndQs(url, qs) {
  return qs
    ? url + (url.includes('?') ? (url.endsWith('?') ? '' : '&') : '?') + qs
    : url
}

watch(() => registered.value, (newVal, oldVal) => {
  if (!pageOptions.value.needLogin || newVal) {
    src.value = ''

    nextTick(() => {
      initOk(newVal)
    })
  }
})

function initOk() {
  console.log(userStore.userInfo)

  let url = "";

  const options = pageOptions.value

  if (options.type) {
    const type = options.type;
    url = urlMap[type];
  } else if (options.url) {
    url = decodeURIComponent(options.url)
  }

  const params = {}

  const {unionId, cuk} = globalStore
  if (unionId && !params.unionId) params.unionId = unionId
  if (cuk && !params.cuk) params.cuk = cuk
  const {memberId} = userStore.userInfo
  if (memberId) params.crmId = memberId

  const paramStr = Object.keys(params)
    .filter(key => params[key] !== undefined && params[key] !== null && params[key] !== '')
    .map(key => `${key}=${encodeURIComponent(params[key])}`)
    .join('&')

  url = joinUrlAndQs(url, paramStr)
  if (options.params) {
    url = joinUrlAndQs(url, decodeURIComponent(options.params))
  }

  src.value = url
  console.log('webview url:', url)
}

onLoad(async (options) => {
  pageOptions.value = options
  console.log('页面参数:', options)

  wx.showShareMenu({
    withShareTicket: true,
    menus: ['shareAppMessage', 'shareTimeline']
  })
});

function onMessage(e) {
  const data = e.detail.data
  const lastData = data[data.length - 1]
  console.log('webview 消息接收:', lastData)
  switch (lastData.type) {
    case 'share':
      shareData.value = lastData.payload
      break;
  }
}

function shareHook() {
  if (shareData.value) {
    const {url, title, imageUrl = ''} = shareData.value

    console.log('使用分享数据:', shareData.value)

    return {
      title,
      path: url || '/pages/index/index',
      imageUrl,
      success: function (res) {
        console.log('分享成功:', res)
        //星妈会埋点方法，用户分享成功后触发事件
      },
      fail: function (res) {
        console.log('分享失败:', res)
      },
      complete: function (res) {
        console.log('分享完成:', res)
      }
    }
  }

  // 如果没有分享数据，返回默认分享
  return {
    path: '/pages/index/index'
  }
}

onShareAppMessage((options) => {
  console.log('分享给朋友数据:', shareData.value)

  return shareHook()
})
</script>

<script lang="ts">
/*export default {
  onShareAppMessage() {
    return this.shareHook()
  }
}*/
</script>