<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()
  }
})

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

// 任务列表数据
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 filterProcessStartTime = ref('')
const filterProcessEndTime = ref('')
const filterCreateType = ref('')
const filterCompletionStatus = ref('')
const filterTaskName = ref('')
const typeDataData = ref<any>({
  operatMeet:'operational',
})
// 下拉框数据
const stationList = ref<Array<{ value: string; label: string }>>([])
const createTypeList = ref<Array<{ value: string; label: string }>>([
  { value: '0', label: '系统' },
  { value: '1', label: '新增' }
])
const completionStatusList = ref<Array<{ value: string; label: string }>>([
  { value: '0', label: '待完成' },
  { value: '1', label: '按时完成' },
  { value: '2', label: '逾期完成' }
])

// 时间选择器相关
const showStartTimePicker = ref(true)
const showEndTimePicker = 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)
  }
}

// 处理时间选择确认
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') {
    filterProcessStartTime.value = formattedDate
  } else {
    filterProcessEndTime.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 (filterProcessStartTime.value) {
      params.processStartTime = filterProcessStartTime.value
    }
    
    if (filterProcessEndTime.value) {
      params.processEndTime = filterProcessEndTime.value
    }
    
    if (filterCreateType.value) {
      params.createType = filterCreateType.value
    }
    
    if (filterCompletionStatus.value) {
      params.completionStatus = filterCompletionStatus.value
    }
    
    if (filterTaskName.value) {
      params.taskName = filterTaskName.value
    }
    params.directoryType = typeDataData.value[perms.value]
    const response = await http.get<{ rows: any[], total: number }>('/formMeetingRecords/records/list', params)
    const newData = response.rows || []   
    
    const formattedData = newData.map(item => ({
      detailType: 'task',
      id: item.id,
      taskId: item.taskId,
      button: '',
      title: item.meetingTheme || item.taskName || '',
      statusName: item.completionStatus === 0 ? '待完成' : item.completionStatus === 1 ? '逾期完成' : '按时完成',
      statusClass: completionStatusList.value.find(status => status.value === item.completionStatus)?.value === '0' ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800',
      userName: item.executorName+ '/' + item.stationName || '',
      createTime: item.createTime || '',
      meetingHost: item.meetingHost || '',
      meetingLocation: item.meetingLocation || '',
      attendeesCount: item.attendeesCount || 0,
      totalCount: item.totalCount || 0
    }))
    
    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 = ''
  filterProcessStartTime.value = ''
  filterProcessEndTime.value = ''
  filterCreateType.value = ''
  filterCompletionStatus.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.title }}</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 mb-2">
            <text>主持人：{{ item.meetingHost }}</text>
            <text>地点：{{ item.meetingLocation }}</text>
          </view>
          <view class="flex justify-between items-center text-sm text-gray-600 mb-2">
            <text>参会人数：{{ item.attendeesCount }}/{{ item.totalCount }}</text>
            <text>{{ item.createTime }}</text>
          </view>
          <view class="flex justify-start items-center text-sm text-gray-600">
            <text>执行人：{{ item.executorName }}</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>
            <view class="relative">
              <wd-calendar 
                v-model="filterProcessStartTime" 
                @confirm="(date) => handleConfirm(date, 'start')" 
                v-if="showStartTimePicker"
              />
            </view>
          </view>
          
          <!-- 结束时间选择 -->
          <view class="mb-4">
            <text class="block mb-2">结束时间</text>
            <view class="relative">
              <wd-calendar 
                v-model="filterProcessEndTime" 
                @confirm="(date) => handleConfirm(date, 'end')" 
                v-if="showEndTimePicker"
              />
            </view>
          </view>
          
          <!-- 创建类型下拉框 -->
          <view class="mb-4">
            <text class="block mb-2">创建类型</text>
            <wd-picker 
              :columns="[createTypeList]" 
              v-model="filterCreateType" 
            />
          </view>
          
          <!-- 完成状态下拉框 -->
          <view class="mb-4">
            <text class="block mb-2">完成状态</text>
            <wd-picker 
              :columns="[completionStatusList]" 
              v-model="filterCompletionStatus" 
            />
          </view>
          
        </view>
      </template>
    </JiayiList>
  </view>
</template>
