<template>
  <div>
    <div class="tw-bg-white tw-p-5 tw-rounded-xl tw-mb-5">
      项目名称
      <a-input
        v-model:value="project.name"
        disabled
        class="tw-mr-4"
        style="width: 178px"
        placeholder="项目名称"
        allowClear
      ></a-input>

      <span class="tw-mr-4"></span>
      数据解析状态
      <a-input
        disabled
        :value="$filters.projectStatusFilter(project.status)"
        class="tw-mr-4"
        style="width: 178px"
        placeholder="项目名称"
        allowClear
      ></a-input>
      <span class="tw-mr-4"></span>
      <a-button @click="goBack">返回</a-button>
    </div>

    <div class="tw-bg-white tw-p-5 tw-rounded-xl">
      <a-radio-group
        v-model:value="dataSourceChannel"
        :options="[...plainOptions]"
      />
      <div class="tw-mb-5"></div>
      <a-form v-if="dataSourceChannel === '数据上传'">
        <a-form-item label="文件地址">
          <input id="file-input" :multiple="false" type="file" />
        </a-form-item>
        <a-form-item label="下载模板">
          <a-button class="download-tpl-btn" @click="downloadTpl">
            下载模板
          </a-button>
        </a-form-item>
        <a-button type="primary" @click="handleImport">保存</a-button>
      </a-form>
      <a-form v-else>
        <a-form-item label="系统域名">
          <a-input v-model:value="domain" placeholder="http://192.168.10.100" />
        </a-form-item>
        <a-form-item label="考试标识">
          <a-select v-model:value="examId" placeholder="请选择考试">
            <a-select-option
              v-for="(item, index) in exams"
              :key="index"
              :value="item.id"
            >
              {{ item.name }}({{ item.id }})
            </a-select-option>
          </a-select>
        </a-form-item>
        <div class="tw-flex tw-gap-2">
          <a-button type="primary" @click="handleTestServer">测试</a-button>
          <a-button type="primary" @click="handleSync">保存</a-button>
        </div>
      </a-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import {
  getProjectList,
  importProjectDataSource,
} from "@/api/projectManagementPage";
import { httpApp } from "@/plugins/axiosApp";
import { useMainStore } from "@/store";
import { Project } from "@/types";
import { downloadFileURL, goBack } from "@/utils/utils";
import { message } from "ant-design-vue";
import { debounce } from "lodash-es";
import QueryString from "qs";
import { onMounted, computed, watch } from "vue";
import { useRoute } from "vue-router";

const store = useMainStore();
store.currentLocation = "项目管理 / 项目列表 / 数据管理";

let rootOrgId = $ref(undefined as unknown as number);

const route = useRoute();
const projectId = +route.params.projectId;
let data = $ref<Project[]>([]);

let project = computed(() => data[0] || {});

async function search() {
  await fetchData();
}

async function fetchData() {
  const res = await getProjectList({
    id: projectId,
    rootOrgId,
  });
  data = res.data.content;
}

onMounted(async () => {
  rootOrgId = store.userInfo.rootOrgId;
  await search();
});

async function downloadTpl() {
  await downloadFileURL("/api/ess/project/template");
}

async function handleImport() {
  const files = (document.querySelector("#file-input") as HTMLInputElement)
    .files;
  const fileToImport = files && files[0];
  if (!fileToImport) {
    void message.warn({ content: "请选择文件" });
    return;
  }
  (document.querySelector("#file-input") as HTMLInputElement).value = "";
  await importProjectDataSource(projectId, fileToImport);
  void message.success({ content: "导入成功" });
}

const plainOptions = ["数据上传", "资料同步"] as const;
let dataSourceChannel: typeof plainOptions[number] = $ref("数据上传");

const domain = $ref("");

async function handleTestServer() {
  if (!domain) {
    void message.warn({ content: "请先填写域名" });
    return;
  }
  try {
    const res = await httpApp.post<any, { data: string }>(
      "/api/ess/task/sync/test",
      QueryString.stringify({
        domain,
        projectId,
      })
    );
    // console.log(res);
    void message.info(res.data);
  } catch (error) {
    console.log(error);
    void message.info("网络失败，请检查网络或联系管理员!");
  }
}

interface Exam {
  id: number;
  name: string;
}

let exams: Exam[] = $ref([]);
async function fetchExamsFromOtherServer() {
  if (!domain) {
    return;
  }
  try {
    const res = await httpApp.post<any, { data: Exam[] }>(
      "/api/ess/task/exams",
      QueryString.stringify({
        domain,
        projectId,
      }),
      { noErrorMessage: true }
    );
    // console.log(res);
    // void message.info(res.data);
    exams = res.data;
  } catch (error) {
    console.log(error);
    // void message.info("网络失败，请检查网络或联系管理员!");
  }
}

const deboundcedFunc = debounce(fetchExamsFromOtherServer, 5000);
watch(
  () => [domain],
  () => {
    void deboundcedFunc();
  }
);

let examId: string = $ref(null as unknown as string);

async function handleSync() {
  if (typeof examId !== "number") {
    void message.warn("请先选择考试");
    return;
  }
  await httpApp.post("/api/ess/task/sync", {
    domain,
    examId,
    projectId,
  });

  void message.warn("正在同步中...");
}
</script>
