<template>
  <view class="container">
    <uni-section type="line" title="请求地址和租户ID配置" @click="handleClick"> </uni-section>
    <uni-forms label-position="top" label-width="100">
      <uni-forms-item label="系统请求地址">
        <uni-easyinput v-model="baseUrl" placeholder="请输入系统请求地址"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item v-if="showContent" label="租户ID">
        <uni-easyinput v-model="tenantId" placeholder="请输入租户ID"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item v-if="showContent" label="app更新地址">
        <uni-easyinput v-model="upgradeBaseUrl" placeholder="请输入"></uni-easyinput>
      </uni-forms-item>
    </uni-forms>
    <u-button type="primary" @click="submitForm">保存</u-button>
    <u-button v-if="showContent" type="primary" @click="clearCache">清除缓存</u-button>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'

// 响应式数据
const baseUrl = ref('')
const tenantId = ref('')
const upgradeBaseUrl = ref('')
const clickCount = ref(0) // 初始化点击次数为0
const threshold = 5 // 设置点击次数的阈值
const thresholdTime = 2 // 设置连续点击的时间阈值（秒）
let timer = null

// 计算属性：根据点击次数决定是否显示隐藏内容
const showContent = computed(() => {
  return clickCount.value >= threshold
})

// 页面加载时从缓存中读取已保存的配置
onMounted(() => {
  baseUrl.value = uni.getStorageSync('base_url')
  tenantId.value = uni.getStorageSync('tenant_id')
  upgradeBaseUrl.value = uni.getStorageSync('upgradeBaseUrl')
})

// 清除缓存方法
function clearCache() {
  uni.showModal({
    title: '提示',
    content: '确定要清空缓存？',
    success: function (res) {
      if (res.confirm) {
        try {
          uni.clearStorageSync()
          plus.runtime.restart()
        } catch (e) {}
      }
    }
  })
}

// 提交表单：保存配置到缓存
function submitForm() {
  if (!baseUrl.value) {
    uni.showToast({
      title: '请输入地址和租户',
      icon: 'none'
    })
    return
  }
  uni.setStorageSync('base_url', baseUrl.value)
  uni.setStorageSync('tenant_id', tenantId.value)
  uni.setStorageSync('upgradeBaseUrl', upgradeBaseUrl.value)
  uni.showToast({
    title: '保存成功',
    icon: 'none'
  })
  uni.navigateBack()
}

// 点击标题区域的处理逻辑：用于触发隐藏内容的显示
function handleClick() {
  // 如果已经达到阈值，显示内容后不再响应点击
  if (showContent.value) {
    clearTimeout(timer)
    return
  }
  // 增加点击次数
  clickCount.value++
  uni.showToast({
    title: `再点击${threshold - clickCount.value}次可显示内容`,
    icon: 'none',
    duration: 1000
  })

  // 清除之前的定时器（如果有），设置新的定时器
  clearTimeout(timer)
  timer = setTimeout(() => {
    // 如果还没达到阈值，则重置点击次数
    if (!showContent.value) {
      clickCount.value = 0
    }
  }, thresholdTime * 1000)
}
</script>

<style lang="scss" scoped>
.container {
  padding: 30px;
}
</style>
