<route lang="json5" type="page">
{
  layout: 'default',
  style: {
    navigationBarTitleText: '我的优惠券',
  },
}
</route>

<template>
  <view class="bg-white min-h-screen">
    <view class="space-y-4">
      <!-- 筛选条件 -->
      <view class="filter-section bg-gray-50 p-3">
        <view class="filter-row flex items-center gap-2">
          <wd-drop-menu custom-style="flex: 0 0 120px;">
            <wd-drop-menu-item
              v-model="filterForm.type"
              :title="getFilterTypeLabel()"
              :options="filterTypeOptions"
              @change="onFilterTypeChange"
            />
          </wd-drop-menu>
          <wd-input
            v-model="filterForm.value"
            :placeholder="getInputPlaceholder()"
            :disabled="!filterForm.type"
            custom-style="flex: 1"
            clearable
          />
          <wd-button type="primary" size="small" @click="handleSearch">搜索</wd-button>
        </view>
      </view>

      <!-- 优惠券列表 -->
      <view class="sticky-box-content w-100vw" v-if="couponList.length">
        <view class="coupon-list">
          <view class="coupon-item" v-for="item in couponList" :key="item.coupon2id">
            <!-- 优惠劵标题 -->
            <view class="coupon-header">
              <text class="coupon-code">券码: {{ item.coupon2code }}</text>
              <view class="flex items-center gap-2">
                <wd-tag
                  :type="
                    item.coupon2sype === 0
                      ? 'warning'
                      : item.coupon2sype === 1
                        ? 'success'
                        : item.coupon2sype === 2
                          ? 'danger'
                          : 'default'
                  "
                  custom-class="status-tag"
                >
                  {{
                    item.coupon2sype === 0
                      ? '审核中'
                      : item.coupon2sype === 1
                        ? '审核通过'
                        : item.coupon2sype === 2
                          ? '审核不通过'
                          : '未知状态'
                  }}
                </wd-tag>
                <wd-tag
                  :type="item.coupon2isused ? 'primary' : 'success'"
                  custom-class="status-tag"
                >
                  {{ item.coupon2isused ? '已使用' : '未使用' }}
                </wd-tag>
              </view>
            </view>
            <!-- 优惠劵信息 -->
            <view class="coupon-content">
              <view class="coupon-info">
                <text>券名: {{ item.coupon2mc || '暂无券名' }}</text>
              </view>
              <view class="coupon-info">
                <text>产品: {{ item.productsname || '暂无产品信息' }}</text>
              </view>
              <view class="coupon-info">
                <text>领劵时间: {{ formatDate(item.coupon2adddatetime) }}</text>
              </view>
              <view class="coupon-info">
                <text>用户名: {{ item.usersname || '暂无用户名' }}</text>
              </view>
              <view class="coupon-info">
                <text>电话: {{ item.usersphone || '暂无电话' }}</text>
              </view>
              <view class="coupon-info" v-if="item.coupon2sype === 2">
                <text>审核备注: {{ item.coupon2shbz || '暂无审核备注' }}</text>
              </view>
            </view>
            <!-- 优惠劵下单 -->
            <view
              class="coupon-footer flex justify-end"
              v-if="item.coupon2sype === 1 && !item.coupon2isused"
            >
              <view>
                <wd-button type="primary" size="small" @click="handleCouponOrder(item)">
                  优惠劵下单
                </wd-button>
              </view>
            </view>
            <!-- 修改信息按钮 - 审核中或审核不通过时显示 -->
            <view
              class="coupon-footer flex justify-end"
              v-if="item.coupon2sype === 0 || item.coupon2sype === 2"
            >
              <view>
                <wd-button type="warning" size="small" @click="handleModifyInfo(item)">
                  修改信息
                </wd-button>
              </view>
            </view>
          </view>
        </view>
      </view>
      <view class="sticky-box-content w-100vw" v-else>
        <wd-status-tip image="content" tip="暂无优惠券" />
      </view>

      <!-- loading -->
      <wd-overlay :show="overlayShow">
        <view class="wrapper w-full h-full flex items-center justify-center">
          <wd-loading />
        </view>
      </wd-overlay>

      <!-- 回到首页 -->
      <view class="sticky-box-content w-full box-border px-2 pb-2">
        <wd-button type="primary" block @click="handleBack">回到首页</wd-button>
      </view>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import { useCouponStore } from '@/store/coupon'
import { useAppStore } from '@/store/app'
import { useMessage } from 'wot-design-uni'
import dayjs from 'dayjs'

const appStore = useAppStore()
const couponStore = useCouponStore()
const couponList = ref([])
const overlayShow = ref(false)
const message = useMessage()

// 筛选表单数据
const filterForm = ref({
  type: '',
  value: '',
})

// 下拉选项数据
const filterTypeOptions = ref([
  { label: '用户名', value: 'username' },
  { label: '电话', value: 'phone' },
  { label: '身份证后4位', value: 'idCardLast4' },
])

// 各类型对应的选项数据
const usernameOptions = ref([])
const phoneOptions = ref([])
const idCardOptions = ref([])

// 原始优惠券数据（用于筛选）
const originalCouponList = ref([])

// 格式化日期
function formatDate(dateStr) {
  if (!dateStr) return '--'
  return dayjs(dateStr).format('YYYY-MM-DD HH:mm:ss')
}

// 获取当前筛选类型的标签
function getFilterTypeLabel() {
  if (!filterForm.value.type) return '筛选类型'

  const selectedOption = filterTypeOptions.value.find(
    (option) => option.value === filterForm.value.type,
  )
  return selectedOption ? selectedOption.label : '筛选类型'
}

// 获取输入框占位符
function getInputPlaceholder() {
  if (!filterForm.value.type) return '请先选择筛选类型'

  const placeholderMap = {
    username: '请输入用户名',
    phone: '请输入电话',
    idCardLast4: '请输入身份证后4位',
  }
  return placeholderMap[filterForm.value.type] || '请输入查询条件'
}

// 筛选类型变化处理
function onFilterTypeChange() {
  // 清空筛选值
  filterForm.value.value = ''
}

// 提取筛选选项（现在用于生成选项数据，虽然不直接使用但保留用于数据统计）
function extractFilterOptions(data) {
  const usernames = Array.from(new Set(data.map((item) => item.usersname).filter(Boolean)))
  const phones = Array.from(new Set(data.map((item) => item.usersphone).filter(Boolean)))
  const idCards = Array.from(
    new Set(data.map((item) => item.usersidcardnumber?.slice(-4)).filter(Boolean)),
  )

  usernameOptions.value = usernames.map((name) => ({ label: name, value: name }))
  phoneOptions.value = phones.map((phone) => ({ label: phone, value: phone }))
  idCardOptions.value = idCards.map((id) => ({ label: id, value: id }))
}

// 处理搜索
function handleSearch() {
  // 从原始数据中筛选
  let filteredList = [...originalCouponList.value]

  if (filterForm.value.type && filterForm.value.value) {
    if (filterForm.value.type === 'username') {
      filteredList = filteredList.filter(
        (item) => item.usersname && item.usersname.includes(filterForm.value.value),
      )
    } else if (filterForm.value.type === 'phone') {
      filteredList = filteredList.filter(
        (item) => item.usersphone && item.usersphone.includes(filterForm.value.value),
      )
    } else if (filterForm.value.type === 'idCardLast4') {
      filteredList = filteredList.filter(
        (item) =>
          item.usersidcardnumber && item.usersidcardnumber.slice(-4) === filterForm.value.value,
      )
    }
  }

  couponList.value = filteredList
}

function handleBack() {
  uni.switchTab({
    url: '/pages/index/index',
  })
}

onLoad(() => {
  overlayShow.value = true

  // 调用获取优惠券列表接口
  couponStore
    .getCoupon2List({ coupon2userid: appStore.appInfo.userid })
    .then((res) => {
      originalCouponList.value = res.Data || []
      couponList.value = [...originalCouponList.value]
      // 提取筛选选项
      extractFilterOptions(originalCouponList.value)
      overlayShow.value = false
    })
    .finally(() => {
      overlayShow.value = false
    })
})

// 优惠劵下单
function handleCouponOrder(item) {
  if (item.coupon2sype !== 1) {
    message.alert({
      title: '提示',
      msg: '优惠券未审核通过',
    })
    return
  }

  console.log(item)

  uni.navigateTo({
    url: `/pages/form/formStep4?productsid=${item.coupon2productids}&couponcode=${item.coupon2code}&usersid=${item.coupon2merchantid}`,
  })
}

// 修改信息
function handleModifyInfo(item) {
  // 跳转到基本信息修改页面，传递优惠券信息
  uni.navigateTo({
    url: `/pages/coupon/modify-info?coupon2sid=${item.coupon2sid}`,
  })
}
</script>

<style lang="scss" scoped>
.filter-section {
  margin-bottom: 8px;
  border-radius: 8px;
}

.filter-row {
  display: flex;
  gap: 8px;
  align-items: center;
}

.coupon-list {
  padding: 0 12px;
}

.coupon-item {
  position: relative;
  padding: 12px;
  margin-bottom: 12px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.coupon-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-bottom: 8px;
  border-bottom: 1px solid #f5f5f5;
}

.coupon-code {
  flex: 1;
  font-size: 16px;
  font-weight: 500;
  color: #333;
}

.status-tag {
  flex-shrink: 0;
}

.coupon-content {
  padding: 8px 0;
}

.coupon-info {
  margin-bottom: 4px;
  font-size: 14px;
  line-height: 1.5;
  color: #666;
}
</style>
