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

import { http } from '@/utils/request'

// 接收参数
const perms = ref('')
onPageShow(() => {
  // 从详情页返回时刷新数据
  fetchWorkOrderList()
})
// 动态页面标题
const pageTitle = computed(() => {
  switch (perms.value) {
    case 'taskWaiting':
      return '我的待办'
    case 'taskFinish':
      return '我的已办'
    case 'taskCopyList':
      return '我的抄送'
    case 'delayedReview':
      return '延时审核'
    default:
      return '公共订单列表'
  }
})

// 定义页面配置
definePage({
  title: '工单列表'
})

// 工单数据接口
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)

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

// 使用 onLoad 生命周期接收参数
function onLoad(options: any) {
  if (options.perms) {
    perms.value = options.perms as string
    // 设置页面标题
    uni.setNavigationBarTitle({
      title: pageTitle.value
    })
    // 加载数据
    fetchWorkOrderList()
  }
}

// 获取接口 URL 根据 perms 值
function getApiUrl() {
  switch (perms.value) {
    case 'taskWaiting':
      return '/workOrder/order/list/pending'
    case 'taskFinish':
      return '/workOrder/order/list/over'
    case 'taskCopyList':
      return '/workOrder/order/list/cc'
    case 'delayedReview':
      return '/workOrder/order/list/delay'
    default:
      return '/workOrder/order/list/pending'
  }
}

// 获取工单列表数据
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 (filterOrderNo.value) {
      params.orderNo = filterOrderNo.value
    }
    
    // 获取接口 URL
    const apiUrl = getApiUrl()
    
    const response = await http.get<{ rows: any[], total: number }>(apiUrl, params)
    const newData = response.rows || []   
    
    // 获取状态映射
    function getStatusName(status: string | number, permsValue: string) {
      if (permsValue === 'delayedReview') {
        // 待办状态映射
        const statusMap: Record<string | number, string> = {
          0: '未审批',
          1: '已同意',
          2: '已拒绝',
          3: '已废除'
        }
        return statusMap[status] || ''
      } else {
        // 其他状态映射
        const statusMap: Record<string | number, string> = {
          0: '待处理',
          1: '处理中',
          2: '已处理',
          3: '已退回'
        }
        return statusMap[status] || ''
      }
    }
    
    // 转换数据格式为组件所需的格式
    const formattedData = newData.map(item => ({
      id: item.orderId,
      delayId: perms.value === 'delayedReview' ? item.id : '',
      button: item.button || '',
      taskId: item.taskId,
      title: item.ticketTypeName || '',
      statusName: item.statusName || getStatusName(item.status, perms.value) || getStatusName(item.approveStatus, perms.value),
      orderNo: item.orderNo || '',
      userName:item.createBy ? item.createBy + "/" + (item.stationName || '') : item.applyUserIdName || '',
      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() {
  console.log('刷新数据')
  fetchWorkOrderList()
}

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

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

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

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

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

onMounted(() => {
  // 页面加载时获取参数并加载数据
  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)
    // 设置页面标题
    uni.setNavigationBarTitle({
      title: pageTitle.value
    })
    fetchWorkOrderList()
  }
})

</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="filterOrderNo" placeholder="请输入工单编号" />
          </view>
        </view>
      </template>
    </JiayiList>
  </view>
</template>

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