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

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

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

    <!-- 筛选条件栏 -->
    <view class="filter-bar">
      <view
        v-for="(item, index) in rightTypeList"
        :key="item.id"
        class="filter-item"
        @click="handleRightType(item.id)"
      >
        <view class="checkbox-wrapper" :style="{ marginLeft: index === 0 ? '0' : '15px' }">
          <view class="checkbox" :class="{ 'radio-checked': rightType === item.id }">
            <view v-if="rightType === item.id" class="radio-inner"></view>
          </view>
          <text class="checkbox-text">{{ item.value }}</text>
        </view>
      </view>
    </view>

    <!-- 列表 -->
    <scroll-view class="list-scroll" scroll-y @scrolltolower="loadMore">
      <view v-for="item in listData" :key="item.id" class="task-cell">
        <TaskItem
          :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>
    </scroll-view>
  </view>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useUserStore } from '@/store/user'
import QueryView from './components/query/QueryView.vue'
import TaskItem from './components/TaskItem.vue'
import { useConfigStore } from '@/store/config'
import { TaskOrderFuncName, requestFunc } from '@/api/ApiRouter/taskOrder'

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' | ''>('unclaim')
const rightTypeList = [
  { value: '全部', id: '' },
  { value: '已认领', id: 'claim' },
  { value: '已分配', id: 'allot' },
  { value: '待认领', id: 'unclaim' },
]

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

const equipType = useConfigStore().equipType

// 默认查询参数
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 = true
      result.mainCheckerIds = userId.value
      break
    case 'allot':
      result.isClaim = true
      result.isAllot = true
      result.checkUserStrIds = userId.value
      break
    case 'unclaim':
      result.isClaim = false
      result.planCheckUserIds = userId.value
      break
    default:
      result.mainCheckerIds = userId.value
      result.planCheckUserIds = userId.value
      result.checkUserStrIds = userId.value
      result.managerStrIds = userId.value
      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 = (id: string) => {
  rightType.value = id 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' })
  }
}

// 页面显示时刷新
onMounted(() => {
  refreshList()
})
</script>

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

.navigate-view {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 44px;
  background-color: #fff;
  border-bottom: 1px solid #eee;
}

.navigate-title {
  font-size: 17px;
  font-weight: 500;
  color: #333;
}

.filter-bar {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  padding: 10px 15px;
  background-color: #fff;
  border-bottom: 1px solid #eee;
}

.filter-item {
  display: flex;
  flex-direction: row;
  align-items: center;
}

.checkbox-wrapper {
  display: flex;
  flex-direction: row;
  align-items: center;
}

.checkbox {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 16px;
  height: 16px;
  margin-right: 6px;
  border: 1px solid #bbb;
  border-radius: 50%;
}

.checkbox.radio-checked {
  background-color: #fff;
  border-color: #2f8eff;
}

.checkbox .radio-inner {
  width: 8px;
  height: 8px;
  background-color: #2f8eff;
  border-radius: 50%;
}

.checkbox-text {
  font-size: 14px;
  color: #333;
}

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

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