<route lang="json5" type="page">
{
  layout: 'default',
  style: {
    navigationBarTitleText: '任务单',
    navigationStyle: 'custom',
    disableScroll: true,
    'app-plus': {
      bounce: 'none',
    },
  },
}
</route>

<template>
  <view class="unclaim-container">
    <!-- 导航栏 -->
    <NavBar title="任务单" />

    <!-- 查询视图 -->
    <view class="query-view-wrapper">
      <QueryView
        ref="queryViewRef"
        :equip-type="equipType"
        :query-type="defaultTypeValue"
        @query-action="queryAction"
      />
    </view>

    <!-- 筛选条件栏 -->
    <view class="filter-bar">
      <RadioFilterBar
        v-model="rightType"
        :options="rightTypeList"
        type="radio"
        @change="handleRightRefresh"
      />
      <RadioFilterBar
        v-model="showTodayOnly"
        :options="todayOnlyOptions"
        type="checkbox"
        :margin-left="'15px'"
        @change="handleShowTodayOnly"
      />
    </view>

    <!-- 列表 -->
    <scroll-view class="list-scroll" scroll-y @scrolltolower="loadMore">
      <view v-for="(item, index) in listData" :key="item.id" class="task-cell">
        <TaskItem
          :ref="setItemRef(item.id)"
          :item="item"
          @claim-task="handleClaimTask"
          @btn-tap="handleBtnTap"
          @safety-check="handleSafetyCheck"
          @update-contact="handleUpdateContact"
          @pdf-detail="handlePdfDetail"
        />
      </view>

      <view v-if="loading" class="loading-text">加载中...</view>
      <view v-if="!hasMore && listData.length > 0" class="no-more-text">没有更多了</view>
      <view v-if="!loading && listData.length === 0" class="empty-text">
        <text>暂无数据</text>
      </view>
    </scroll-view>

    <!-- 修改联系人弹窗 -->
    <UpdateContactPopup
      v-if="showUpdateContactPopup"
      :popup-data="currentOrderInfo"
      @hide="closeUpdateContactPopup"
      @refresh="refreshList"
    />
  </view>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import dayjs from 'dayjs'
import QueryView from './components/query/QueryView.vue'
import TaskItem from './components/TaskItem.vue'
import UpdateContactPopup from './components/UpdateContactPopup.vue'
import RadioFilterBar from '@/components/RadioFilterBar/RadioFilterBar.vue'
import { useConfigStore } from '@/store/config'
import { TaskOrderFuncName, requestFunc } from '@/api/ApiRouter/taskOrder'
import {
  SecurityCheckFuncName,
  requestFunc as securityCheckRequestFunc,
} from '@/api/ApiRouter/taskOrderSecurityCheck'
import NavBar from '@/components/NavBar/NavBar.vue'

defineOptions({
  name: 'unClaimList',
})

// 状态
const queryViewRef = ref<any>(null)
const listData = ref<any[]>([])
const loading = ref(false)
const hasMore = ref(true)
const params = reactive({
  pageNo: 1,
  pageSize: 5,
  taskStatus: '',
  showTodayOnly: true,
})
const showTodayOnly = ref(true)
const rightType = ref('')
const rightTypeList = [
  { value: '全部', id: '' },
  { value: '待认领', id: '100' },
  { value: '已认领', id: '400' },
]
const todayOnlyOptions = [{ value: '仅看今天', id: 'today' }]
const defaultTypeValue = {}
const itemRefs = reactive<Record<string, any>>({})
const showUpdateContactPopup = ref(false)
const currentOrderInfo = ref<any>({})

const configStore = useConfigStore()
const equipType = configStore.getEquipType()

// 设置组件引用
const setItemRef = (itemId: string) => (ref: any) => {
  if (ref) {
    itemRefs[itemId] = ref
  } else {
    delete itemRefs[itemId]
  }
}

// 获取查询参数
const getQueryParams = () => {
  const queryData = queryViewRef.value?.getQueryParams() || {}
  if (params.showTodayOnly) {
    return {
      ...queryData,
      checkDate: [dayjs().format('YYYY-MM-DD 00:00:00'), dayjs().format('YYYY-MM-DD 23:59:59')],
    }
  }
  return queryData
}

// 获取列表数据
const fetchList = async (refresh = false) => {
  if (loading.value) return

  const queryData = {
    ...getQueryParams(),
    taskStatus: params.taskStatus,
    pageNo: refresh ? 1 : params.pageNo + 1,
  }
  params.pageNo = queryData.pageNo

  loading.value = true
  try {
    const responseResult = await requestFunc(TaskOrderFuncName.ConfirmList, equipType, queryData)
    const newList = responseResult?.data?.list || []

    if (refresh) {
      listData.value = newList
    } else {
      listData.value = [...listData.value, ...newList]
    }

    hasMore.value = newList.length >= params.pageSize
  } catch (error) {
    console.error('获取列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 加载更多
const loadMore = () => {
  if (!loading.value && hasMore.value) {
    fetchList(false)
  }
}

// 刷新列表
const refreshList = () => {
  params.pageNo = 1
  fetchList(true)
}

// 查询动作
const queryAction = () => {
  refreshList()
}

// 筛选刷新
const handleRightRefresh = (value: string | number | boolean) => {
  rightType.value = value as string
  params.taskStatus = rightType.value
  refreshList()
}

// 切换仅看今天
const handleShowTodayOnly = (value: string | number | boolean) => {
  showTodayOnly.value = value as boolean
  params.showTodayOnly = showTodayOnly.value
  refreshList()
}

// 认领任务
const handleClaimTask = async (id: string, isClaim: boolean) => {
  try {
    const result = await requestFunc(TaskOrderFuncName.TaskConfirm, equipType, {
      id,
      confirm: isClaim,
    })
    if (result?.code === 0 && result?.data) {
      uni.showToast({ title: `${isClaim ? '认领' : '取消认领'}成功`, icon: 'success' })
      refreshList()
    } else {
      const msg = result?.msg || `${isClaim ? '认领' : '取消认领'}失败`
      uni.showToast({ title: msg, icon: 'error' })
    }
  } catch (error) {
    console.error('认领任务失败:', error)
    uni.showToast({ title: '认领失败', icon: 'error' })
  }
}

const businessTypeMap: Record<string, number> = { FWD: 100, JYRS: 200 }
// 按钮点击（服务单/受理单/检验结果告知）
const handleBtnTap = async (type: 'FWD' | 'JYRS', taskOrder: any) => {
  // 检查网络状态
  const networkType = uni.getNetworkType()
  if (networkType === 'none') {
    return uni.showToast({ title: '无网络连接，请联网重试', icon: 'error' })
  }

  try {
    // const res = await requestFunc(TaskOrderFuncName.TaskOrderDetail, equipType, {
    //   id: taskOrder.id,
    // })
    // if (!res?.data) {
    //   uni.showToast({ title: res?.msg || '获取详情失败', icon: 'error' })
    //   return
    // }
    // const signFileRespVOList = res.data.signFileRespVOList || []
    // const targetBusinessType = businessTypeMap[type]
    // const currentBusinessType =
    //   signFileRespVOList.find((row: any) => row.businessType === targetBusinessType) || {}
    const { unitContact, unitPhone, receiverEmail } = taskOrder

    // if (currentBusinessType.isSignature === '1') {
    //   uni.navigateTo({
    //     url: `/pages/sign-detail/index?orderId=${taskOrder.id}&type=${type}&unitContact=${unitContact || ''}&unitPhone=${unitPhone || ''}&receiverEmail=${receiverEmail || ''}`,
    //   })
    //   return
    // }
    uni.navigateTo({
      url: `/pages/sign/index?orderId=${taskOrder.id}&type=${type}&unitContact=${unitContact || ''}&unitPhone=${unitPhone || ''}&receiverEmail=${receiverEmail || ''}`,
    })
  } catch (error) {
    console.error('获取详情失败:', error)
  }
}

// 安全检查记录
const handleSafetyCheck = async (taskOrder: any) => {
  // 检查网络状态
  const networkType = uni.getNetworkType()
  if (networkType === 'none') {
    return uni.showToast({ title: '无网络连接，请联网重试', icon: 'error' })
  }

  try {
    const res = await securityCheckRequestFunc(SecurityCheckFuncName.getTemplate, equipType, {
      orderId: taskOrder.id,
    })
    // 跳转到 WebView 编辑器
    uni.navigateTo({
      url: `/pages/securityCheck/securityCheckEditor?businessType=AQJC&orderId=${taskOrder.id}&templateId=${res.data.templateId}&useOnline=1&mode=create`,
    })
  } catch (configError) {
    console.error('获取葡萄城配置信息失败:', configError)
    uni.showToast({ title: '获取配置信息失败，请重试', icon: 'error' })
  }
}

// 修改联系人
const handleUpdateContact = (item: any) => {
  currentOrderInfo.value = item
  showUpdateContactPopup.value = true
}

// 关闭修改联系人弹窗
const closeUpdateContactPopup = () => {
  showUpdateContactPopup.value = false
  currentOrderInfo.value = {}
}

// PDF 详情（告知单/服务单/受理单）
const handlePdfDetail = (businessType: any, signFilePdf: string, orderId: string) => {
  const businessTypeTitle = businessType === 200 ? '告知单' : '服务单/受理单'
  uni.navigateTo({
    url: `/pages/sign/index?type=${businessType}&orderId=${orderId}&businessTypeTitle=${businessTypeTitle}`,
  })
}

// 页面显示时刷新（使用 onShow 替代 useDidShow）
onShow((options) => {
  refreshList()
})

// 监听页面卸载
onUnmounted(() => {
  // 触发更新事件
  uni.$emit('UpdateNum', ['unClaim', 'unDownload'])
})

// 暴露 onShow 给页面
defineExpose({
  onShow,
})
</script>

<style lang="scss" scoped>
.unclaim-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f5f5f5;
}

.query-view-wrapper {
  flex-shrink: 0;
}

.list-scroll {
  flex: 1;
  overflow: hidden;
}

.loading-text,
.no-more-text {
  padding: 15px;
  font-size: 14px;
  color: #999;
  text-align: center;
}

.empty-text {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 0;
  font-size: 14px;
  color: #999;
}

.filter-bar {
  display: flex;
  justify-content: space-between;
  flex-shrink: 0;
  background-color: white;
}
</style>
