<template>
  <div>
    <div class="tw-bg-white tw-p-5 tw-rounded-xl tw-mb-5">
      <RootOrgSelect v-if="store.isSuperAdmin" v-model:value="rootOrgId" />

      <span class="tw-mr-4"></span>
      <a-input
        v-model:value="code"
        style="width: 178px"
        placeholder="科目代码"
        allowClear
      ></a-input>
      <span class="tw-mr-4"></span>
      <a-input
        v-model:value="name"
        class="tw-mr-4"
        style="width: 178px"
        placeholder="科目名称"
        allowClear
      ></a-input>

      <span class="tw-mr-4"></span>
      <CourseTypeSelect v-model:value="type" />
      <span class="tw-mr-4"></span>
      <StateSelect v-model:value="enable" />
      <span class="tw-mr-4"></span>
      <a-button class="query-btn" @click="clickSearch">查询</a-button>
    </div>

    <div
      v-if="store.isGreaterThanEqualRootOrgAdmin"
      class="tw-flex tw-gap-2 tw-my-4"
    >
      <a-button type="primary" @click="newCourse">新增</a-button>
      <a-button @click="importModalVisible = true">批量导入</a-button>
      <a-button @click="handleExport">批量导出</a-button>
      <a-button @click="handleToggleCourses(true, selectIds)">
        批量启用
      </a-button>
      <a-button @click="handleToggleCourses(false, selectIds)">
        批量禁用
      </a-button>
    </div>

    <div class="tw-bg-white tw-p-5 tw-rounded-xl">
      <a-table
        rowKey="id"
        :columns="columns"
        :scroll="{ x: 1500 }"
        :data-source="data"
        :rowSelection="{
          selectedRowKeys: selectIds,
          onChange: handleRowSelect,
        }"
        :pagination="{
          pageSize: pageSize,
          current: pageNo,
          total: totalElements,
          showTotal: () => ``,
          onChange: (pageNoChanged, pageSizeChanged) => {
            selectIds = [];
            pageNo = pageNoChanged;
            pageSize = pageSizeChanged;
          },
        }"
      >
        <template #rootOrgName="{ record }">
          <a-tooltip placement="topLeft">
            <template #title
              >{{ record.rootOrgName }}({{ record.rootOrgCode }})</template
            >
            {{ record.rootOrgName }}({{ record.rootOrgCode }})
          </a-tooltip>
          <!-- <a>{{ record.rootOrgName }}({{ record.rootOrgCode }})</a> -->
        </template>
        <template #name="{ record }">
          <a-tooltip placement="topLeft">
            <template #title>{{ record.name }}</template>
            {{ record.name }}
          </a-tooltip>
        </template>
        <template #type="{ text }">
          <a>{{ $filters.courseTypeFilter(text) }}</a>
        </template>
        <template #enable="{ text }">
          <a>{{ $filters.booleanEnableDisableFilter(text) }}</a>
        </template>
        <template #action="{ record }">
          <span v-if="store.isGreaterThanEqualRootOrgAdmin">
            <a-button @click="showModal(record)">编辑</a-button>
            <a-button @click="handleToggleCourses(!record.enable, [record.id])">
              {{ record.enable ? "禁用" : "启用" }}
            </a-button>
          </span>
        </template>
      </a-table>
    </div>

    <a-modal
      v-model:visible="visible"
      title="科目信息页"
      okText="确定"
      cancelText="取消"
      @ok="handleOk"
    >
      <a-form :labelCol="{ span: 4 }">
        <a-form-item v-show="store.isSuperAdmin" label="学校">
          <RootOrgSelect
            v-model:value="courseObj.rootOrgId"
            :disabled="!!courseObj.id"
          />
        </a-form-item>
        <a-form-item label="科目代码">
          <a-input
            v-model:value="courseObj.code"
            :disabled="!!courseObj.id"
          ></a-input>
        </a-form-item>
        <a-form-item label="科目名称">
          <a-input v-model:value="courseObj.name"></a-input>
        </a-form-item>
        <a-form-item label="科目类型">
          <CourseTypeSelect v-model:value="courseObj.type" />
        </a-form-item>
        <a-form-item label="状态">
          <a-radio-group v-model:value="courseObj.enable">
            <a-radio :value="true">启用</a-radio>
            <a-radio :value="false">禁用</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-form>
    </a-modal>

    <a-modal
      v-model:visible="importModalVisible"
      title="批量科目导入"
      okText="确定"
      cancelText="取消"
      @ok="handleImport"
    >
      <a-form>
        <a-form-item label="学校">
          <RootOrgSelect
            v-show="store.isSuperAdmin"
            v-model:value="courseObj.rootOrgId"
          />
        </a-form-item>
        <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 {
  exportCourses,
  getCourseList,
  importCourses,
  toggleCourses,
  updateCourse,
} from "@/api/courseManagementPage";
import { useMainStore } from "@/store";
import { Course, Course_Type } from "@/types";
import { downloadFileURL } from "@/utils/utils";
import { message } from "ant-design-vue";
import { watch, onMounted, ref, reactive, toRaw, h } from "vue";

const store = useMainStore();
store.currentLocation = "基础管理 / 科目管理";

let rootOrgId = $ref(undefined as unknown as number);
let type = $ref(undefined as unknown as Course_Type); // 科目类型
let code = $ref("");
let name = $ref("");
let enable = $ref(undefined as undefined | boolean);

let data = $ref<Course[]>([]);
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 getCourseList({
    code,
    name,
    enable,
    type,
    rootOrgId,
    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: "rootOrgName",
    width: 200,
    slots: { customRender: "rootOrgName" },
    ellipses: true,
  },
  {
    title: "科目代码",
    dataIndex: "code",
    width: 100,
  },
  {
    title: "科目名称",
    dataIndex: "name",
    slots: { customRender: "name" },
    width: 180,
  },
  {
    title: "科目类型",
    dataIndex: "type",
    slots: { customRender: "type" },
    width: 100,
  },
  {
    title: "状态",
    dataIndex: "enable",
    slots: { customRender: "enable" },
    width: 60,
  },
  {
    title: "创建时间",
    dataIndex: "createTime",
    width: 180,
  },
  {
    title: "创建人",
    dataIndex: "creator",
    width: 90,
  },
  {
    title: "更新时间",
    dataIndex: "updateTime",
    width: 180,
  },
  {
    title: "更新人",
    dataIndex: "updater",
    width: 90,
  },
  {
    title: "操作",
    key: "action",
    slots: { customRender: "action" },
    fixed: "right",
    width: 180,
  },
];

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

const visible = ref<boolean>(false);

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

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

const initCourse = <Course>(<unknown>{
  id: undefined,
  code: "",
  name: "",
  enable: true,
  type: undefined,
  rootOrgId: store.userInfo.rootOrgId,
});
const courseObj = reactive({ ...initCourse });

const newCourse = () => {
  Object.assign(courseObj, initCourse);
  showModal(courseObj);
};

function checkEmpty(selectIds: number[]): boolean {
  if (selectIds && selectIds.length > 0) {
    return false;
  } else {
    void message.warn({ content: "请先选择行" });
    return true;
  }
}
async function handleToggleCourses(enable: boolean, ids: number[]) {
  if (checkEmpty(ids)) return;
  await toggleCourses(enable, ids);
  selectIds = [];
  await search();
}

/** <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 importCourses(rootOrgId, 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 exportCourses({ rootOrgId, name, code, type, enable });
  void message.success({ content: "导出成功" });
}

let selectIds = $ref<number[]>([]);

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

const handleRowSelect = (selectedRowKeys: (string | number)[]) => {
  selectIds = selectedRowKeys as number[];
};
</script>
