<!--任务管理-->
<template>
  <GiPageLayout>
    <a-button type="primary" style="margin-bottom: 16px" @click="openAddModal">发布任务</a-button>
    <GiTable
      row-key="taskId"
      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"
      @row-click="onRowClick"
    >
      <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.stop="onRowClick(record)">详情</a-link>
          <a-link status="danger" @click.stop="deleteRecord(record)">删除</a-link>
        </a-space>
      </template>
    </GiTable>
    <!-- 发布任务弹窗 -->
    <a-modal v-model:visible="showAddModal" title="发布任务" @ok="handleAddTask" @cancel="showAddModal = false">
      <a-form :model="addForm" label-width="90px">
        <a-form-item label="任务ID">
          <a-input v-model="addForm.taskId" disabled />
        </a-form-item>
        <a-form-item label="任务描述">
          <a-input v-model="addForm.remark" placeholder="请输入任务描述" />
        </a-form-item>
        <a-form-item label="创建时间">
          <a-input v-model="addForm.createTime" disabled />
        </a-form-item>
      </a-form>
    </a-modal>
    <!-- 任务详情弹窗 -->
    <a-modal v-model:visible="showDetailModal" title="任务详情" @ok="handleUpdateTask" @cancel="showDetailModal = false" :footer="false">
      <a-form :model="detailForm" label-width="90px">
        <a-form-item label="任务ID">
          <a-input v-model="detailForm.taskId" disabled />
        </a-form-item>
        <a-form-item label="任务描述">
          <a-input v-model="detailForm.remark" />
        </a-form-item>
        <a-form-item label="分配岗位">
          <a-select v-model="detailForm.deptName" :options="deptOptions" allow-clear placeholder="请选择岗位" />
        </a-form-item>
        <a-form-item label="分配人员">
          <a-select v-model="detailForm.mainUserId" :options="userOptions" allow-clear placeholder="请选择人员" />
        </a-form-item>
        <a-form-item label="任务状态">
          <a-input :value="getTaskStatusText(detailForm.status)" disabled />
        </a-form-item>
        <a-form-item label="创建时间">
          <a-input v-model="detailForm.createTime" disabled />
        </a-form-item>
        <a-form-item label="完成时间">
          <a-input v-model="detailForm.finishTime" disabled />
        </a-form-item>
      </a-form>
      <template #footer>
        <a-space style="float: right">
          <a-button status="danger" @click="handleDeleteTask">删除</a-button>
          <a-button type="primary" @click="handleUpdateTask">确定</a-button>
        </a-space>
      </template>
    </a-modal>
  </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' // 接口调用处注释

// 任务状态映射
// 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
}

// 示例岗位和人员
const deptOptions = [
  { label: '开发', value: '开发' },
  { label: '测试', value: '测试' },
  { label: '运维', value: '运维' }
]
const userOptions = [
  { label: '张三', value: '张三' },
  { label: '李四', value: '李四' },
  { label: '王五', value: '王五' }
]

// 搜索表单
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 showAddModal = ref(false)
const addForm = reactive({
  taskId: '',
  remark: '',
  createTime: ''
})
const openAddModal = () => {
  addForm.taskId = Date.now().toString()
  addForm.remark = ''
  addForm.createTime = new Date().toLocaleString()
  showAddModal.value = true
}
const handleAddTask = () => {
  if (!addForm.remark) {
    Message.warning('请输入任务描述')
    return
  }
  const newTask = {
    taskId: addForm.taskId,
    taskName: addForm.remark,
    mainUserId: '',
    deptName: '',
    remark: addForm.remark,
    status: 0, // 未分配
    createTime: addForm.createTime,
    finishTime: ''
  }
  allData.value.unshift(newTask)
  filterAndPaginate()
  showAddModal.value = false
  Message.success('任务发布成功')
}

// 任务详情弹窗
const showDetailModal = ref(false)
const detailForm = reactive({
  taskId: '',
  taskName: '',
  mainUserId: '',
  deptName: '',
  remark: '',
  status: 0,
  createTime: '',
  finishTime: ''
})
let detailIndex = -1
const onRowClick = (record: any) => {
  Object.assign(detailForm, record)
  detailIndex = allData.value.findIndex(item => item.taskId === record.taskId)
  showDetailModal.value = true
}
const handleUpdateTask = () => {
  if (detailIndex !== -1) {
    allData.value[detailIndex] = { ...detailForm }
    filterAndPaginate()
    showDetailModal.value = false
    Message.success('任务更新成功')
  }
}
const handleDeleteTask = () => {
  if (detailIndex !== -1) {
    allData.value.splice(detailIndex, 1)
    filterAndPaginate()
    showDetailModal.value = false
    Message.success('任务已删除')
  }
}

// 获取任务数据（用示例数据，接口调用处注释）
const fetchTaskList = async () => {
  loading.value = true
  try {
    // const res = await listTask(params)
    // const rows = res?.rows || res?.data?.rows || []
    // allData.value = rows
    // 示例数据：
    allData.value = [
      {
        taskId: '1710000000000',
        taskName: '示例任务A',
        mainUserId: '张三',
        deptName: '开发',
        remark: '开发新功能',
        status: 1,
        createTime: '2024-05-01 10:00:00',
        finishTime: ''
      },
      {
        taskId: '1710000000001',
        taskName: '示例任务B',
        mainUserId: '',
        deptName: '',
        remark: '待分配任务',
        status: 0,
        createTime: '2024-05-02 11:00:00',
        finishTime: ''
      },
      {
        taskId: '1710000000002',
        taskName: '示例任务C',
        mainUserId: '李四',
        deptName: '测试',
        remark: '测试任务',
        status: 2,
        createTime: '2024-05-03 09:00:00',
        finishTime: '2024-05-05 18:00:00'
      }
    ]
    filterAndPaginate()
    pagination.total = allData.value.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
  filterAndPaginate()
}

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

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

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

// 删除操作（表格操作列）
const deleteRecord = (record: any) => {
  const idx = allData.value.findIndex(item => item.taskId === record.taskId)
  if (idx !== -1) {
    allData.value.splice(idx, 1)
    filterAndPaginate()
    Message.success('任务已删除')
  }
}

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