<template>
  <div>
    <div class="tw-bg-white tw-p-5 tw-rounded-xl tw-mb-5">
      <ProjectCourseSelect v-model:value="courseId" :projectId="projectId" />
      <span class="tw-mr-4"></span>
      <a-button class="query-btn" @click="clickSearch">查询</a-button>
    </div>

    <div class="tw-my-4 tw-flex tw-gap-2">
      <a-button @click="importModalVisible = true">批量导入</a-button>
      <a-button @click="handleExport">批量导出</a-button>
      <a-button @click="goBack">返回</a-button>
    </div>

    <div class="tw-bg-white tw-p-5 tw-rounded-xl">
      <a-table
        rowKey="id"
        :columns="columns"
        :data-source="data"
        :pagination="{
          pageSize: pageSize,
          current: pageNo,
          total: totalElements,
          showTotal: () => ``,
          onChange: (pageNoChanged, pageSizeChanged) => {
            pageNo = pageNoChanged;
            pageSize = pageSizeChanged;
          },
        }"
      >
        <template #course="{ record }">
          <a>{{ `${record.courseName}(${record.courseCode})` }}</a>
        </template>
        <template #action="{ record }">
          <span>
            <a-button @click="showModal(record)">编辑</a-button>
          </span>
        </template>
      </a-table>
    </div>

    <a-modal
      v-model:visible="visible"
      title="单科线设置页"
      okText="确定"
      cancelText="取消"
      @ok="handleOk"
    >
      <a-form :labelCol="{ span: 5 }">
        <a-form-item label="项目名称">
          <a-input v-model:value="projectObj.projectName" disabled></a-input>
        </a-form-item>
        <a-form-item label="科目名称">
          <a-input
            disabled
            :value="projectObj.courseName + '(' + projectObj.courseCode + ')'"
          ></a-input>
        </a-form-item>
        <a-form-item label="科目类型">
          <CourseTypeSelect :value="projectObj.courseType" disabled />
        </a-form-item>

        <a-form-item label="起始计算分">
          <a-input-number
            v-model:value="projectObj.startScore"
            :min="0"
            :max="1000"
          />
        </a-form-item>
        <a-form-item label="国家单科线" :min="0" :max="1000">
          <a-input-number
            v-model:value="projectObj.nationalScore"
          ></a-input-number>
        </a-form-item>
        <a-form-item label="复试科目线">
          <a-input-number
            v-model:value="projectObj.retestScore"
            :min="0"
            :max="1000"
          ></a-input-number>
        </a-form-item>
        <!-- <a-form-item label="国家总分线">
          <a-input v-model:value="projectObj.nationalTotalScore"></a-input>
        </a-form-item>
        <a-form-item label="复试总分线">
          <a-input v-model:value="projectObj.retestTotalScore"></a-input>
        </a-form-item> -->
        <!-- <a-form-item label="总分满分线">
          <a-input v-model:value="projectObj.totalScoreLine"></a-input>
        </a-form-item> -->
      </a-form>
    </a-modal>

    <a-modal
      v-model:visible="importModalVisible"
      title="单科线批量导入"
      okText="确定"
      cancelText="取消"
      @ok="handleImport"
    >
      <a-form>
        <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-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import {
  exportProjectParams,
  getProjectCourseList,
  importProjectParams,
  updateProjectCourse,
} from "@/api/projectParamsManagementPage";
import { useMainStore } from "@/store";
import { ProjectCourse } from "@/types";
import { downloadFileURL, goBack } from "@/utils/utils";
import { message } from "ant-design-vue";
import { watch, onMounted, ref, reactive, toRaw, h } from "vue";
import { useRoute } from "vue-router";

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

// let rootOrgId = $ref(undefined as unknown as number);
let courseId = $ref(undefined as undefined | number);
const route = useRoute();
const projectId = +route.params.projectId;

let data = $ref<ProjectCourse[]>([]);
let pageSize = $ref(10);
let pageNo = $ref(1);
let totalElements = $ref(0);

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

async function clickSearch() {
  pageNo = 1;
  await fetchData();
}

watch(() => [pageNo, pageSize], fetchData);

async function fetchData() {
  const res = await getProjectCourseList({
    projectId,
    courseId,
    pageSize,
    pageNo,
  });
  // console.log(res);
  data = res.data.content;
  pageNo = res.data.pageNo;
  pageSize = res.data.pageSize;
  totalElements = res.data.totalElements;
}

const columns = [
  {
    title: "科目",
    dataIndex: "course",
    slots: { customRender: "course" },
  },
  {
    title: "起始计算分",
    dataIndex: "startScore",
  },
  {
    title: "国家单科线",
    dataIndex: "nationalScore",
  },
  {
    title: "复试科目线",
    dataIndex: "retestScore",
  },
  // {
  //   title: "国家总分线",
  //   dataIndex: "nationalTotalScore",
  // },
  // {
  //   title: "复试总分线",
  //   dataIndex: "retestTotalScore",
  // },
  // {
  //   title: "总分满分线",
  //   dataIndex: "totalScoreLine",
  // },
  {
    title: "操作",
    key: "action",
    width: 120,
    slots: { customRender: "action" },
  },
];

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

const visible = ref<boolean>(false);

const showModal = (record: ProjectCourse) => {
  Object.assign(projectObj, record);
  visible.value = true;
};

const handleOk = async () => {
  await updateProjectCourse(toRaw(projectObj));
  visible.value = false;
  await search();
  void message.success({ content: "操作成功" });
};

const initProject = <ProjectCourse>(<unknown>{
  id: 0,
  nationalScore: 0,
  nationalTotalScore: 0,
  startScore: 0,
  retestScore: 0,
  retestTotalScore: 0,
  totalScoreLine: 0,
  projectName: "",
  courseName: "",
  courseCode: "",
  courseType: undefined,
});
const projectObj = reactive({ ...initProject });

/** <handleImport> */
let importModalVisible = $ref<boolean>(false);
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 = "";
  const res = await importProjectParams(projectId, fileToImport);
  if (!res.data.hasError) {
    importModalVisible = false;
    void message.success({ content: "导入成功" });
    await clickSearch();
  } else {
    // eslint-disable-next-line
    const msg = res.data.failRecords.map((v) =>
      h("div", `行号：${v.lineNum}, 错误：${v.msg}`)
    );
    void message.error({
      content: h("span", ["导入失败", ...msg]),
    });
  }
}
/** </handleImport> */

async function handleExport() {
  await exportProjectParams(projectId);
  void message.success({ content: "导出成功" });
}

async function downloadTpl() {
  await downloadFileURL("/api/ess/projectCourse/template");
}
</script>
