<template>
  <div class="p-2">
    <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="taskCode">
              <el-input v-model="queryParams.taskCode" 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="palletBarcode">
              <el-input v-model="queryParams.palletBarcode" placeholder="请输入托盘条码" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="校验物料" prop="isValidate">
              <el-select v-model="queryParams.isValidate" placeholder="请选择校验物料" clearable>
                <el-option v-for="dict in wcs_is_flag" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)" />
              </el-select>
            </el-form-item>
            <el-form-item label="任务状态" prop="taskStatus">
              <el-select v-model="queryParams.taskStatus" placeholder="请选择任务状态" clearable>
                <el-option v-for="dict in wcs_task_status" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)" />
              </el-select>
            </el-form-item>
            <el-form-item label="创建时间" style="width: 410px">
              <el-date-picker
                v-model="dateRange"
                :format="CREATED_TIME_PICKER_FORMAT"
                :value-format="CREATED_TIME_VALUE_FORMAT"
                type="datetimerange"
                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-date-picker>
            </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="['wcs:taskDetail:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['wcs:taskDetail:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['wcs:taskDetail:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['wcs:taskDetail:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="taskDetailList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" align="center" type="index" width="60" />
        <el-table-column label="任务编号" align="center" prop="taskCode" min-width="120" />
        <el-table-column label="物料编号" align="center" prop="materialCode" min-width="110" />
        <el-table-column label="物料名称" align="center" prop="materialName" min-width="110" />
        <el-table-column label="托盘条码" align="center" prop="palletBarcode" min-width="120" />
        <el-table-column label="物料条码" align="center" prop="materialBarcode" min-width="120" />
        <el-table-column label="物料数量" align="center" prop="materialCount" width="90" />
        <el-table-column label="任务类型" align="center" prop="taskType" width="100">
          <template #default="scope">
            <dict-tag :options="wcs_task_type" :value="scope.row.taskType" />
          </template>
        </el-table-column>
        <el-table-column label="任务类别" align="center" prop="taskCategory" width="100">
          <template #default="scope">
            <dict-tag :options="wcs_task_category" :value="scope.row.taskCategory" />
          </template>
        </el-table-column>
        <el-table-column label="起始位置" align="center" prop="startPoint" min-width="100" />
        <el-table-column label="结束位置" align="center" prop="endPoint" min-width="100" />
        <el-table-column label="校验物料" align="center" prop="isValidate" width="90">
          <template #default="scope">
            <dict-tag :options="wcs_is_flag" :value="scope.row.isValidate" />
          </template>
        </el-table-column>
        <el-table-column label="路径编号" align="center" prop="pathCode" min-width="100" />
        <el-table-column label="路径名称" align="center" prop="pathName" min-width="100" />
        <el-table-column label="任务状态" align="center" prop="taskStatus" width="100">
          <template #default="scope">
            <dict-tag :options="wcs_task_status" :value="scope.row.taskStatus" />
          </template>
        </el-table-column>
        <el-table-column label="是否标识" align="center" prop="isFlag" width="90">
          <template #default="scope">
            <dict-tag :options="wcs_is_flag" :value="scope.row.isFlag" />
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime, CREATED_TIME_DISPLAY_FORMAT) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="创建人" align="center" prop="createByName" width="100" />
        <el-table-column label="更新人" align="center" prop="updateByName" width="100" />
        <el-table-column label="操作" align="center" fixed="right" class-name="small-padding fixed-width" width="120">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['wcs:taskDetail:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['wcs:taskDetail: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 :title="dialog.title" v-model="dialog.visible" width="820px" append-to-body>
      <el-form ref="taskDetailFormRef" :model="form" :rules="rules" label-width="80px">
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="任务编号" prop="taskCode">
              <el-input v-model="form.taskCode" placeholder="请输入任务编号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物料编号" prop="materialCode">
              <el-select v-model="form.materialCode" placeholder="请选择物料" clearable filterable class="w-full" @change="handleMaterialChange">
                <el-option v-for="item in materialList" :key="item.objId" :label="`${item.materialCode} / ${item.materialName}`" :value="item.materialCode" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="托盘条码" prop="palletBarcode">
              <el-input v-model="form.palletBarcode" placeholder="请输入托盘条码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物料条码" prop="materialBarcode">
              <el-input v-model="form.materialBarcode" placeholder="物料条码" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物料数量" prop="materialCount">
              <el-input-number v-model="form.materialCount" :min="0" controls-position="right" class="w-full" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="任务类型" prop="taskType">
              <el-select v-model="form.taskType" placeholder="请选择任务类型" class="w-full">
                <el-option v-for="dict in wcs_task_type" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="任务类别" prop="taskCategory">
              <el-select v-model="form.taskCategory" placeholder="请选择任务类别" class="w-full">
                <el-option v-for="dict in wcs_task_category" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="校验物料" prop="isValidate">
              <el-radio-group v-model="form.isValidate">
                <el-radio v-for="dict in wcs_is_flag" :key="dict.value" :value="parseInt(dict.value)">{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="起始位置" prop="startPoint">
              <el-input v-model="form.startPoint" placeholder="请输入起始位置" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束位置" prop="endPoint">
              <el-input v-model="form.endPoint" placeholder="请输入结束位置" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="路径编号" prop="pathCode">
              <el-select v-model="form.pathCode" placeholder="请选择路径" clearable filterable class="w-full">
                <el-option v-for="item in pathList" :key="item.objId" :label="`${item.pathCode} / ${item.pathName}`" :value="item.pathCode" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="任务状态" prop="taskStatus">
              <el-select v-model="form.taskStatus" placeholder="请选择任务状态" class="w-full">
                <el-option v-for="dict in wcs_task_status" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否标识" prop="isFlag">
              <el-radio-group v-model="form.isFlag">
                <el-radio v-for="dict in wcs_is_flag" :key="dict.value" :value="parseInt(dict.value)">{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
      </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="TaskDetail" lang="ts">
import { listTaskDetail, getTaskDetail, delTaskDetail, addTaskDetail, updateTaskDetail } from '@/api/wcs/taskDetail';
import { TaskDetailVO, TaskDetailQuery, TaskDetailForm } from '@/api/wcs/taskDetail/types';
import { getMaterialInfoList } from '@/api/wcs/materialInfo';
import { MaterialInfoVO } from '@/api/wcs/materialInfo/types';
import { getPathInfoList } from '@/api/wcs/pathInfo';
import { PathInfoVO } from '@/api/wcs/pathInfo/types';
import {
  CREATED_TIME_DISPLAY_FORMAT,
  CREATED_TIME_PICKER_FORMAT,
  CREATED_TIME_VALUE_FORMAT,
  getTodayCreatedTimeRange
} from '../utils/createTimeRange';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { wcs_is_flag, wcs_task_category, wcs_task_type, wcs_task_status } = toRefs<any>(
  proxy?.useDict('wcs_is_flag', 'wcs_task_category', 'wcs_task_type', 'wcs_task_status')
);

const taskDetailList = ref<TaskDetailVO[]>([]);
const materialList = ref<MaterialInfoVO[]>([]);
const pathList = ref<PathInfoVO[]>([]);
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);

// 创建时间范围筛选，与 SysUser 一致由 addDateRange 注入到 params.beginTime/endTime。
const dateRange = ref<[string, string]>(getTodayCreatedTimeRange());

const queryFormRef = ref<ElFormInstance>();
const taskDetailFormRef = ref<ElFormInstance>();

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

const initFormData: TaskDetailForm = {
  objId: undefined,
  taskCode: undefined,
  materialCode: undefined,
  palletBarcode: undefined,
  materialBarcode: undefined,
  materialCount: undefined,
  taskType: undefined,
  taskCategory: undefined,
  startPoint: undefined,
  endPoint: undefined,
  isValidate: 1,
  pathCode: undefined,
  taskStatus: undefined,
  isFlag: 1,
  remark: undefined,
  createTime: undefined,
}
const data = reactive<PageData<TaskDetailForm, TaskDetailQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    taskCode: undefined,
    materialCode: undefined,
    palletBarcode: undefined,
    materialBarcode: undefined,
    materialCount: undefined,
    taskType: undefined,
    taskCategory: undefined,
    startPoint: undefined,
    endPoint: undefined,
    isValidate: undefined,
    pathCode: undefined,
    taskStatus: undefined,
    isFlag: undefined,
    params: {}
  },
  rules: {
    taskCode: [
      { required: true, message: "任务编号不能为空", trigger: "blur" }
    ],
  }
});

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

const getList = async () => {
  loading.value = true;
  try {
    // 走 addDateRange 把日期范围塞到 params.beginTime/endTime，对齐后端 SysUser 的范围筛选契约。
    const res = await listTaskDetail(proxy?.addDateRange(queryParams.value, dateRange.value));
    taskDetailList.value = res.rows;
    total.value = res.total;
  } finally {
    loading.value = false;
  }
}

const getMaterialList = async () => {
  // 下拉接口只取启用的业务主数据，避免把分页查询形态强塞进免分页接口。
  const res = await getMaterialInfoList({ isFlag: 1, params: {} });
  materialList.value = res.data || [];
}

const getPathList = async () => {
  // 路径下拉仅需要启用状态过滤，保持与后端 getPathInfoList 契约一致。
  const res = await getPathInfoList({ isFlag: 1, params: {} });
  pathList.value = res.data || [];
}

const loadFormOptions = async () => {
  await Promise.all([getMaterialList(), getPathList()]);
}

const handleMaterialChange = (materialCode?: string) => {
  const material = materialList.value.find(item => item.materialCode === materialCode);
  // 物料条码来自物料主数据，只能随物料选择同步，避免手工改出编码与条码不一致的数据。
  form.value.materialBarcode = material?.materialBarcode;
}

const cancel = () => {
  reset();
  dialog.visible = false;
}

const reset = () => {
  form.value = { ...initFormData, isValidate: 1, isFlag: 1 };
  taskDetailFormRef.value?.resetFields();
}

const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

const resetQuery = () => {
  queryFormRef.value?.resetFields();
  // 重置后恢复当天完整范围，避免刚新增的数据落在旧结束时间之后。
  dateRange.value = getTodayCreatedTimeRange();
  handleQuery();
}

const handleSelectionChange = (selection: TaskDetailVO[]) => {
  ids.value = selection.map(item => item.objId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

const handleAdd = async () => {
  reset();
  await loadFormOptions();
  dialog.visible = true;
  dialog.title = "添加实时任务明细";
}

const handleUpdate = async (row?: TaskDetailVO) => {
  reset();
  await loadFormOptions();
  const _objId = row?.objId || ids.value[0]
  const res = await getTaskDetail(_objId);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改实时任务明细";
}

const buildSubmitData = (): TaskDetailForm => ({
  objId: form.value.objId,
  taskCode: form.value.taskCode,
  materialCode: form.value.materialCode,
  palletBarcode: form.value.palletBarcode,
  materialBarcode: form.value.materialBarcode,
  materialCount: form.value.materialCount,
  taskType: form.value.taskType,
  taskCategory: form.value.taskCategory,
  startPoint: form.value.startPoint,
  endPoint: form.value.endPoint,
  isValidate: form.value.isValidate,
  pathCode: form.value.pathCode,
  taskStatus: form.value.taskStatus,
  isFlag: form.value.isFlag,
  remark: form.value.remark
});

const submitForm = () => {
  taskDetailFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      // 详情接口会带出物料名称、路径名称等展示字段，提交时白名单保留真实业务字段。
      const submitData = buildSubmitData();
      if (submitData.objId) {
        await updateTaskDetail(submitData).finally(() =>  buttonLoading.value = false);
      } else {
        await addTaskDetail(submitData).finally(() =>  buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      await getList();
    }
  });
}

const handleDelete = async (row?: TaskDetailVO) => {
  const _objIds = row?.objId || ids.value;
  try {
    await proxy?.$modal.confirm('是否确认删除实时任务明细编号为"' + _objIds + '"的数据项？');
    await delTaskDetail(_objIds);
    proxy?.$modal.msgSuccess("删除成功");
    await getList();
  } catch (e) {
    if (e !== 'cancel' && e !== 'close') {
      console.error('删除实时任务明细失败', e);
    }
  }
}

const handleExport = () => {
  proxy?.download('wcs/taskDetail/export', {
    ...queryParams.value
  }, `taskDetail_${new Date().getTime()}.xlsx`)
}

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