<template>
  <div>
    <el-card>
      <div class="title">爬虫管理</div>
      <div class="low-titme">Spider Manager</div>
      <el-divider class="divider" />
    </el-card>
    <div class="table-content">
      <el-table
        :data="tableData"
        style="width: 100%"
        border
        :header-cell-style="{ textAlign: 'center' }"
        :cell-style="{ textAlign: 'center' }"
        :row-style="{ height: '60px' }"
        v-loading="tableData.length == 0"
        element-loading-background="rgba(48, 65, 86, 0.7)"
      >
        <el-table-column property="number" label="序号" type="index" width="80" />
        <el-table-column property="spider" label="爬虫代号" show-overflow-tooltip />
        <el-table-column property="spider_name" label="爬虫名称" show-overflow-tooltip />
        <el-table-column property="spider_info" label="任务描述" show-overflow-tooltip />
        <el-table-column label="操作">
          <template #default="scope">
            <div class="btn-group">
              <el-button type="primary" plain @click="handleDetails(scope.row)">查看任务</el-button>
              <el-button type="primary" plain @click="handleEditSateId">编辑</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination w-full flex flex-row-reverse pr-4 m-t-4">
      <Pagination
        :total="pageObj.total"
        v-model:page="pageObj.pageNo"
        v-model:limit="pageObj.pageSize"
        @pagination="getData"
      />
    </div>

    //编辑弹窗
    <el-dialog style="z-index: 999999" draggable v-model="editDialogVisible" title="指定下载以下卫星" width="400">
      <div class="No-Content" ref="noContentRef">
        <TransitionGroup
          enter-active-class="animate__animated animate__slideInRight"
          leave-active-class="animate__animated animate__slideOutRight"
          enter-from-class="animate__opacity-0"
          leave-to-class="animate__opacity-0"
        >
          <NoItem
            v-for="(no, index) in sateNoList"
            :key="index"
            class="no-item-row"
            :-no="no"
            @add-no="handleSateAdd"
            @del-no="handleSateDel"
            :reset-selected="resetSelected"
          ></NoItem>
        </TransitionGroup>
      </div>
      <div class="footer">
        <div class="No">
          <span style="color: white; font-weight: 500">NORAD编号：</span>
          <el-input
            @input="handleNumInput"
            maxlength="5"
            placeholder="请输入编号"
            v-model="curSateNo"
            style="width: 100px"
          ></el-input>
        </div>
        <div class="btn">
          <el-button :disabled="curSateNo == ''" plain type="primary" @click="addNoToList">添加</el-button>
          <el-button plain type="danger" @click="delNoList">删除</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick } from "vue";
import Pagination from "@/components/pagination/index.vue";
import { useRouter } from "vue-router";
import { getSpiderList, addSateNo, getSateIdList } from "@/api/system.ts";
import NoItem from "./components/NoItem.vue";
import { ElMessage } from "element-plus";

const router = useRouter();
const tableData = ref([]);
const pageObj = ref({
  total: 10,
  pageSize: 10,
  pageNo: 1,
});
const handleDetails = (row: any) => {
  router.push({
    path: "/osTaskInformation/list",
    query: {
      jump: "yes",
      spiderType: row.spider,
      page: "spiderManager",
    },
  });
};
// 获取爬虫数据的方法
const getData = async () => {
  const res = await getSpiderList({ scrapydServerId: "1", project: "spiders" });
  tableData.value = res.data;
};

const editDialogVisible = ref(false);

const sateNoList = ref<string[]>([]);

const curSateNo = ref("");

const curSelSateNo = ref<(string | number)[]>([]);

const resetSelected = ref(false);

//添加选中项到当前列表
const handleSateAdd = (no: string | number) => {
  curSelSateNo.value.push(padZeroTo5Digits(no));
};

//从当前列表删除选中项
const handleSateDel = (no: string | number) => {
  curSelSateNo.value = curSelSateNo.value.filter((item) => item != no);
};
//添加编号到列表并整体发到后端
const addNoToList = async () => {
  try {
    if (sateNoList.value.includes(padZeroTo5Digits(curSateNo.value))) {
      ElMessage.error("当前编号已存在，请重新输入");
      curSateNo.value = "";
      return;
    }
    sateNoList.value.push(padZeroTo5Digits(curSateNo.value));
    const res = await addSateNo({ id: sateNoList.value });
    if (res.code === 0) {
      ElMessage.success("添加编号成功");
    } else {
      sateNoList.value.pop();
      ElMessage.error(res.message);
    }
    curSateNo.value = "";
    scrollToBottom();
  } catch (error: any) {
    ElMessage.error(error.message);
  }
};

//删除选中编号
const delNoList = async () => {
  try {
    sateNoList.value = sateNoList.value.filter((item) => !curSelSateNo.value.includes(item));
    const res = await addSateNo({ id: sateNoList.value as string[] });
    if (res.code === 0) {
      ElMessage.success("删除编号成功");
    }
    resetSelected.value = true;
    curSelSateNo.value = [];
    nextTick(() => {
      resetSelected.value = false;
    });
  } catch (error: any) {
    ElMessage.error(error.message);
  }
};

const noContentRef = ref<HTMLDivElement | null>(null);

//新添加滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    const container = noContentRef.value;
    if (container) {
      container.scrollTop = container.scrollHeight - container.clientHeight;
    }
  });
};

const handleNumInput = (value: string) => {
  const filtered = value.replace(/\D/g, "");
  curSateNo.value = filtered.slice(0, 5);
};

//编号格式化
const padZeroTo5Digits = (num: number | string): string => {
  const numStr = String(num);
  const pureNumStr = numStr.replace(/\D/g, "");
  return pureNumStr.padStart(5, "0").slice(-5);
};

const handleEditSateId = async () => {
  editDialogVisible.value = true;
  try {
    const res = await getSateIdList();
    if (res.code === 0) {
      sateNoList.value = res.data || [];
    }
    console.log(res);
  } catch (error: any) {
    ElMessage.error(error.message);
  }
};

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

<style scoped>
/* 去除按钮边框 */
.el-button:focus {
  outline: none;
}

.table-content {
  padding: 10px;
}

.title {
  text-align: left;
  font-size: 18px;
  font-weight: 500;
  color: white;
}

.low-titme {
  color: #ccc;
  text-align: left;
  margin-left: 20px;
}
.divider {
  margin-top: 15px;
}

.No-Content {
  width: 100%;
  height: 200px;
  background-color: #1d5484;
  border: 4px solid #083b67;
  display: flex;
  padding: 10px;
  box-sizing: border-box;
  flex-direction: column;
  gap: 10px;
  overflow-y: auto;
  overflow-x: hidden;
}

.footer {
  margin-top: 20px;
  display: flex;
  justify-content: space-between;
}

.No {
  display: flex;
  align-items: center;
}

.No-Content::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

.No-Content::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.No-Content::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
  box-shadow: inset 0 0 2px rgba(0, 0, 0, 0.1);
}

.No-Content::-webkit-scrollbar-thumb:hover {
  background: #999;
}

.No-Content::-webkit-scrollbar-button {
  display: none;
}

.No-Content {
  scrollbar-width: thin;
  scrollbar-color: #c1c1c1 #f1f1f1;
}

.btn-group {
  display: flex;
  gap: 8px;
  white-space: nowrap;
  justify-content: center;
}
.btn-group .el-button {
  flex-shrink: 0;
}
</style>
