<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { useMessage } from 'naive-ui';
import RightIconn from '@/assets/imgs/Right.png';
import StopIcon from '@/assets/imgs/执行中.png';
import inIcon from '@/assets/imgs/入库.png';
import outIcon from '@/assets/imgs/出库.png';
import allIcon from '@/assets/imgs/ALL.png';
import { fetchAddManageTaskToWCS, fetchGetTodoWorkManageTask } from '@/service/api/taskmg';
import TodoWork from './modules/todowork-search.vue';

const message = useMessage();
// 父组件的查询参数
const searchParams = ref<Api.PlanManage.TaskDetailsSearchParams>({
  PalletNo: '', // 托盘号
  OrderLine: '', // 订单+行号
  TaskQty: null, // 任务数量
  RFID: '', // RFID编号
  TaskStatus: null, // 任务状态
  TaskType: null, // 任务类型
  CreateUser: '', // 创建任务的用户名
  CreateTimeStart: '', // 创建时间
  CreateTimeEnd: '' // 创建时间
});
// 重置搜索参数的方法
function resetSearchParams() {
  searchParams.value = {
    PalletNo: null, // 托盘号
    OrderLine: null, // 订单+行号
    TaskQty: null, // 任务数量
    RFID: null, // RFID编号
    TaskStatus: null, // 任务状态
    TaskType: null, // 任务类型
    CreateUser: null, // 创建任务的用户名
    CreateTimeStart: null, // 创建时间
    CreateTimeEnd: null // 创建时间
  };
}
// const TodoWorkManageTask = ref<Api.PlanManage.TaskDetails[] | undefined>([]);
const TodoWorkManageTask = ref<(Api.PlanManage.TaskDetails & { isSelected: boolean })[] | undefined>([]);

async function GetTodoWorkList() {
  const datas = await fetchGetTodoWorkManageTask(searchParams.value);
  // TodoWorkManageTask.value = datas.data?.data;
  // 为每个任务添加 isSelected 属性，默认值为 false
  TodoWorkManageTask.value = datas.data?.data.map((item: Api.PlanManage.TaskDetails) => ({
    ...item, // 保留原有属性
    isSelected: false // 添加 isSelected 属性
  }));
}

// 获取分页数据的方法
function getDataByPage() {
  // 使用 searchParams 获取数据逻辑，例如发送 API 请求
  // console.log('获取数据：', searchParams.value);
  GetTodoWorkList();
}

async function AddManageTaskList(selectedTasks: Api.PlanManage.ManageTaskToWCSRequest) {
  const response = await fetchAddManageTaskToWCS(selectedTasks);
  if (response.data?.Status === 1) {
    await GetTodoWorkList();
    message.info(response.data?.msg, { duration: 5000 });
  }
}
function AddManageTaskList2(taskList: (Api.PlanManage.TaskDetails & { isSelected?: boolean })[]) {
  const requestBody: Api.PlanManage.ManageTaskToWCSRequest = {
    TaskDetailsList: taskList.map(({ isSelected: _isSelected, ...task }) => task) // 这里排除 isSelected
  };

  AddManageTaskList(requestBody);
}

const formatTaskStatus = (status: number | null) => {
  if (status === null) return '未知';
  switch (status) {
    case 0:
      return '待执行';
    case 1:
      return '执行中';
    case 2:
      return '已完成';
    case 3:
      return '异常';
    default:
      return '未知';
  }
};
const formatTaskType = (type: number | null) => {
  if (type === null) return '未知';
  switch (type) {
    case 1:
      return '入库';
    case 2:
      return '出库';
    case 3:
      return '盘库';
    default:
      return '未知';
  }
};

const selectedAll = ref(false);
function selectAll() {
  if (TodoWorkManageTask.value?.length) {
    TodoWorkManageTask.value.forEach(item => {
      item.isSelected = selectedAll.value;
    });
  }
}

function AllManageTask() {
  const selected = TodoWorkManageTask.value?.filter(item => item.isSelected) || [];

  if (selected.length === 0) {
    message.warning('请选择任务');
    return;
  }

  const hasExecutedTask = selected.some(item => item.TaskStatus === 1);

  if (hasExecutedTask) {
    message.warning('不能再次执行已经执行的任务');
    return;
  }

  const selectedTasks: Api.PlanManage.ManageTaskToWCSRequest = {
    TaskDetailsList: selected.map(({ isSelected: _isSelected, ...task }) => task)
  };

  // console.log(selectedTasks);
  AddManageTaskList(selectedTasks);
}
// 控制是否显示子组件
const showTaskDetail = ref(false);
const currentTaskData = ref<Api.PlanManage.TaskDetails>({} as Api.PlanManage.TaskDetails);
// 显示组件
const showTaskDetail_Click = (task: Api.PlanManage.TaskDetails) => {
  showTaskDetail.value = true;
  currentTaskData.value = task;
};
// 供子组件调用的回调，用于隐藏子组件
const onTaskDetailSubmitted = () => {
  showTaskDetail.value = false;
};
const handleTaskIDClick = (task: Api.PlanManage.TaskDetails) => {
  showTaskDetail_Click(task);
};

// onMounted(async () => {
//   await GetTodoWorkList();
// });
onMounted(() => {
  GetTodoWorkList(); // 先立即执行一次

  // const intervalId = setInterval(() => {
  //   GetTodoWorkList();
  // }, 3000); // 每隔1000ms执行一次

  // // 如果你需要在组件卸载时清除定时器，记得加上：
  // onUnmounted(() => {
  //   clearInterval(intervalId);
  // });
});
</script>

<template>
  <div class="flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <TodoWork v-if="!showTaskDetail" v-model:model="searchParams" @reset="resetSearchParams" @search="getDataByPage" />
    <NCard v-if="!showTaskDetail">
      <div class="flex-container">
        <NCheckbox v-model:checked="selectedAll" size="large" label="全选" @click="selectAll" />
        <div class="btn left">
          <span class="right_title" @click="AllManageTask">批量执行</span>
          <NAvatar class="avatars2" :size="20" :src="allIcon" />
        </div>
      </div>
    </NCard>
    <NInfiniteScroll
      v-if="!showTaskDetail && Array.isArray(TodoWorkManageTask) && TodoWorkManageTask.length > 0"
      :distance="10"
    >
      <NCard v-for="item in TodoWorkManageTask" :key="item.TaskID" class="item">
        <div class="card-content">
          <div class="left">
            <NCheckbox v-model:checked="item.isSelected" size="large" />
            <NAvatar v-if="item.TaskType === 1" class="avatars" :src="inIcon" />
            <NAvatar v-if="item.TaskType === 2" class="avatars" :src="outIcon" />
            <span class="title" @click="handleTaskIDClick(item)">单号:{{ item.TaskID }}</span>
          </div>
          <div class="center">
            <p class="line data-row">
              <span :title="item.TaskID">
                <span class="task-quantity">单号ID:</span>
                {{ item.TaskID }}
              </span>
              <span>
                <span class="task-quantity">托盘号:</span>
                {{ item.PalletNo }}
              </span>
              <span :title="item.RFID">
                <span class="task-quantity">RFID编号:</span>
                {{ item.RFID }}
              </span>
              <span>
                <span class="task-quantity">起点位置:</span>
                {{ item.SourceLocation }}
              </span>
              <span>
                <span class="task-quantity">终点位置:</span>
                {{ item.TargetLocation }}
              </span>
            </p>
            <p class="line data-row">
              <span>
                <span class="task-quantity">任务数量:</span>
                {{ item.TaskQty }}
              </span>
              <span>
                <span class="task-quantity">任务状态:</span>
                {{ formatTaskStatus(item.TaskStatus) }}
              </span>
              <span>
                <span class="task-quantity">任务类型:</span>
                {{ formatTaskType(item.TaskType) }}
              </span>
              <span>
                <span class="task-quantity">创建用户:</span>
                {{ item.CreateUser }}
              </span>
              <span :title="item.CreateTime">
                <span class="task-quantity">创建时间:</span>
                {{ item.CreateTime }}
              </span>
            </p>
          </div>
          <div class="right">
            <!-- <NButton class="btn" icon-placement="right" ghost :render-icon="renderIcon">删除</NButton> -->
            <div class="btn left">
              <NPopconfirm v-if="item.TaskStatus === 0" :show-icon="false" @positive-click="AddManageTaskList2([item])">
                <template #trigger>
                  <div class="left">
                    <span class="right_title">执&nbsp;&nbsp;&nbsp;行</span>
                    <NAvatar class="avatars2" :src="RightIconn" />
                  </div>
                </template>
                确认执行当前任务？
              </NPopconfirm>
              <!-- <span v-if="item.TaskStatus === 0" class="right_title" @click="AddManageTaskList">执行</span> -->
              <span v-if="item.TaskStatus === 1" class="right_title">执行中</span>
              <NAvatar v-if="item.TaskStatus === 1" class="avatars2" :src="StopIcon" />
            </div>
          </div>
        </div>
        <!-- 右上角标签 -->
        <div v-if="item.Ext1 === '1'" class="outin">待 回 库</div>
      </NCard>
    </NInfiniteScroll>
    <NCard v-if="!(Array.isArray(TodoWorkManageTask) && TodoWorkManageTask.length > 0)" class="notask">
      <NEmpty class="notask_" description="没有待执行的任务"></NEmpty>
    </NCard>
    <TaskDetailTodoWork
      v-if="showTaskDetail"
      :task-data="currentTaskData"
      @submitted="onTaskDetailSubmitted"
    ></TaskDetailTodoWork>
  </div>
</template>

<style scoped>
.notask {
  height: 100%;
}
.notask_ {
  margin-top: 10%;
}
.center {
  flex-grow: 1;
  padding: 0 50px;
}

.line {
  margin-top: 2vh;
  margin-bottom: 2vh;
  font-size: 14px;
}

.data-row {
  display: flex;
  gap: 10px;
  margin-top: 2vh;
}

.data-row span {
  flex: 1 1 20%;
  box-sizing: border-box;
  /* 强制不换行+省略号 */
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  /* 添加光标提示 */
  cursor: default;
}

.task-quantity {
  color: #868686;
  margin-right: 10px;
}
.card-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.flex-container {
  display: flex;
  justify-content: space-between; /* 将子元素分散在两端 */
  align-items: center; /* 垂直居中对齐 */
}
.left {
  display: flex;
  align-items: center;
}
.icon {
  font-size: 24px;
  margin-right: 8px;
}

.title {
  font-size: 20px;
  font-weight: bold;
  cursor: pointer;
}
.right_title {
  font-size: 18px;
  font-weight: bold;
}

.right {
  display: flex;
  justify-content: space-between;
  width: 140px;
}

.btn {
  cursor: pointer;
  margin-right: 1vw;
  margin-left: 1vw;
}

.avatars {
  background-color: transparent;
  margin-right: 10px;
  margin-left: 10px;
  min-width: 30px;
  min-height: 30px;
}
.avatars2 {
  background-color: transparent;
  margin-left: 10px;
  min-width: 30px;
  min-height: 30px;
}
.item {
  margin-bottom: 15px;
}

.outin {
  position: absolute;
  top: 0;
  right: 0;
  width: 100px;
  height: 30px;
  background-color: #43b36b;
  border-bottom-left-radius: 10px;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  /* font-weight: bold; */
}
</style>
