<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 filterSurveyDateStart = ref('')
const filterSurveyDateEnd = ref('')
const filterTaskName = ref('')
const typeDataData = ref<any>({
  operatSales:'operational',
})
// 下拉框数据
const stationList = ref<Array<{ value: string; label: string }>>([])
const competitorList = ref<Array<{ value: string; label: string }>>([])

// 时间选择器相关
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)
  
  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')) {
      formattedDate = date.replace('T', ' ').substring(0, 19)
    } else if (date.length === 10) {
      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 (filterSurveyDateStart.value) {
      params.surveyDateStart = filterSurveyDateStart.value
    }
    
    if (filterSurveyDateEnd.value) {
      params.surveyDateEnd = filterSurveyDateEnd.value
    }
    
    if (filterTaskName.value) {
      params.taskName = filterTaskName.value
    }
    params.directoryType = typeDataData.value[perms.value]
    const response = await http.get<{ data: any[], total: number }>('/formCompetitorSalesSurvey/survey/list', params)
    const newData = response.rows || []   
    
    const formattedData = newData.map(item => ({
      detailType: 'task',
      id: item.id,
      taskId: item.taskId,
      button: '',
      title: item.taskName || '',
      statusName: item.completionStatus === 0 ? '待完成' : item.completionStatus === 1 ? '逾期完成' : '按时完成',
      statusClass: item.completionStatus === 0 ? 'bg-yellow-100 text-yellow-800' : item.completionStatus === 1 ? 'bg-red-100 text-red-800' : 'bg-green-100 text-green-800',
      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 = ''
  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.completionStatus === 0 ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'">
              {{ item.completionStatus === 0 ? '按时完成' : '逾期完成' }}
            </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>
            <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>
