<script setup lang="ts">
import { done, type FlowTask, type TaskQuery } from '@/api/modules/flow/task'
import dayjs from 'dayjs'
import { useCachedViewStore } from '@/stores/modules/cachedView'
import StatusTag from './StatusTag'

const router = useRouter()
const cachedViewStore = useCachedViewStore()
const list = ref<FlowTask[]>([])
const error = ref(false)
const loading = ref(false)
const finished = ref(false)
const refreshing = ref(false)
const total = ref(0)
const queryForm = ref<TaskQuery>({
  name: '',
  instanceName: '',
  startUserId: '',
  instanceId: '',
  modelCode: '',
  definitionId: '',
  startDates: [],
  page: 0,
  limit: 10
})
const onSearch = () => {
  refreshing.value = true
  onRefresh()
}
const onRefresh = () => {
  finished.value = false
  loading.value = true
  onLoad()
}
const onLoad = () => {
  queryForm.value.page++
  if (refreshing.value) {
    queryForm.value.page = 1
    list.value = []
    refreshing.value = false
  }
  done(queryForm.value)
    .then((res) => {
      if (res.success) {
        list.value.push(...res.data.rows)
        total.value = res.data.total
      }
    })
    .catch(() => {
      error.value = true
    })
    .finally(() => {
      loading.value = false
      finished.value = list.value.length >= total.value
    })
}
const handleTask = (task: FlowTask) => {
  cachedViewStore.delCachedView('HandleTask')
  router.push({ name: 'HandleTask', query: { id: task.id } })
}
</script>

<template>
  <form action="/">
    <van-search
      v-model="queryForm.instanceName"
      placeholder="请输入流程名称"
      shape="round"
      @search="onSearch"
    >
    </van-search>
  </form>
  <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
    <van-list
      v-model:loading="loading"
      v-model:error="error"
      error-text="请求失败，点击重新加载"
      :finished="finished"
      finished-text="没有更多了"
      @load="onLoad"
    >
      <van-cell-group inset mt-2 v-for="item in list" :key="item.id">
        <van-cell @click="handleTask(item)">
          <template #title>
            <div flex-between>
              <div style="width: 85%;">
                {{ item.instanceName }} 
              </div>
              <StatusTag :status="item.status" />
            </div>
          </template>
          <template #label>
            <div flex-between>
              <span>
                <UserName :username="item.startUserId" />
              </span>
              {{ dayjs(item.startTime).format('MM-DD HH:mm') }}
            </div>
          </template>
        </van-cell>
      </van-cell-group>
    </van-list>
  </van-pull-refresh>
</template>

<style scoped lang="less"></style>
