<template>
  <div class="p-2 wcs-task-instance-page">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px] task-instance-search-wrap">
        <el-card class="task-instance-search-card" shadow="hover">
          <el-form ref="queryFormRef" class="task-instance-query-form" :model="queryParams" :inline="true">
            <el-form-item label="任务编码" prop="taskCode">
              <el-input v-model="queryParams.taskCode" placeholder="请输入任务编码" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="任务名称" prop="taskName">
              <el-input v-model="queryParams.taskName" placeholder="请输入任务名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="任务类型Key" prop="taskTypeKey">
              <el-input v-model="queryParams.taskTypeKey" placeholder="请输入任务类型Key" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="任务类型名称" prop="taskTypeName">
              <el-input v-model="queryParams.taskTypeName" placeholder="请输入任务类型名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="任务状态" prop="status">
              <el-select v-model="queryParams.status" placeholder="请选择任务状态" clearable>
                <el-option v-for="dict in task_status" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="优先级" prop="priority">
              <el-select v-model="queryParams.priority" placeholder="请选择优先级" clearable>
                <el-option v-for="dict in task_priority" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)" />
              </el-select>
            </el-form-item>
            <el-form-item label="源位置" prop="sourceLocation">
              <el-input v-model="queryParams.sourceLocation" placeholder="请输入源位置" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="目标位置" prop="targetLocation">
              <el-input v-model="queryParams.targetLocation" placeholder="请输入目标位置" clearable @keyup.enter="handleQuery" />
            </el-form-item>
<!--            <el-form-item label="物料编码" prop="materialCode">-->
<!--              <el-input v-model="queryParams.materialCode" placeholder="请输入物料编码" clearable @keyup.enter="handleQuery" />-->
<!--            </el-form-item>-->
<!--            <el-form-item label="物料名称" prop="materialName">-->
<!--              <el-input v-model="queryParams.materialName" placeholder="请输入物料名称" clearable @keyup.enter="handleQuery" />-->
<!--            </el-form-item>-->
<!--            <el-form-item label="任务参数" prop="taskParams">-->
<!--              <el-input v-model="queryParams.taskParams" placeholder="请输入任务参数" clearable @keyup.enter="handleQuery" />-->
<!--            </el-form-item>-->
<!--            <el-form-item label="当前子任务序号" prop="currentsubtaskNo">-->
<!--              <el-input-number v-model="queryParams.currentsubtaskNo" :min="0" :controls="false" placeholder="请输入当前子任务序号" />-->
<!--            </el-form-item>-->
<!--            <el-form-item label="子任务总数" prop="subtaskCount">-->
<!--              <el-input-number v-model="queryParams.subtaskCount" :min="0" :controls="false" placeholder="请输入子任务总数" />-->
<!--            </el-form-item>-->
<!--            <el-form-item label="当前执行的子任务编码" prop="currentSubtaskCode">-->
<!--              <el-input v-model="queryParams.currentSubtaskCode" placeholder="请输入当前执行的子任务编码" clearable @keyup.enter="handleQuery" />-->
<!--            </el-form-item>-->
<!--            <el-form-item label="执行结果代码" prop="resultCode">-->
<!--              <el-input-number v-model="queryParams.resultCode" :min="0" :controls="false" placeholder="请输入执行结果代码" />-->
<!--            </el-form-item>-->
<!--            <el-form-item label="错误信息" prop="errorMessage">-->
<!--              <el-input v-model="queryParams.errorMessage" placeholder="请输入错误信息" clearable @keyup.enter="handleQuery" />-->
<!--            </el-form-item>-->
            <el-form-item label="创建时间" prop="createtime">
              <el-date-picker clearable
                v-model="queryParams.createtime"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择创建时间"
              />
            </el-form-item>
            <el-form-item class="task-instance-query-actions">
              <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="['wcs:taskInstance:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['wcs:taskInstance:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['wcs:taskInstance:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['wcs:taskInstance:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:show-search="showSearch" :columns="columns" @query-table="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="taskInstanceList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column v-if="columns[0].visible" type="index" label="序号" width="60" align="center" />
        <el-table-column v-if="columns[1].visible" label="任务编码" align="center" prop="taskCode" min-width="130" :show-overflow-tooltip="true" />
        <el-table-column v-if="columns[2].visible" label="任务名称" align="center" prop="taskName" min-width="150" :show-overflow-tooltip="true" />
        <el-table-column v-if="columns[3].visible" label="任务类型Key" align="center" prop="taskTypeKey" min-width="130" :show-overflow-tooltip="true" />
        <el-table-column v-if="columns[4].visible" label="任务类型名称" align="center" prop="taskTypeName" min-width="130" :show-overflow-tooltip="true" />
        <el-table-column v-if="columns[5].visible" label="任务状态" align="center" prop="status" width="110">
          <template #default="scope">
            <dict-tag :options="task_status" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column v-if="columns[6].visible" label="优先级" align="center" prop="priority" width="90">
          <template #default="scope">
            <dict-tag :options="task_priority" :value="scope.row.priority" />
          </template>
        </el-table-column>
        <el-table-column v-if="columns[7].visible" label="源位置" align="center" prop="sourceLocation" min-width="140" :show-overflow-tooltip="true" />
        <el-table-column v-if="columns[8].visible" label="目标位置" align="center" prop="targetLocation" min-width="140" :show-overflow-tooltip="true" />
        <el-table-column v-if="columns[9].visible" label="物料编码" align="center" prop="materialCode" min-width="120" :show-overflow-tooltip="true" />
        <el-table-column v-if="columns[10].visible" label="物料名称" align="center" prop="materialName" min-width="140" :show-overflow-tooltip="true" />
        <el-table-column v-if="columns[11].visible" label="任务参数" align="center" prop="taskParams" min-width="160" :show-overflow-tooltip="true" />
        <el-table-column v-if="columns[12].visible" label="当前子任务序号" align="center" prop="currentsubtaskNo" width="130" />
        <el-table-column v-if="columns[13].visible" label="子任务总数" align="center" prop="subtaskCount" width="110" />
        <el-table-column v-if="columns[14].visible" label="当前子任务编码" align="center" prop="currentSubtaskCode" min-width="150" :show-overflow-tooltip="true" />
        <el-table-column v-if="columns[15].visible" label="结果代码" align="center" prop="resultCode" width="100" />
        <el-table-column v-if="columns[16].visible" label="错误信息" align="center" prop="errorMessage" min-width="160" :show-overflow-tooltip="true" />
        <el-table-column v-if="columns[17].visible" label="备注" align="center" prop="remark" min-width="150" :show-overflow-tooltip="true" />
        <el-table-column v-if="columns[18].visible" label="创建时间" align="center" prop="createtime" width="170">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createtime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column v-if="columns[19].visible" label="创建人" align="center" prop="createuser" width="110" />
        <el-table-column v-if="columns[20].visible" label="更新人" align="center" prop="updateuser" width="110" />
        <el-table-column label="操作" align="center" fixed="right"  class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['wcs:taskInstance:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['wcs:taskInstance:remove']"></el-button>
            </el-tooltip>
          </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>
    <!-- 添加或修改主任务执行对话框 -->
    <el-dialog class="task-instance-edit-dialog" :title="dialog.title" v-model="dialog.visible" width="860px" append-to-body>
      <el-form ref="taskInstanceFormRef" class="task-instance-dialog-form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="任务编码" prop="taskCode">
          <el-input v-model="form.taskCode" placeholder="请输入任务编码" />
        </el-form-item>
        <el-form-item label="任务名称" prop="taskName">
          <el-input v-model="form.taskName" placeholder="请输入任务名称" />
        </el-form-item>
        <el-form-item label="任务类型Key" prop="taskTypeKey">
          <el-input v-model="form.taskTypeKey" placeholder="请输入任务类型Key" />
        </el-form-item>
        <el-form-item label="任务类型名称" prop="taskTypeName">
          <el-input v-model="form.taskTypeName" placeholder="请输入任务类型名称" />
        </el-form-item>
        <el-form-item label="任务状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择任务状态">
            <el-option v-for="dict in task_status" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="优先级" prop="priority">
          <el-select v-model="form.priority" placeholder="请选择优先级">
            <el-option v-for="dict in task_priority" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)" />
          </el-select>
        </el-form-item>
        <el-form-item label="源位置" prop="sourceLocation">
          <el-input v-model="form.sourceLocation" placeholder="请输入源位置" />
        </el-form-item>
        <el-form-item label="目标位置" prop="targetLocation">
          <el-input v-model="form.targetLocation" placeholder="请输入目标位置" />
        </el-form-item>
        <el-form-item label="物料编码" prop="materialCode">
          <el-input v-model="form.materialCode" placeholder="请输入物料编码" />
        </el-form-item>
        <el-form-item label="物料名称" prop="materialName">
          <el-input v-model="form.materialName" placeholder="请输入物料名称" />
        </el-form-item>
        <el-form-item class="task-instance-dialog-span" label="任务参数" prop="taskParams">
            <el-input v-model="form.taskParams" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="当前子任务序号" prop="currentsubtaskNo">
          <el-input-number v-model="form.currentsubtaskNo" :min="0" :controls="false" class="w-full" placeholder="请输入当前子任务序号" />
        </el-form-item>
        <el-form-item label="子任务总数" prop="subtaskCount">
          <el-input-number v-model="form.subtaskCount" :min="0" :controls="false" class="w-full" placeholder="请输入子任务总数" />
        </el-form-item>
        <el-form-item label="当前执行的子任务编码" prop="currentSubtaskCode">
          <el-input v-model="form.currentSubtaskCode" placeholder="请输入当前执行的子任务编码" />
        </el-form-item>
        <el-form-item label="执行结果代码" prop="resultCode">
          <el-input-number v-model="form.resultCode" :min="0" :controls="false" class="w-full" placeholder="请输入执行结果代码" />
        </el-form-item>
        <el-form-item class="task-instance-dialog-span" label="错误信息" prop="errorMessage">
            <el-input v-model="form.errorMessage" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item class="task-instance-dialog-span" label="备注" prop="remark">
            <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="TaskInstance" lang="ts">
import { listTaskInstance, getTaskInstance, delTaskInstance, addTaskInstance, updateTaskInstance } from '@/api/wcs/taskInstance';
import { TaskInstanceVO, TaskInstanceQuery, TaskInstanceForm } from '@/api/wcs/taskInstance/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { task_status, task_priority } = toRefs<any>(proxy?.useDict('task_status', 'task_priority'));

const taskInstanceList = ref<TaskInstanceVO[]>([]);
const buttonLoading = ref(false);
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 queryFormRef = ref<ElFormInstance>();
const taskInstanceFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

// 主任务列表用于调度追踪，隐藏数据库ID和逻辑删除字段，保留任务流转与异常排查字段。
const columns = ref<FieldOption[]>([
  { key: 0, label: '序号', visible: true, children: [] },
  { key: 1, label: '任务编码', visible: true, children: [] },
  { key: 2, label: '任务名称', visible: true, children: [] },
  { key: 3, label: '任务类型Key', visible: true, children: [] },
  { key: 4, label: '任务类型名称', visible: true, children: [] },
  { key: 5, label: '任务状态', visible: true, children: [] },
  { key: 6, label: '优先级', visible: true, children: [] },
  { key: 7, label: '源位置', visible: true, children: [] },
  { key: 8, label: '目标位置', visible: true, children: [] },
  { key: 9, label: '物料编码', visible: true, children: [] },
  { key: 10, label: '物料名称', visible: true, children: [] },
  { key: 11, label: '任务参数', visible: true, children: [] },
  { key: 12, label: '当前子任务序号', visible: true, children: [] },
  { key: 13, label: '子任务总数', visible: true, children: [] },
  { key: 14, label: '当前子任务编码', visible: true, children: [] },
  { key: 15, label: '结果代码', visible: true, children: [] },
  { key: 16, label: '错误信息', visible: true, children: [] },
  { key: 17, label: '备注', visible: true, children: [] },
  { key: 18, label: '创建时间', visible: true, children: [] },
  { key: 19, label: '创建人', visible: true, children: [] },
  { key: 20, label: '更新人', visible: true, children: [] }
]);

const initFormData: TaskInstanceForm = {
  id: undefined,
  taskCode: undefined,
  taskName: undefined,
  taskTypeKey: undefined,
  taskTypeName: undefined,
  status: undefined,
  priority: undefined,
  sourceLocation: undefined,
  targetLocation: undefined,
  materialCode: undefined,
  materialName: undefined,
  taskParams: undefined,
  currentsubtaskNo: undefined,
  subtaskCount: undefined,
  currentSubtaskCode: undefined,
  resultCode: undefined,
  errorMessage: undefined,
  isDeleted: undefined,
  remark: undefined,
  createtime: undefined,
}
const data = reactive<PageData<TaskInstanceForm, TaskInstanceQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    taskCode: undefined,
    taskName: undefined,
    taskTypeKey: undefined,
    taskTypeName: undefined,
    status: undefined,
    priority: undefined,
    sourceLocation: undefined,
    targetLocation: undefined,
    materialCode: undefined,
    materialName: undefined,
    taskParams: undefined,
    currentsubtaskNo: undefined,
    subtaskCount: undefined,
    currentSubtaskCode: undefined,
    resultCode: undefined,
    errorMessage: undefined,
    isDeleted: undefined,
    createtime: undefined,
    params: {
    }
  },
  rules: {
    id: [
      { required: true, message: "主键不能为空", trigger: "blur" }
    ],
    taskCode: [
      { required: true, message: "任务编码不能为空", trigger: "blur" }
    ],
    taskTypeKey: [
      { required: true, message: "任务类型Key不能为空", trigger: "blur" }
    ],
    status: [
      { required: true, message: "任务状态不能为空", trigger: "change" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询主任务执行列表 */
const getList = async () => {
  loading.value = true;
  const res = await listTaskInstance(queryParams.value);
  taskInstanceList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  taskInstanceFormRef.value?.resetFields();
}

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

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

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

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加主任务执行";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: TaskInstanceVO) => {
  reset();
  const _id = row?.id || ids.value[0]
  const res = await getTaskInstance(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改主任务执行";
}

/** 提交按钮 */
const submitForm = () => {
  taskInstanceFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateTaskInstance(form.value).finally(() =>  buttonLoading.value = false);
      } else {
        await addTaskInstance(form.value).finally(() =>  buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      await getList();
    }
  });
}

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

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('wcs/taskInstance/export', {
    ...queryParams.value
  }, `taskInstance_${new Date().getTime()}.xlsx`)
}

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

<style scoped lang="scss">
.wcs-task-instance-page {
  /* 任务实例用于追踪执行链路，查询条件密集，独立栅格让状态、位置、错误信息分组更清晰。 */
  :deep(.task-instance-search-card) {
    border: 1px solid var(--el-border-color-lighter);
    border-radius: 8px;
    box-shadow: 0 8px 22px rgb(15 23 42 / 6%);
  }

  :deep(.task-instance-search-card .el-card__body) {
    padding: 16px 18px 6px;
  }

  :deep(.task-instance-query-form) {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(245px, 1fr));
    column-gap: 16px;
    align-items: start;
  }

  :deep(.task-instance-query-form .el-form-item) {
    margin-right: 0;
    margin-bottom: 12px;
  }

  :deep(.task-instance-query-form .el-form-item__label) {
    justify-content: flex-start;
    width: 112px;
    color: var(--el-text-color-regular);
  }

  :deep(.task-instance-query-form .el-input),
  :deep(.task-instance-query-form .el-select),
  :deep(.task-instance-query-form .el-date-editor) {
    width: 100%;
  }

  :deep(.task-instance-query-actions) {
    grid-column: 1 / -1;
  }

  :deep(.task-instance-query-actions .el-form-item__content) {
    justify-content: flex-end;
    gap: 8px;
  }
}

:global(.task-instance-edit-dialog) {
  width: min(860px, calc(100vw - 32px)) !important;
}

:global(.task-instance-edit-dialog .el-dialog__header) {
  padding: 18px 22px 14px;
  background: linear-gradient(90deg, rgb(37 99 235 / 8%), rgb(20 184 166 / 6%));
}

:global(.task-instance-edit-dialog .el-dialog__body) {
  padding: 20px 24px 8px !important;
}

:global(.task-instance-edit-dialog .task-instance-dialog-form) {
  display: grid;
  grid-template-columns: repeat(2, minmax(0, 1fr));
  column-gap: 18px;
}

:global(.task-instance-edit-dialog .el-form-item) {
  margin-bottom: 18px;
}

:global(.task-instance-edit-dialog .task-instance-dialog-span) {
  grid-column: 1 / -1;
}

:global(.task-instance-edit-dialog .el-input),
:global(.task-instance-edit-dialog .el-select),
:global(.task-instance-edit-dialog .el-date-editor) {
  width: 100%;
}

:global(.task-instance-edit-dialog .el-textarea__inner) {
  min-height: 76px !important;
}

:global(.task-instance-edit-dialog .el-dialog__footer) {
  padding: 12px 24px 18px;
  border-top: 1px solid var(--el-border-color-lighter);
}

@media (max-width: 768px) {
  .wcs-task-instance-page {
    :deep(.task-instance-query-form) {
      grid-template-columns: 1fr;
    }
  }

  :global(.task-instance-edit-dialog .task-instance-dialog-form) {
    grid-template-columns: 1fr;
  }
}
</style>
