<template>
  <view class="more-tips">
    <view class="more-tips-scroll">
      <view
        class="more-tips-item"
        v-for="(item, index) in itemList"
        :key="index"
      >
        <button
          class="reset-btn more-tips-item-title"
          :open-type="needAuth ? 'getPhoneNumber' : ''"
          @getphonenumber="handleGetPhoneNumber"
          @click="handleClick(item)"
        >
          {{ item }}
        </button>
      </view>
    </view>
  </view>
</template>

<script setup>
import { defineProps, ref } from "vue";
import { onLogin, checkToken } from "@/hooks/useGoLogin";

const emits = defineEmits(["replySent"]);
const needAuth = ref(true);
let pendingText = "";

defineProps({
  itemList: {
    type: Array,
    default: [
      "定温泉票",
      "定酒店",
      "优惠套餐",
      "亲子玩法",
      "了解交通",
      "看看酒店",
      "看看美食",
    ],
  },
});

const sendReply = (text) => {
  checkToken().then(() => {
    emits("replySent", text); // 向父组件传递数据
  });
};

// 处理点击事件
const handleClick = (text) => {
  // 检查本地token
  const token = uni.getStorageSync("token");

  if (token) {
    // 情况2：token有值，直接发送回复，此时open-type为空字符串
    needAuth.value = false;
    sendReply(text);
  } else {
    // 情况1：token没有值，设置需要授权状态，触发微信授权
    needAuth.value = true;
    pendingText = text;
    // 由于open-type已经动态绑定为'getPhoneNumber'，点击会自动触发授权
  }
};

// 处理微信授权回调
const handleGetPhoneNumber = async (e) => {
  await onLogin(e);

  // 授权成功后发送之前存储的文本
  if (pendingText) {
    sendReply(pendingText);
    pendingText = "";
  }

  needAuth.value = false;
};
</script>

<style lang="scss" scoped>
@import "./styles/ChatMoreTips.scss";
</style>
