<!-- 使用 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>

    <!-- 数据统计卡片 -->
    <view class="grid grid-cols-2 gap-3 mb-4">
      <!-- 总销售额 -->
      <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>

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

    <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 { useAppStore } from '@/store/app'
import { useDictStore } from '@/store/dict'
import { useMessage } from 'wot-design-uni'
import dayjs from 'dayjs'
import StatisticsCard from '@/components/StatisticsCard.vue'

const userStore = useUserStore()
const appStore = useAppStore()
const dictStore = useDictStore()
const message = useMessage()
// const current = ref<number>(0)
// const swiperList = ref([banner1, banner1, banner1])

const statisticsData = ref({})

// 获取安全区域距离
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',
  })
}

uni.$on('authComplete', function (data) {
  if (data.result) {
    showCompleteDialog()
  }
})

// 入口完善信息提示
const showCompleteDialog = () => {
  console.log(appStore.isLogined, userStore.isAuthComplete, appStore.needAlertCompleteInDays)

  // 如果已登录且已完善信息，则不提示
  if (appStore.isLogined && userStore.isAuthComplete) return

  // 如果需要提示完善信息，并且N天内没有提示过，则提示
  if (appStore.needAlertCompleteInDays) {
    message
      .confirm({
        msg: '您还未完善个人信息, 无法享受优惠劵活动, 点击按钮完善信息',
        title: '提示',
        confirmButtonText: '去完善',
        cancelButtonText: '继续浏览',
      })
      .then(() => {
        uni.navigateTo({
          url: '/pages-sub/user/index',
        })
      })
      .catch(() => {
        appStore.setAlertCompleteInfo({
          hasAlert: true,
          time: dayjs().format('YYYY-MM-DD HH:mm:ss'),
        })
      })
  }
}

// 获取统计数据
const getStatisticsData = async () => {
  const configList = await dictStore.getConfigList('mini_program_index_sumary')
  if (configList.length > 0) {
    // 将字符串分割后转换为数字类型
    statisticsData.value = configList[0].substance.split(',').map((item) => Number(item))
  }
}

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

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

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