
<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(() => {
  // 从详情页返回时刷新数据
  fetchWorkOrderList()
})
// 工单数据接口
interface WorkOrder {
  id: string
  title: string
  statusName: string
  orderNo: string
  userName: string
  createTime: string
}

// 工单列表数据
const listData = ref<WorkOrder[]>([])
const loading = ref(false)
const loadingMore = ref(false)
const pageNum = ref(1)
const hasMore = ref(true)

// 获取工单列表数据
async function fetchWorkOrderList(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 (filterStatus.value.length > 0) {
      params.statusName = filterStatus.value.join(',')
    }
    
    if (filterContent.value) {
      params.content = filterContent.value
    }
    
    if (filterStatusValue.value) {
      params.status = filterStatusValue.value
    }
    
    if (filterOrderNo.value) {
      params.orderNo = filterOrderNo.value
    }
    
    const response = await http.get<{ rows: any[], total: number }>('/workOrder/order/myList', params)
    const newData = response.rows || []   
    
    // 转换数据格式为组件所需的格式
    const formattedData = newData.map(item => ({
      id: item.id,
      button: '',
      title: item.ticketTypeName || '',
      statusName: item.statusName || '',
      orderNo: item.orderNo || '',
      userName: item.createBy+"/"+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() {
  fetchWorkOrderList()
}

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

// 筛选相关变量
const filterStatus = ref<string[]>([])
const filterTimeRange = ref<string[]>([])
const filterContent = ref('')
const filterStatusValue = ref('')
const filterOrderNo = ref('')

// 工单状态字典数据
const statusColumns = ref<Array<{ value: string; label: string }>>([])

// 获取工单状态字典数据
async function fetchStatusDict() {
  try {
    const response = await http.get<any[]>('/system/dict/data/type/ticket_status')
    statusColumns.value = response.map(item => ({
      value: item.dictValue,
      label: item.dictLabel
    }))
  } catch (error) {
    console.error('获取工单状态字典失败:', error)
  }
}

// 处理状态选择确认
function handleStatusConfirm({ value }: { value: string }) {
  filterStatusValue.value = value
}

// 处理筛选
function handleFilter() {
  console.log('筛选数据')
  // 这里可以添加筛选数据的逻辑
}

// 处理筛选确定
function handleFilterConfirm() {
  console.log('筛选确定', filterStatus.value, filterTimeRange.value)
  // 重新获取数据，应用筛选条件
  fetchWorkOrderList()
}

// 处理筛选取消
function handleFilterCancel() {
  console.log('筛选取消')
  // 这里可以添加筛选取消的逻辑
}

// 处理重置
function handleReset() {
  console.log('重置筛选条件')
  // 清空所有筛选条件
  filterStatus.value = []
  filterContent.value = ''
  filterStatusValue.value = ''
  filterOrderNo.value = ''
  filterTimeRange.value = []
}

onMounted(() => {
  fetchWorkOrderList()
  fetchStatusDict()
})

</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="filterContent" placeholder="请输入工单内容" />
          </view>
          
          <!-- 工单状态下拉框 -->
          <view class="mb-4">
            <text class="block mb-2">工单状态</text>
            <wd-picker 
              :columns="[statusColumns]" 
              v-model="filterStatusValue" 
              @confirm="handleStatusConfirm"
            />
          </view>
          
          <!-- 工单编号搜索 -->
          <view class="mb-4">
            <text class="block mb-2">工单编号</text>
            <wd-input v-model="filterOrderNo" placeholder="请输入工单编号" />
          </view>
          
        </view>
      </template>
    </JiayiList>
  </view>
</template>

<style scoped>
.page {
  padding-bottom: 100rpx;
}
</style>
