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

<template>
  <view class="task-online-container">
    <!-- 导航栏 -->
    <NavBar title="在线录入" />

    <!-- 查询视图 -->
    <component
      :is="queryViewComponent"
      ref="queryViewRef"
      :query-type="defaultTypeValue"
      @query-action="queryAction"
    />

    <!-- 筛选条件栏 -->
    <RadioFilterBar
      v-if="equipType === EquipmentType.BOILER""
      v-model="rightType"
      :options="rightTypeList"
      type="radio"
      @change="handleRightType"
    />

    <!-- 列表 -->
    <scroll-view class="list-scroll" scroll-y @scrolltolower="loadMore">
      <view v-for="item in listData" :key="item.id" class="task-cell">
        <component
          :is="taskItemComponent"
          :ref="setItemRef(item.id)"
          :item="item"
          :user-id="userId"
          @claim-task="handleClaimTask"
        />
      </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>
  </view>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useUserStore } from '@/store/user'
import BoilerQueryView from './components/query/BoilerQueryView.vue'
import PipeQueryView from './components/query/PipeQueryView.vue'
import RadioFilterBar from '@/components/RadioFilterBar/RadioFilterBar.vue'
import { useConfigStore } from '@/store/config'
import { TaskOrderFuncName, requestFunc } from '@/api/ApiRouter/taskOrder'
import NavBar from '@/components/NavBar/NavBar.vue'
import BoilerTaskItem from './components/BoilerTaskItem.vue'
import PipeTaskItem from './components/PipeTaskItem.vue'
import { EquipmentType } from '@/utils/dictMap'
import { onShow } from '@dcloudio/uni-app'

defineOptions({
  name: 'taskOnline',
})

// 状态
const queryViewRef = ref<any>(null)
const listData = ref<any[]>([])
const loading = ref(false)
const hasMore = ref(true)
const params = reactive({
  pageNo: 1,
  pageSize: 10,
})
const rightType = ref<'claim' | 'allot' | 'unclaim' | ''>('')
const rightTypeList = [
  { value: '全部', id: '' },
  { value: '已认领', id: 'claim' },
  { value: '待认领', id: 'unclaim' },
]

const userStore = useUserStore()
const userInfo = computed(() => userStore.userInfo)
const userId = computed(() => userInfo.value?.id || '')

const equipType = useConfigStore().getEquipType()

const taskItemComponent = computed(() => {
  switch (equipType) {
    case EquipmentType.BOILER:
      return BoilerTaskItem
    case EquipmentType.PIPE:
      return PipeTaskItem
    default:
      return null
  }
})

const queryViewComponent = computed(() => {
  switch (equipType) {
    case EquipmentType.BOILER:
      return BoilerQueryView
    case EquipmentType.PIPE:
      return PipeQueryView
    default:
      return null
  }
})

// 默认查询参数
const defaultTypeValue = computed(() => ({
  orderNo: '',
  taskStatusList: [400, 500, 510],
}))

const itemRefs = reactive<Record<string, any>>({})

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

// 获取查询参数
const getQueryParams = () => {
  const queryData = queryViewRef.value?.getQueryParams() || {}
  const statusData = handleRightRefresh()
  return {
    ...params,
    ...queryData,
    ...statusData,
  }
}

// 获取筛选条件
const handleRightRefresh = () => {
  const result: Record<string, any> = {}
  switch (rightType.value) {
    case 'claim':
      result.isClaim = 'claim'
      break
    case 'unclaim':
      result.isClaim = 'unclaim'
      break
    default:
      result.isClaim = null
      break
  }
  return result
}

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

  params.pageNo = refresh ? 1 : params.pageNo + 1
  const queryData = getQueryParams()

  loading.value = true
  try {
    const responseResult = await requestFunc(TaskOrderFuncName.TaskEquipList, 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 handleRightType = (value: string | number | boolean) => {
  rightType.value = value as 'claim' | 'allot' | 'unclaim' | ''
  refreshList()
}

// 设备认领/取消认领
const handleClaimTask = async (id: string, isClaim: boolean) => {
  try {
    let result = null
    if (isClaim) {
      result = await requestFunc(TaskOrderFuncName.EquipmentConfirmClaim, equipType, { id })
    } else {
      result = await requestFunc(TaskOrderFuncName.EquipmentCancelClaim, equipType, { id })
    }

    if (result?.code === 0 && result?.data) {
      uni.showToast({ title: `${isClaim ? '认领' : '取消认领'}成功`, icon: 'success' })
      itemRefs[id]?.setIsClaim(isClaim)
      refreshList()
    } else {
      const msg = result?.msg || `${isClaim ? '设备认领' : '取消认领'}失败`
      uni.showToast({ title: msg, icon: 'error' })
    }
  } catch (error) {
    console.error('认领任务失败:', error)
    uni.showToast({ title: '操作失败', icon: 'error' })
  }
}

onShow(() => {
  refreshList()
})

</script>

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

.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;
  color: #999;
  font-size: 14px;
}
</style>
