<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: '班组日志'
})

// 班组日志数据接口
interface TeamLog {
  id: number
  taskName: string
  executorName: string
  stationId: number
  createType: number
  deadline: string
  processTime: string
  completionStatus: number
  shiftDate: string
  shiftId: string
  weather: string
  shiftLeaderName: string
  shiftMembers: string
}

// 任务列表数据
const listData = ref<TeamLog[]>([])
const loading = ref(false)
const loadingMore = ref(false)
const pageNum = ref(1)
const hasMore = ref(true)
const perms = ref('')
const typeDataData = ref<any>({
  operatTeam:'operational',
})



// 筛选相关变量
const filterStationId = ref('')
const filterProcessStartTime = ref('')
const filterProcessEndTime = ref('')
const filterCreateType = ref('')
const filterCompletionStatus = ref('')
const filterTaskName = ref('')

// 下拉框数据
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 shiftIdList = ref<Array<{ value: string; label: string }>>([
  { value: '早班', label: '早班' },
  { value: '中班', label: '中班' },
  { value: '晚班', label: '晚班' }
])

// 获取加油站列表
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 || ''
    }))
  } catch (error) {
    console.error('获取加油站列表失败:', error)
  }
}

// 处理时间选择确认
function handleConfirm(date: any, type: 'start' | 'end' | 'shift') {
  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
    }
  }
  
  if (type === 'start') {
    filterProcessStartTime.value = formattedDate
  } else if (type === 'end') {
    filterProcessEndTime.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 }>('/formTeamShiftLog/log/list', params)
    const newData = response.rows || []
    
    // 转换数据格式为组件所需的格式
    const formattedData = newData.map(item => ({
      detailType: 'tasd',
      id: item.id,
      taskId: item.taskId,
      button: '',
      title: item.taskName || '',
      statusName: item.completionStatus === 0 ? '待完成' : item.completionStatus === 1 ? '逾期完成' : '按时完成',
      statusClass: item.completionStatus === 0 ? 'bg-green-100 text-green-800' : item.completionStatus === 1 ? 'bg-red-100 text-red-800' : 'bg-green-100 text-green-800', 
      userName: item.executorName+ '/' + item.stationName || '',
      createTime: item.processTime || item.shiftDate || '',
      shiftId: item.shiftId || '',
      weather: item.weather || '',
      shiftLeaderName: item.shiftLeaderName || ''
    }))
    
    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 = ''
}

// 页面加载时获取数据
onMounted(() => {})

// 页面显示时刷新数据
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()
  }
})

</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 #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')" 
              />
            </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')" 
              />
            </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>