<template>
  <div>
    <div class="tw-bg-white tw-p-5 tw-rounded-xl tw-mb-5">
      <template v-if="store.isSuperAdmin">
        <RootOrgSelect v-model:value="rootOrgId" />
        <span class="tw-mr-4"></span>
      </template>
      <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>
      <StateSelect v-model:value="enable" />
      <span class="tw-mr-4"></span>
      <a-button class="query-btn" @click="search(1)">查询</a-button>
    </div>

    <div class="tw-flex tw-gap-2 tw-my-4">
      <a-button type="primary" @click="newOrg">新增</a-button>
      <a-button @click="importModalVisible = true">批量导入</a-button>
      <a-button @click="handleExport">批量导出</a-button>
      <a-button @click="handleToggleOrg(true, selectIds)">批量启用</a-button>
      <a-button @click="handleToggleOrg(false, selectIds)">批量禁用</a-button>
      <!-- 不做删除 https://zentao2.qmth.com.cn/bug-view-2612.html -->
      <!-- <a-button @click="handleDelOrg(selectIds)">批量删除</a-button> -->
    </div>

    <div class="tw-bg-white tw-p-5 tw-rounded-xl">
      <a-table
        rowKey="id"
        :columns="columns"
        :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 #enable="{ text }">
          <a>{{ $filters.booleanEnableDisableFilter(text) }}</a>
        </template>
        <template #action="{ record }">
          <span>
            <a-button @click="showModal(record)">编辑</a-button>
            <a-button @click="handleToggleOrg(!record.enable, [record.id])">
              {{ record.enable ? "禁用" : "启用" }}
            </a-button>
            <!-- <a-button @click="handleDelOrg([record.id])">删除</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="orgObj.rootOrgId"
            :disabled="!!orgObj.id"
          />
        </a-form-item>
        <a-form-item label="机构名称">
          <a-input v-model:value="orgObj.name"></a-input>
        </a-form-item>
        <a-form-item label="机构编码">
          <a-input
            v-model:value="orgObj.code"
            :disabled="!!orgObj.id"
          ></a-input>
        </a-form-item>
        <a-form-item label="状态">
          <a-radio-group v-model:value="orgObj.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="orgObj.rootOrgId"
            :disabled="!!orgObj.id"
          />
        </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 {
  exportOrgs,
  getSubOrgList,
  importOrgs,
  toggleSubOrgs,
  updateSubOrg,
} from "@/api/subOrgPage";
import { useMainStore } from "@/store";
import { SubOrg } 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 code = $ref("");
let name = $ref("");
let enable = $ref(undefined as undefined | boolean);

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

async function search(goPageNo?: number) {
  if (typeof goPageNo === "number") pageNo = goPageNo;
  await fetchData();
}

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

async function fetchData() {
  const res = await getSubOrgList({
    code,
    name,
    enable,
    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: 150,
  },
  {
    title: "机构代码",
    dataIndex: "code",
    width: 150,
  },
  {
    title: "机构名称",
    dataIndex: "name",
    width: 150,
  },
  {
    title: "状态",
    dataIndex: "enable",
    slots: { customRender: "enable" },
  },
  {
    title: "创建时间",
    dataIndex: "createTime",
  },
  {
    title: "创建人",
    dataIndex: "creator",
  },
  {
    title: "更新时间",
    dataIndex: "updateTime",
  },
  {
    title: "更新人",
    dataIndex: "updater",
  },
  {
    title: "操作",
    key: "action",
    slots: { customRender: "action" },
  },
];

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

const visible = ref<boolean>(false);

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

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

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

const newOrg = () => {
  Object.assign(orgObj, {
    id: undefined,
    code: "",
    name: "",
    enable: true,
    rootOrgId,
  });
  showModal(orgObj);
};

function checkEmpty(selectIds: number[]): boolean {
  if (selectIds && selectIds.length > 0) {
    return false;
  } else {
    void message.warn({ content: "请先选择行" });
    return true;
  }
}

async function handleToggleOrg(enable: boolean, ids: number[]) {
  if (checkEmpty(ids)) return;
  await toggleSubOrgs(enable, ids);
  selectIds = [];
  await search();
}

//  function handleDelOrg(ids: number[]) {
//   if (checkEmpty(ids)) return;
//   Modal.confirm({
//     title: "提示",
//     content: "确认删除？",
//     cancelText: "取消",
//     okText: "确定",
//     onOk: async () => {
//       await delOrgs(ids);
//       await search();
//       void message.success({ content: "操作成功" });
//     },
//   });
// }

/** <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 importOrgs(rootOrgId, fileToImport);
  if (!res.data.hasError) {
    importModalVisible = false;
    void message.success({ content: "导入成功" });
  } 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 exportOrgs({ rootOrgId, name, code, enable });
  void message.success({ content: "导出成功" });
}

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

async function downloadTpl() {
  await downloadFileURL("/api/ess/org/template");
}
const handleRowSelect = (selectedRowKeys: (string | number)[]) => {
  selectIds = selectedRowKeys as number[];
};
</script>
