<template>
  <div>
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
      :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="任务名称" prop="name">
              <el-input v-model="queryParams.name" placeholder="请输入任务名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="发起人" prop="initiator">
              <el-input v-model="queryParams.initiator" placeholder="请输入发起人" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="质控项目" prop="projectId">
              <el-input v-model="queryParams.projectId" placeholder="请输入质控项目" clearable @keyup.enter="handleQuery" />
            </el-form-item>

            <el-form-item label="截止时间" style="width: 308px">
              <el-date-picker v-model="dateRangeDeadline" value-format="YYYY-MM-DD HH:mm:ss" type="daterange"
                range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"
                :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]" />
            </el-form-item>
            <el-form-item label="创建者" prop="createBy">
              <el-input v-model="queryParams.createBy" placeholder="请输入创建者" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="创建时间" style="width: 308px">
              <el-date-picker v-model="dateRangeCreateTime" value-format="YYYY-MM-DD HH:mm:ss" type="daterange"
                range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"
                :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]" />
            </el-form-item>
            <el-form-item label="更新者" prop="updateBy">
              <el-input v-model="queryParams.updateBy" placeholder="请输入更新者" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="更新时间" style="width: 308px">
              <el-date-picker v-model="dateRangeUpdateTime" value-format="YYYY-MM-DD HH:mm:ss" type="daterange"
                range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"
                :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['qc:task:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()"
              v-hasPermi="['qc:task:remove']">删除</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="taskList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" align="center" prop="id" v-if="true" />
        <el-table-column label="任务名称" align="center" prop="name" width="200" />
        <el-table-column label="发起人" align="center" prop="initiator" width="150">
          <template #default="scope">
            <span>{{ scope.row.initiatorName || scope.row.initiator }}</span>
          </template>
        </el-table-column>
        <el-table-column label="质控项目" align="center" prop="projectId" width="200">
          <template #default="scope">
            <span>{{ scope.row.projectName || scope.row.projectId }}</span>
          </template>
        </el-table-column>

        <el-table-column label="截止时间" align="center" prop="deadline" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.deadline, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="任务状态" align="center" prop="status" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.status === 0" type="info">未开始</el-tag>
            <el-tag v-else-if="scope.row.status === 1" type="warning">进行中</el-tag>
            <el-tag v-else-if="scope.row.status === 2" type="success">已完成</el-tag>
            <el-tag v-else type="info">未知</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="完成度" align="center" width="200">
          <template #default="scope">
            <div style="width: 100%; padding: 5px 0">
              <el-progress :percentage="Math.round((Number(scope.row.schedule) || 0) * 100 * 100) / 100"
                :stroke-width="14" :show-text="true" :format="(percentage) => `${percentage}%`" :empty-color="'#e0e0e0'"
                color="#409eff" style="width: 100%" />
            </div>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="note" />
        <el-table-column label="创建者" align="center" prop="createBy" width="150" />
        <el-table-column label="创建时间" align="center" prop="createTime" width="180" />
        <el-table-column label="更新者" align="center" prop="updateBy" width="150" />
        <el-table-column label="更新时间" align="center" prop="updateTime" width="180" />
        <el-table-column label="操作" align="center" fixed="right" width="240" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button v-hasPermi="['qc:task:query']" type="info" icon="View"
              style="padding: 0 5px; font-size: 10px; height: 24px; margin-right: 5px"
              @click="handleView(scope.row.id)">
              查看
            </el-button>
            <el-button v-if="scope.row.status === 0" v-hasPermi="['qc:task:start']" type="primary" icon="VideoPlay"
              style="padding: 0 5px; font-size: 10px; height: 24px; margin-right: 5px" @click="handleStart(scope.row)">
              开始
            </el-button>
            <el-button v-hasPermi="['qc:task:remove']" type="danger" icon="Delete"
              style="padding: 0 5px; font-size: 10px; height: 24px" @click="handleDelete(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
  </div>
</template>

<script setup name="TaskList" lang="ts">
import { listTask, getTask, delTask, startTask } from '@/api/qc/task';
import { TaskVO, TaskQuery } from '@/api/qc/task/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const emit = defineEmits<{
  add: [];
  view: [taskId: string | number];
}>();

const taskList = ref<TaskVO[]>([]);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const dateRangeDeadline = ref<[DateModelType, DateModelType]>(['', '']);
const dateRangeCreateTime = ref<[DateModelType, DateModelType]>(['', '']);
const dateRangeUpdateTime = ref<[DateModelType, DateModelType]>(['', '']);

const queryFormRef = ref<ElFormInstance>();

const data = reactive<PageData<any, TaskQuery>>({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: undefined,
    initiator: undefined,
    projectId: undefined,
    status: undefined,
    createBy: undefined,
    updateBy: undefined,
    params: {
      deadline: undefined,
      createTime: undefined,
      updateTime: undefined
    }
  }
});

const { queryParams } = toRefs(data);

/** 查询文档质控任务列表 */
const getList = async () => {
  loading.value = true;
  queryParams.value.params = {};

  proxy?.addDateRange(queryParams.value, dateRangeDeadline.value, 'Deadline');
  proxy?.addDateRange(queryParams.value, dateRangeCreateTime.value, 'CreateTime');
  proxy?.addDateRange(queryParams.value, dateRangeUpdateTime.value, 'UpdateTime');
  const res = await listTask(queryParams.value);
  taskList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  dateRangeDeadline.value = ['', ''];
  dateRangeCreateTime.value = ['', ''];
  dateRangeUpdateTime.value = ['', ''];
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: TaskVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  emit('add');
};

/** 查看任务详情 */
const handleView = (taskId: string | number) => {
  emit('view', taskId);
};

/** 开始任务 */
const handleStart = async (row: TaskVO) => {
  try {
    await proxy?.$modal.confirm(`是否确认开始任务 "${row.name}"？`);
    const res = await startTask(row.id);
    if (res.code === 200) {
      proxy?.$modal.msgSuccess('任务开始成功');
      getList(); // 重新获取列表
    } else {
      proxy?.$modal.msgError(res.msg || '任务开始失败');
    }
  } catch (error) {
    console.error('开始任务失败:', error);
  }
};

/** 删除按钮操作 */
const handleDelete = async (row?: TaskVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除文档质控任务编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delTask(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

onMounted(() => {
  getList();
});
</script>
