<template>
  <!-- 抽屉搜索组件 -->
  <van-popup v-model:show="showDrawer"
    position="right"
    class="search-drawer"
    :style="{ width: '85%', height: '100%' }"
    teleport="body"
    @close="handleClose">

    <!-- 抽屉头部 -->
    <van-nav-bar title="筛选条件"
      left-text="关闭"
      left-arrow
      @click-left="handleClose" />

    <!-- 搜索表单内容 -->
    <div class="search-content">
      <van-cell-group inset>
        <!-- 计划月份 -->
        <van-field :modelValue="parseTime(queryParams.salesMonth, '{y}-{m}')"
          label="计划月份"
          placeholder="选择计划月份"
          readonly
          is-link
          @click="showMonthPicker = true">
          <template #input>
            <span>{{ parseTime(queryParams.salesMonth, '{y}-{m}') || '请选择' }}</span>
          </template>
        </van-field>

        <!-- 大区/战区 -->
        <van-field v-model="queryParams.deptName"
          label="大区/战区"
          placeholder="请输入大区/战区"
          @update:model-value="handleChange"
          clearable />

        <!-- 经销商编码/名称 -->
        <van-field v-model="queryParams.dealerCN"
          label="经销商编码/名称"
          placeholder="请输入经销商编码/名称"
          @update:model-value="handleChange"
          clearable />

        <!-- 系统名称 -->
        <van-field v-model="queryParams.lineNameLike"
          label="系统名称"
          placeholder="请输入系统名称"
          @update:model-value="handleChange"
          clearable />

        <!-- 门店编码/名称 -->
        <van-field v-if="showStoreSearch"
          v-model="queryParams.storeCN"
          label="门店编码/名称"
          placeholder="请输入门店编码/名称"
          @update:model-value="handleChange"
          clearable />

        <!-- 数据筛选 -->
        <van-field v-model="queryParams.rqStatus"
          label="数据筛选"
          placeholder="请选择筛选状态"
          readonly
          is-link
          @click="showStatusPicker = true">
          <template #input>
            <span>{{ getStatusText(queryParams.rqStatus) }}</span>
          </template>
        </van-field>
      </van-cell-group>

      <!-- 月份选择器 -->
      <van-popup v-model:show="showMonthPicker"
        position="bottom"
        teleport="body">
        <van-date-picker v-model="currentMonth"
          title="选择计划月份"
          :columns-type="['year', 'month']"
          :min-date="minDate"
          :max-date="maxDate"
          @confirm="confirmMonth"
          @cancel="showMonthPicker = false" />
      </van-popup>

      <!-- 状态选择器 -->
      <van-popup v-model:show="showStatusPicker"
        position="bottom"
        teleport="body">
        <van-picker :columns="statusOptions"
          @confirm="confirmStatus"
          @cancel="showStatusPicker = false" />
      </van-popup>

      <!-- 操作按钮 -->
      <div class="action-buttons">
        <van-button type="default"
          size="large"
          @click="handleReset"
          class="reset-btn">
          <van-icon name="replay" /> 重置
        </van-button>
        <van-button type="primary"
          size="large"
          @click="handleConfirm"
          class="confirm-btn">
          <van-icon name="success" /> 确定
        </van-button>
      </div>
    </div>
  </van-popup>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { parseTime } from '@/utils'

const { proxy } = getCurrentInstance()

const props = defineProps({
  showSearch: {
    type: Boolean,
    default: false
  },
  showStoreSearch: {
    type: Boolean,
    default: true
  },
  queryParams: {
    type: Object,
    default: () => ({})
  }
})

const emits = defineEmits(['change', 'update:showSearch'])

// 抽屉显示状态
const showDrawer = computed({
  get: () => props.showSearch,
  set: (value) => emits('update:showSearch', value)
})

// 选择器状态
const showMonthPicker = ref(false)
const showStatusPicker = ref(false)
const currentMonth = ref([])

// 日期范围
const minDate = new Date(2016, 0, 1)
const maxDate = new Date(new Date().getFullYear(), new Date().getMonth() + 1, 31)

// 状态选项
const statusOptions = [
  { text: '全部', value: '' },
  { text: '未执行', value: '未执行' }
]

// 获取状态文本
const getStatusText = (value) => {
  const option = statusOptions.find(item => item.value === value)
  return option ? option.text : '全部'
}

// 确认月份选择
const confirmMonth = ({ selectedValues: value }) => {
  // value 是 [2025, 2] 这种格式
  const year = value[0]
  const month = String(value[1]).padStart(2, '0')
  props.queryParams.salesMonth = new Date(`${year}-${month}-01`)
  showMonthPicker.value = false
  handleChange()
}

// 确认状态选择
const confirmStatus = (value) => {
  props.queryParams.rqStatus = value.selectedOptions[0]?.value || ''
  showStatusPicker.value = false
  handleChange()
}

// 处理变化
const handleChange = () => {
  emits('change')
}

// 关闭抽屉
const handleClose = () => {
  showDrawer.value = false
}

// 重置表单
const handleReset = () => {
  // 重置所有查询参数
  Object.keys(props.queryParams).forEach(key => {
    if (key !== 'pageNum' && key !== 'pageSize') {
      props.queryParams[key] = ''
    }
  })
  handleChange()
}

// 确定搜索
const handleConfirm = () => {
  handleChange()
  handleClose()
}

// 监听外部showSearch变化
watch(() => props.showSearch, (newVal) => {
  if (newVal) {
    // 打开抽屉时初始化当前月份
    if (props.queryParams.salesMonth) {
      // 如果是日期类型转成字符串
      const [year, month] = props.queryParams.salesMonth.toISOString().split('T')[0].substring(0, 7).split('-')
      // currentMonth = [2025, 02] 这种格式
      currentMonth.value = [parseInt(year), parseInt(month)]
    } else {
      // 当前年月日，注意：getMonth()返回0-11，需要+1变成1-12
      const now = new Date()
      currentMonth.value = [now.getFullYear(), now.getMonth() + 1]
    }
  }
})
</script>

<style scoped
  lang="scss">
  .search-drawer {
    .search-content {
      height: calc(100% - 46px); // 减去导航栏高度
      overflow-y: auto;
      padding: 16px;

      .van-cell-group {
        margin-bottom: 20px;
      }

      .action-buttons {
        position: fixed;
        bottom: 0;
        left: 0;
        right: 0;
        background: #fff;
        padding: 16px;
        display: flex;
        gap: 12px;
        border-top: 1px solid #ebedf0;

        .reset-btn,
        .confirm-btn {
          flex: 1;

          :deep(.van-button__content) {
            display: flex;
            align-items: center;
            gap: 4px;
          }
        }
      }
    }
  }
</style>