<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" />
      <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 @click="search">查询</a-button>

      <div class="tw-mt-4">
        <a-button @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>
        <a-button @click="handleDelOrg(selectIds)">批量删除</a-button>
      </div>
    </div>

    <div class="tw-bg-white tw-p-5 tw-rounded-xl">
      <a-table
        row-key="id"
        :columns="columns"
        :data-source="data"
        :row-selection="rowSelection"
        :pagination="{
          pageSize: pageSize,
          current: pageNo,
          total: totalElements,
          showTotal: (total: number) => `总数：${total}`,
          onChange: (pageNoChanged: number, pageSizeChanged: number) => {
            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="机构信息页"
      @ok="handleOk"
      ok-text="确定"
      cancel-text="取消"
    >
      <a-form>
        <a-form-item v-show="store.isSuperAdmin" label="顶级机构">
          <RootOrgSelect
            :disabled="!!orgObj.id"
            v-model:value="orgObj.rootOrgId"
          />
        </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
            :disabled="!!orgObj.id"
            v-model:value="orgObj.code"
          ></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="批量机构导入"
      @ok="handleImport"
      ok-text="确定"
      cancel-text="取消"
    >
      <a-form>
        <a-form-item label="顶级机构">
          <RootOrgSelect
            v-show="store.isSuperAdmin"
            :disabled="!!orgObj.id"
            v-model:value="orgObj.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 @click="downloadTpl">下载模板</a-button>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import {
  delOrgs,
  exportOrgs,
  getSubOrgList,
  importOrgs,
  toggleSubOrgs,
  updateSubOrg,
} from "@/api/subOrgPage";
import { useMainStore } from "@/store";
import { downloadFileURL } from "@/utils/utils";
import { message, Modal } from "ant-design-vue";
import { watch, onMounted, ref, reactive, toRaw } from "vue-demi";

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([]);
let pageSize = $ref(10);
let pageNo = $ref(1);
let totalElements = $ref(0);

async function search() {
  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: "Action",
    key: "action",
    slots: { customRender: "action" },
  },
];

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

const visible = ref<boolean>(false);

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

const handleOk = async (e: MouseEvent) => {
  await updateSubOrg(toRaw(orgObj));
  visible.value = false;
  await search();
};

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

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

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

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

async function handleDelOrg(ids: number[]) {
  if (checkEmpty()) return;
  Modal.confirm({
    title: "提示",
    content: "确认删除？",
    cancelText: "取消",
    okText: "确定",
    onOk: async () => {
      await delOrgs(ids);
      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) {
    message.warn({ content: "请选择文件" });
    return;
  }

  await importOrgs(rootOrgId, fileToImport);
  message.success({ content: "导入成功" });
}
/** </handleImport> */

async function handleExport() {
  await exportOrgs({ rootOrgId, name, code, enable });
  message.success({ content: "导出成功" });
}

let selectIds = $ref<number[]>([]);
const rowSelection = {
  onChange: (selectedRowKeys: (string | number)[]) => {
    console.log(`selectedRowKeys: ${selectedRowKeys}`);
    selectIds = selectedRowKeys as number[];
  },
};

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