<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="name"
        class="tw-mr-4"
        style="width: 178px"
        placeholder="姓名"
        allowClear
      ></a-input>
      <span class="tw-mr-4"></span>
      <a-input
        v-model:value="loginName"
        style="width: 178px"
        placeholder="登录名"
        allowClear
      ></a-input>
      <span class="tw-mr-4"></span>
      <RoleSelect v-model:value="role" :rootOrgId="rootOrgId" />
      <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 class="tw-flex tw-gap-2 tw-my-4">
      <a-button type="primary" @click="newUser">新增</a-button>
      <a-button @click="importModalVisible = true">批量导入</a-button>
      <a-button @click="handleExport">批量导出</a-button>
      <a-button @click="handleToggleUsers(true, selectIds)">
        批量启用
      </a-button>
      <a-button @click="handleToggleUsers(false, selectIds)">
        批量禁用
      </a-button>
      <a-button @click="handleResetUsers(selectIds)">批量重置密码</a-button>
    </div>

    <div class="tw-bg-white tw-p-5 tw-rounded-xl">
      <a-table
        rowKey="id"
        :columns="columns"
        :scroll="{ x: 1200 }"
        :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 #enable="{ text }">
          <a>{{ $filters.booleanEnableDisableFilter(text) }}</a>
        </template>
        <template #action="{ record }">
          <span>
            <a-button @click="showModal(record)">编辑</a-button>
            <a-button @click="handleToggleUsers(!record.enable, [record.id])">
              {{ record.enable ? "禁用" : "启用" }}
            </a-button>
            <a-popover placement="bottom">
              <template #content>
                <div class="tw-flex tw-flex-col">
                  <a-button
                    type="text"
                    style="color: white"
                    @click="handleResetUsers([record.id])"
                  >
                    重置密码
                  </a-button>
                  <a-button
                    v-if="store.isGreaterThanEqualRootOrgAdmin"
                    type="text"
                    style="color: white"
                    @click="handleUserPrivilege(record.id)"
                  >
                    权限设置
                  </a-button>
                </div>
              </template>
              <a-button>更多</a-button>
            </a-popover>
          </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="userObj.rootOrgId"
            :disabled="!!userObj.id"
            selectFirst
          />
        </a-form-item>
        <a-form-item label="姓名">
          <a-input v-model:value="userObj.name"></a-input>
        </a-form-item>
        <a-form-item label="登录名">
          <a-input
            v-model:value="userObj.loginName"
            :disabled="!!userObj.id"
          ></a-input>
        </a-form-item>
        <a-form-item label="登录密码">
          <a-input
            v-model:value="userObj.password"
            :disabled="!!userObj.id"
          ></a-input>
        </a-form-item>
        <a-form-item label="角色">
          <RoleSelect
            v-model:value="userObj.role"
            :rootOrgId="userObj.rootOrgId"
          />
        </a-form-item>
        <!-- <a-form-item v-if="curRoleCode === 'COURSE_ADMIN'" label="负责科目">
          <a-input
            v-model:value="userObj.course"
            placeholder="多个科目用中文逗号隔开"
          ></a-input>
        </a-form-item> -->
        <a-form-item label="状态">
          <a-radio-group v-model:value="userObj.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 v-show="store.isSuperAdmin" label="学校">
          <RootOrgSelect
            v-show="store.isSuperAdmin"
            v-model:value="userObj.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 {
  exportUsers,
  getUserList,
  importUsers,
  resetPasswords,
  toggleUsers,
  updateUser,
} from "@/api/userManagementPage";
import router from "@/router";
import { useMainStore } from "@/store";
import { User } from "@/types";
import { downloadFileURL } from "@/utils/utils";
import { message, Modal } from "ant-design-vue";
import { watch, onMounted, ref, reactive, toRaw, h } from "vue";

const store = useMainStore();
store.currentLocation = "基础管理 / 用户管理";

let rootOrgId = $ref<null | number>(null);
let role = $ref(undefined as unknown as string);
let loginName = $ref("");
let name = $ref("");
let enable = $ref(undefined as undefined | boolean);

let data = $ref<User[]>([]);
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);
watch(
  () => store.isSuperAdmin,
  (val) => {
    rootOrgId = val ? null : store.userInfo.rootOrgId;
  }
);

async function fetchData() {
  if (!rootOrgId) return;
  const res = await getUserList({
    loginName,
    name,
    enable,
    role,
    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: "name",
    width: 80,
  },
  {
    title: "登录名",
    dataIndex: "loginName",
    width: 100,
  },
  {
    title: "角色",
    dataIndex: "roleName",
    width: 120,
  },
  {
    title: "状态",
    dataIndex: "enable",
    slots: { customRender: "enable" },
    width: 60,
  },
  {
    title: "创建时间",
    dataIndex: "createTime",
    width: 180,
  },
  {
    title: "创建人",
    dataIndex: "creator",
    width: 80,
  },
  {
    title: "更新时间",
    dataIndex: "updateTime",
    width: 180,
  },
  {
    title: "更新人",
    dataIndex: "updater",
    width: 80,
  },
  {
    title: "操作",
    key: "action",
    slots: { customRender: "action" },
    fixed: "right",
    width: 270,
  },
];

onMounted(async () => {
  rootOrgId = store.isSuperAdmin ? null : store.userInfo.rootOrgId;
  await search();
});

const visible = ref<boolean>(false);

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

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

const initUser = <User>(<unknown>{
  id: undefined,
  code: "",
  name: "",
  loginName: "",
  password: "",
  enable: true,
  role: "",
  rootOrgId: store.isSuperAdmin ? null : store.userInfo.rootOrgId,
});
let userObj = reactive({ ...initUser });

const newUser = () => {
  Object.assign(userObj, initUser);
  userObj.rootOrgId = rootOrgId as number;
  showModal(userObj);
};

// let curRoleCode = $ref("");
// function roleChange(data: RoleOption | null) {
//   curRoleCode = data ? data.code : "";
// }

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

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

/** <handleImport> */
let importModalVisible = $ref<boolean>(false);
async function handleImport() {
  if (!rootOrgId) {
    void message.error("请先选择结构");
    return;
  }
  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 importUsers(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() {
  if (!rootOrgId) {
    void message.error("请先选择结构");
    return;
  }
  await exportUsers({ rootOrgId, name, loginName, role, enable });
  void message.success({ content: "导出成功" });
}

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

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

async function handleUserPrivilege(userId: number) {
  await router.push("/basic/user/privilege/" + userId);
}

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