<template>
  <el-form :inline="true" :model="searchForm" class="search-form">
    <el-form-item label="UID">
      <el-input v-model="searchForm.userId" placeholder="用户ID" clearable @keyup.enter="handleSearch" style="width: 120px" />
    </el-form-item>
    <el-form-item label="推荐人UID">
      <el-input v-model="searchForm.parentId" placeholder="推荐人ID" clearable @keyup.enter="handleSearch" style="width: 120px" />
    </el-form-item>
    <el-form-item label="手机号">
      <el-input v-model="searchForm.mobile" placeholder="手机号" clearable @keyup.enter="handleSearch" style="width: 140px" />
    </el-form-item>
    <el-form-item label="昵称">
      <el-input v-model="searchForm.nickname" placeholder="昵称" clearable @keyup.enter="handleSearch" style="width: 120px" />
    </el-form-item>
    <el-form-item label="IP地址">
      <el-input v-model="searchForm.lastLoginIp" placeholder="IP地址" clearable @keyup.enter="handleSearch" style="width: 140px" />
    </el-form-item>
    <el-form-item label="登录时间">
      <el-date-picker
        v-model="dateRange"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        value-format="YYYY-MM-DD"
        style="width: 240px"
      />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="handleSearch">
        <el-icon><Search /></el-icon>查询
      </el-button>
      <el-button @click="handleReset">
        <el-icon><Refresh /></el-icon>重置
      </el-button>
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { Search, Refresh } from '@element-plus/icons-vue'
import type { UserListQuery } from '@/api/business/user'

const emit = defineEmits<{
  (e: 'search', params: Partial<UserListQuery>): void
  (e: 'reset'): void
}>()

const searchForm = reactive({
  userId: '',
  parentId: '',
  mobile: '',
  nickname: '',
  lastLoginIp: ''
})

const dateRange = ref<[string, string] | null>(null)

const handleSearch = () => {
  const params: Partial<UserListQuery> = {}
  
  if (searchForm.userId) {
    params.userId = parseInt(searchForm.userId)
  }
  if (searchForm.parentId) {
    params.parentId = parseInt(searchForm.parentId)
  }
  if (searchForm.mobile) {
    params.mobile = searchForm.mobile
  }
  if (searchForm.nickname) {
    params.nickname = searchForm.nickname
  }
  if (searchForm.lastLoginIp) {
    params.lastLoginIp = searchForm.lastLoginIp
  }
  if (dateRange.value && dateRange.value.length === 2) {
    params.startDate = dateRange.value[0]
    params.endDate = dateRange.value[1]
  }
  
  emit('search', params)
}

const handleReset = () => {
  searchForm.userId = ''
  searchForm.parentId = ''
  searchForm.mobile = ''
  searchForm.nickname = ''
  searchForm.lastLoginIp = ''
  dateRange.value = null
  emit('reset')
}
</script>

<style scoped>
.search-form {
  margin-bottom: 16px;
}
</style>
