
<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { onPageShow } from '@dcloudio/uni-app'

import JiayiList from '@/components/jiayiList/index.vue'
import { http } from '@/utils/request'

definePage({
  title: '竞对价格调查'
})

onPageShow(() => {
  // 从详情页返回时刷新数据
  const pages = getCurrentPages()
  const currentPage = pages[pages.length - 1]
  if (currentPage.options.perms) {
    perms.value = currentPage.options.perms as string
    console.log('收到的 perms 参数:', perms.value)
    fetchTaskList()
    fetchStationList()
    fetchCompetitorList()
  }
})

// 任务数据接口
interface Task {
  id: number
  taskName: string
  completionStatus: number
  executorName: string
  createTime: string
  stationId: number
  createType: number
  processTime: string
}

// 任务列表数据
const listData = ref<Task[]>([])
const loading = ref(false)
const loadingMore = ref(false)
const pageNum = ref(1)
const hasMore = ref(true)
const perms = ref('')

// 筛选相关变量
const filterStationId = ref('')
const filterCompetitorId = ref('')
const filterIsCompetitor = ref('')
const filterSurveyDateStart = ref('')
const filterSurveyDateEnd = ref('')
const filterTaskName = ref('')
const typeDataData = ref<any>({
  operatPrice:'operational',
})
// 下拉框数据
const stationList = ref<Array<{ value: string; label: string }>>([])
const competitorList = ref<Array<{ value: string; label: string }>>([])
const isCompetitorList = ref<Array<{ value: string; label: string }>>([
  { value: '1', label: '是' },
  { value: '0', label: '否' }
])

// 时间选择器相关
const showSurveyDateStartPicker = ref(true)
const showSurveyDateEndPicker = ref(true)
const calendarValue = ref('')

// 获取加油站列表
async function fetchStationList() {
  try {
    const response = await http.get<any[]>('/sysStation/station/selectAllSysStationList')
    stationList.value = response.map(item => ({
      value: item.id.toString(),
      label: item.stationName || ''
    }))
    console.log(stationList.value)
  } catch (error) {
    console.error('获取加油站列表失败:', error)
  }
}

// 获取竞对油站列表
async function fetchCompetitorList() {
  try {
    const response = await http.get<any[]>('/gasCompetitiveStation/station/list')

    competitorList.value = response.rows.map(item => ({
      value: item.id.toString(),
      label: item.competitorName || ''
    }))
    console.log(competitorList.value)
  } catch (error) {
    console.error('获取竞对油站列表失败:', error)
  }
}

// 处理时间选择确认
function handleConfirm(date: any, type: 'start' | 'end') {
  console.log('确认日期:', date)
  
  // 处理日期值，确保是 yyyy-mm-dd HH:MM:SS 格式
  let formattedDate = ''
  if (typeof date === 'object' && date.value) {
    // 如果是时间戳对象
    const dateObj = new Date(date.value)
    const year = dateObj.getFullYear()
    const month = String(dateObj.getMonth() + 1).padStart(2, '0')
    const day = String(dateObj.getDate()).padStart(2, '0')
    formattedDate = `${year}-${month}-${day} 00:00:00`
  } else if (typeof date === 'number') {
    // 如果是时间戳数字
    const dateObj = new Date(date)
    const year = dateObj.getFullYear()
    const month = String(dateObj.getMonth() + 1).padStart(2, '0')
    const day = String(dateObj.getDate()).padStart(2, '0')
    formattedDate = `${year}-${month}-${day} 00:00:00`
  } else if (typeof date === 'string') {
    // 如果已经是字符串
    if (date.includes('T')) {
      // 如果包含 T，转换为空格分隔
      formattedDate = date.replace('T', ' ').substring(0, 19)
    } else if (date.length === 10) {
      // 如果是 yyyy-mm-dd 格式，添加时间部分
      formattedDate = date + ' 00:00:00'
    } else {
      formattedDate = date
    }
  }
  console.log(formattedDate)
  if (type === 'start') {
    filterSurveyDateStart.value = formattedDate
  } else {
    filterSurveyDateEnd.value = formattedDate
  }
  
  calendarValue.value = formattedDate
}

// 获取任务列表数据
async function fetchTaskList(isLoadMore = false) {
  if (isLoadMore) {
    loadingMore.value = true
  } else {
    loading.value = true
    pageNum.value = 1
    hasMore.value = true
  }
  try {
    // 构建请求参数
    const params = {
      pageSize: 10,
      pageNum: pageNum.value,
    }
    // 添加筛选条件
    if (filterStationId.value) {
      params.stationId = filterStationId.value
    }
    if (filterCompetitorId.value) {
      params.competitorId = filterCompetitorId.value
    }
    if (filterIsCompetitor.value) {
      params.isCompetitor = filterIsCompetitor.value
    }
    if (filterSurveyDateStart.value) {
      params.surveyDateStart = filterSurveyDateStart.value
    }
    
    if (filterSurveyDateEnd.value) {
      params.surveyDateEnd = filterSurveyDateEnd.value
    }
    
    if (filterTaskName.value) {
      params.taskName = filterTaskName.value
    }
    // params.isComplete = 0
    params.directoryType = typeDataData.value[perms.value]

    const response = await http.get<{ data: any[], total: number }>('/formCompetitorMarketingSurvey/survey/list', params)
    const newData = response.data || []   
    
    // 转换数据格式为组件所需的格式
    const formattedData = newData.map(item => ({
      detailType: 'task',
      id: item.id,
      taskId: item.taskId,
      button: '',
      title: item.taskName || '',
      statusName: item.completionStatus === 0 ? '待完成' : item.completionStatus === 1 ? '逾期完成' : '按时完成',
      userName: item.executorName || '' + '/' + item.stationName || '',
      createTime: item.createTime || '',
    }))
    
    if (isLoadMore) {
      listData.value = [...(listData.value || []), ...formattedData]
    } else {
      listData.value = formattedData
    }
    // 检查是否还有更多数据
    hasMore.value = (newData || []).length === 10
    // 增加页码
    pageNum.value++
  }
  catch (error) {
    uni.showToast({
      title: '获取任务列表失败',
      icon: 'none',
    })
  }
  finally {
    loading.value = false
    loadingMore.value = false
  }
}

// 处理刷新
function handleRefresh() {
  fetchTaskList()
}

// 处理加载更多
function handleLoadMore() {
  if (!loadingMore.value && hasMore.value) {
    fetchTaskList(true)
  }
}

// 筛选相关方法
function handleFilter() {
  console.log('筛选数据')
}

function handleFilterConfirm() {
  console.log('筛选确定')
  // 重新获取数据，应用筛选条件
  fetchTaskList()
}

function handleFilterCancel() {
  console.log('筛选取消')
}

function handleReset() {
  console.log('重置筛选条件')
  // 清空所有筛选条件
  filterStationId.value = ''
  filterCompetitorId.value = ''
  filterIsCompetitor.value = ''
  filterSurveyDateStart.value = ''
  filterSurveyDateEnd.value = ''
  filterTaskName.value = ''
}

</script>

<template>
  <view class="page min-h-screen bg-gray-100">
    <JiayiList
      :data="listData"
      @refresh="handleRefresh"
      @filter="handleFilter"
      @filter-confirm="handleFilterConfirm"
      @filter-cancel="handleFilterCancel"
      @reset="handleReset"
      @load-more="handleLoadMore"
    >
      <template #default="{ item }">
        <view class="p-4 bg-white border-b border-gray-200">
          <view class="flex justify-between items-center mb-2">
            <text class="text-lg font-medium">{{ item.taskName }}</text>
            <text class="text-sm px-2 py-1 rounded" :class="item.statusClass">
              {{ item.statusName }}
            </text>
          </view>
          <view class="flex justify-between items-center text-sm text-gray-600">
            <text>执行人：{{ item.executorName }}</text>
            <text>{{ item.createTime }}</text>
          </view>
        </view>
      </template>
      <template #filter-content>
        <view class="p-4">
          <view class="text-lg font-medium mb-4">筛选条件</view>
          
          <!-- 任务名称搜索 -->
          <view class="mb-4">
            <text class="block mb-2">任务名称</text>
            <wd-input v-model="filterTaskName" placeholder="请输入任务名称" />
          </view>
          
          <!-- 加油站下拉框 -->
          <view class="mb-4">
            <text class="block mb-2">加油站</text>
            <wd-picker 
              :columns="[stationList]" 
              v-model="filterStationId" 
            />
          </view>
          
          <!-- 竞对油站下拉框 -->
          <view class="mb-4">
            <text class="block mb-2">竞对油站</text>
            <wd-picker 
              :columns="[competitorList]" 
              v-model="filterCompetitorId" 
            />
          </view>
          
          <!-- 是否竞争下拉框 -->
          <view class="mb-4">
            <text class="block mb-2">是否竞争</text>
            <wd-picker 
              :columns="[isCompetitorList]" 
              v-model="filterIsCompetitor" 
            />
          </view>
          
          <!-- 调查日期开始日期 -->
          <view class="mb-4">
            <text class="block mb-2">调查日期开始</text>
            <view class="relative">
              <wd-calendar 
                v-model="filterSurveyDateStart" 
                @confirm="(date) => handleConfirm(date, 'start')" 
                v-if="showSurveyDateStartPicker"
              />
            </view>
          </view>
          
          <!-- 调查日期结束日期 -->
          <view class="mb-4">
            <text class="block mb-2">调查日期结束</text>
            <view class="relative">
              <wd-calendar 
                v-model="filterSurveyDateEnd" 
                @confirm="(date) => handleConfirm(date, 'end')" 
                v-if="showSurveyDateEndPicker"
              />
            </view>
          </view>
          
        </view>
      </template>
    </JiayiList>
  </view>
</template>
