<template>
  <h1>>说明：任务具体分配给某个人，至少简单的任务分配，并非项目中的任务列表，暂时调用项目中的任务列表，并不完全，</h1>
  <h1>目前需要新建一个任务表，表中的内容。。。。</h1>
  <GiPageLayout>
    <GiTable
      row-key="id"
      title="任务记录"
      :data="dataList"
      :columns="tableColumns"
      :loading="loading"
      :scroll="{ x: '100%', y: '100%', minWidth: 1200 }"
      :pagination="pagination"
      @page-change="onPageChange"
      @page-size-change="onPageSizeChange"
      @refresh="search"
    >
      <template #top>
        <GiForm
          v-model="searchForm"
          search
          :columns="queryFormColumns"
          size="medium"
          @search="search"
          @reset="reset"
        />
      </template>
      <!-- 任务状态显示 -->
      <template #status="{ record }">
        <a-tag :color="getTaskStatusColor(record.status)">{{ getTaskStatusText(record.status) }}</a-tag>
      </template>
      <!-- 操作列 -->
      <template #action="{ record }">
        <a-space>
          <a-link @click="editRecord(record)">编辑</a-link>
          <a-link status="danger" @click="deleteRecord(record)">删除</a-link>
        </a-space>
      </template>
    </GiTable>
  </GiPageLayout>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { Message } from '@arco-design/web-vue'
import type { TableColumnData } from '@arco-design/web-vue'
import { listTask } from '@/apis/project/task'

// 任务状态映射
// status：0未开始，1进行中，2已完成，3已取消
const statusOptions = [
  { label: '未开始', value: 0 },
  { label: '进行中', value: 1 },
  { label: '已完成', value: 2 },
  { label: '已取消', value: 3 }
]
const getTaskStatusColor = (status: number) => {
  const colorMap: Record<number, string> = {
    0: 'gray',
    1: 'blue',
    2: 'green',
    3: 'red'
  }
  return colorMap[status] || 'gray'
}
const getTaskStatusText = (status: number) => {
  const textMap: Record<number, string> = {
    0: '未开始',
    1: '进行中',
    2: '已完成',
    3: '已取消'
  }
  return textMap[status] || status
}

// 搜索表单
let searchForm = reactive({
  taskName: '',
  responsiblePerson: '', // mainUserId
  status: '',
  page: 1,
  size: 10
})

// 查询条件配置
const queryFormColumns = [
  {
    field: 'taskName',
    label: '任务标题',
    type: 'input' as const,
    props: {
      placeholder: '请输入任务标题',
      style: { width: '200px' }
    }
  },
  {
    field: 'responsiblePerson',
    label: '分配用户',
    type: 'input' as const,
    props: {
      placeholder: '请输入分配用户',
      style: { width: '200px' }
    }
  },
  {
    field: 'status',
    label: '任务状态',
    type: 'select' as const,
    props: {
      placeholder: '请选择任务状态',
      options: statusOptions,
      style: { width: '200px' }
    }
  }
]

// 表格列配置
const tableColumns: TableColumnData[] = [
  { title: '任务ID', dataIndex: 'taskId', width: 80 },
  { title: '任务标题', dataIndex: 'taskName', width: 200, ellipsis: true, tooltip: true },
  { title: '分配用户', dataIndex: 'mainUserId', width: 120 },
  { title: '分配部门', dataIndex: 'deptName', width: 120 },
  { title: '任务内容', dataIndex: 'remark', width: 250, ellipsis: true, tooltip: true },
  { title: '任务状态', dataIndex: 'status', slotName: 'status', width: 120 },
  { title: '创建时间', dataIndex: 'createTime', width: 160 },
  { title: '操作', slotName: 'action', width: 120, fixed: 'right' }
]

// 数据状态
const loading = ref(false)
const dataList = ref<any[]>([])
const allData = ref<any[]>([])
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showTotal: true,
  showPageSize: true
})

// 获取任务数据
const fetchTaskList = async () => {
  loading.value = true
  try {
    const params: any = {
      page: searchForm.page,
      pageSize: searchForm.size,
      taskName: searchForm.taskName,
      mainUserId: searchForm.responsiblePerson,
      status: searchForm.status
    }
    // 移除空参数
    Object.keys(params).forEach(key => {
      if (params[key] === '' || params[key] === undefined) delete params[key]
    })
    const res = await listTask(params)
    // 兼容后端返回格式，优先rows，其次data
    const rows = res?.rows || res?.data?.rows || []
    console.log('后端返回数据:', res) // 只打印一次原始数据
    allData.value = rows
    filterAndPaginate()
    pagination.total = rows.length
  } catch (e) {
    Message.error('获取任务数据失败')
  } finally {
    loading.value = false
  }
}

// 前端筛选和分页
const filterAndPaginate = () => {
  let filtered = allData.value
  if (searchForm.taskName) {
    filtered = filtered.filter((item: any) =>
      item.taskName?.toLowerCase().includes(searchForm.taskName.toLowerCase())
    )
  }
  if (searchForm.responsiblePerson) {
    filtered = filtered.filter((item: any) =>
      item.mainUserId?.toLowerCase().includes(searchForm.responsiblePerson.toLowerCase())
    )
  }
  if (searchForm.status !== '' && searchForm.status !== undefined) {
    filtered = filtered.filter((item: any) => String(item.status) === String(searchForm.status))
  }
  // 分页
  const start = (pagination.current - 1) * pagination.pageSize
  const end = start + pagination.pageSize
  dataList.value = filtered.slice(start, end)
  pagination.total = filtered.length
}

// 搜索和重置
const search = async () => {
  pagination.current = 1
  await fetchTaskList()
}

const reset = async () => {
  Object.assign(searchForm, {
    taskName: '',
    responsiblePerson: '',
    status: '',
    page: 1,
    size: 10
  })
  pagination.current = 1
  await fetchTaskList()
}

// 分页处理
const onPageChange = (page: number) => {
  pagination.current = page
  filterAndPaginate()
}

const onPageSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.current = 1
  filterAndPaginate()
}

// 操作方法
const editRecord = (record: any) => {
  Message.info(`编辑任务: ${record.taskName}`)
}

const deleteRecord = (record: any) => {
  Message.info(`删除任务: ${record.taskName}`)
}

onMounted(() => {
  fetchTaskList()
})
</script> 