<!-- 使用 type="home" 属性设置首页，其他页面不需要设置，默认为page；推荐使用json5，更强大，且允许注释 -->
<route lang="json5" type="home">
{
  style: {
    navigationStyle: 'custom',
    navigationBarTitleText: '首页',
  },
}
</route>
<template>
  <view
    class="bg-white overflow-hidden pt-2 px-4"
    :style="{ marginTop: safeAreaInsets?.top + 'px' }"
  >
    <!-- 顶部标题 -->
    <view class="text-xl font-bold text-center py-3 bg-white">达州农机优惠券</view>

    <wd-swiper
      :list="swiperList"
      autoplay
      v-model:current="current"
      :indicator="{ type: 'dots-bar' } as any"
      @click="handleSwiperClick"
      @change="handleSwiperChange"
      v-if="!statisticsDataShow"
    ></wd-swiper>

    <!-- 数据统计卡片 -->
    <view class="grid grid-cols-2 gap-3 mb-4" v-else>
      <!-- 总销售额 -->
      <statistics-card
        title="总销售额"
        :value="statisticsData[0]"
        suffix="万元"
        color="blue"
        :duration="2000"
      />

      <!-- 总订单数 -->
      <statistics-card
        title="总订单数"
        :value="statisticsData[1]"
        suffix="单"
        color="amber"
        :duration="4000"
      />

      <!-- 本季度销售额 -->
      <statistics-card
        title="本季度销售额"
        :value="statisticsData[2]"
        suffix="万元"
        color="emerald"
        :duration="4000"
      />

      <!-- 本季度订单数 -->
      <statistics-card
        title="本季度订单数"
        :value="statisticsData[3]"
        suffix="单"
        color="indigo"
        :duration="4000"
      />

      <!-- 本月销售额 -->
      <statistics-card
        title="本月销售额"
        :value="statisticsData[4]"
        suffix="万元"
        color="purple"
        :duration="4000"
      />

      <!-- 本月订单数 -->
      <statistics-card
        title="本月订单数"
        :value="statisticsData[5]"
        suffix="单"
        color="rose"
        :duration="2000"
      />
    </view>

    <view class="pb-4">
      <!-- 网点地址标题 -->
      <view class="text-lg font-bold py-4 border-b border-gray-100">农机销售网点</view>

      <wd-status-tip image="comment" tip="暂无数据" v-if="locationList.length === 0" />

      <!-- 网点列表 -->
      <view class="divide-y divide-gray-100" v-else>
        <view
          v-for="(item, index) in locationList"
          :key="index"
          class="py-3 flex items-center justify-between"
        >
          <view class="flex items-start gap-2">
            <wd-icon name="location" class="text-green-500 mt-1" />
            <view>
              <view class="font-medium">{{ item.name }}</view>
              <view class="text-sm text-gray-500">{{ item.address }}</view>
            </view>
          </view>
          <view class="flex gap-2">
            <view class="p-1 mr-1">
              <wd-icon
                name="call"
                class="bg-green-500 text-white rounded-md"
                @tap="handleCall(item.phone)"
              />
            </view>

            <view class="p-1">
              <wd-icon
                name="cart"
                class="bg-green-500 text-white rounded-md"
                @tap="handleGoods(item)"
              />
            </view>
          </view>
        </view>
      </view>

      <!-- 申请记录 -->
      <view class="mt-4">
        <view class="flex items-center justify-between border-b border-gray-100 py-4">
          <text class="text-lg font-bold">最近申请</text>
          <view class="ml-auto">
            <wd-button type="success" size="small" round @tap="handleApply">我要申请</wd-button>
          </view>
        </view>
        <view class="bg-white border border-gray-200 rounded-lg p-2">
          <view
            v-for="(record, index) in applyRecords"
            :key="index"
            class="flex items-center gap-2 py-1"
          >
            <text class="text-sm">{{ desensitizeName(record.name) }}</text>
            <text class="text-xs text-green-500">申请</text>
            <text class="text-xs text-gray-400 ml-auto">
              {{ formatTimeText(record.time) }}已申请优惠劵
            </text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script lang="ts" setup>
import banner1 from '@/static/banner1.png'
import { ref } from 'vue'
import { useUserStore } from '@/store/user'
import { useDictStore } from '@/store/dict'
import StatisticsCard from '@/components/StatisticsCard.vue'

const userStore = useUserStore()
const dictStore = useDictStore()

const statisticsDataShow = ref(false)
const current = ref<number>(0)
const swiperList = ref([banner1, banner1, banner1])

const statisticsData = ref([0, 0, 0, 0, 0, 0])

// 获取安全区域距离
const { safeAreaInsets } = uni.getWindowInfo()

// 轮播图事件处理
function handleSwiperClick(e: any) {
  // console.log('轮播图点击', e)
}

function handleSwiperChange(e: any) {
  // console.log('轮播图切换', e)
}

// 网点数据
const locationList = ref([])

// 获取销售点列表（users表,usersnature=渠道）
const getUserList = async () => {
  const userList = await userStore.getSellUserList()

  locationList.value = userList.map((item: any) => ({
    name: item.usersname,
    address: item.usersaddress,
    phone: item.usersphone,
    usersid: item.usersid,
  }))
}

// 格式化时间文本
function formatTimeText(time: Date) {
  const diffMinutes = Math.floor((Date.now() - time.getTime()) / (1000 * 60))
  if (diffMinutes < 60) {
    return `${diffMinutes}分钟前`
  } else {
    const hours = Math.floor(diffMinutes / 60)
    return `${hours}小时前`
  }
}

// 申请记录
const applyRecords = ref([
  { name: '王思聪', time: new Date(Date.now() - 5 * 60 * 1000) },
  { name: '李美丽', time: new Date(Date.now() - 15 * 60 * 1000) },
  { name: '张三', time: new Date(Date.now() - 30 * 60 * 1000) },
  { name: '王五', time: new Date(Date.now() - 60 * 60 * 1000) },
  { name: '赵六', time: new Date(Date.now() - 2 * 60 * 60 * 1000) },
])

// 脱敏name字段 如果姓名2个字，最后一个字替换为*；如果大于3个字，保留第一个和最后一个字，中间全部替换为*；
function desensitizeName(name: string) {
  if (name.length === 2) {
    return name.substring(0, 1) + '*'
  } else if (name.length >= 3) {
    const stars = '*'.repeat(name.length - 2)
    return name.charAt(0) + stars + name.charAt(name.length - 1)
  }
  return name
}

// 处理拨打电话
function handleCall(phone: string) {
  uni.makePhoneCall({
    phoneNumber: phone,
  })
}

// 销售网点跳转
function handleGoods(location: any) {
  console.log(location)

  uni.navigateTo({
    url: `/pages/form/formStep2?usersid=${location.usersid}`,
  })
}

// 处理申请
function handleApply() {
  uni.navigateTo({
    url: '/pages/form/formStep1',
  })
}

// 获取统计数据
const getStatisticsData = async () => {
  const configList = await dictStore.getConfigList('mini_program_index_sumary')
  if (configList.length > 0) {
    // 获取统计数据是否显示配置
    const statisticsDataShowConfig = configList.find(
      (item) => item.groupname === 'mini_program_index_sumary_show',
    )
    statisticsDataShow.value = statisticsDataShowConfig?.substance === '1'
    // 统计数据项
    const statisticsDataConfig = configList.find(
      (item) => item.groupname === 'mini_program_index_sumary_data',
    )
    statisticsData.value = statisticsDataConfig?.substance.split(',').map((item) => Number(item))
  }
}

// // 获取统计数据是否显示配置
// const getStatisticsDataShow = async () => {
//   const configList = await dictStore.getConfigList('mini_program_index_sumary_show')
//   if (configList.length > 0) {
//     // 将字符串分割后转换为数字类型
//     statisticsDataShow.value = configList[0].substance === '1'
//   }
// }

onShow(() => {
  getUserList()
  getStatisticsData()
  // getStatisticsDataShow()
})
</script>

<style>
.main-title-color {
  color: #d14328;
}
</style>

<style lang="scss">
.wd-icon {
  font-size: 20px;
}
</style>
