<template>
  <div>
    <div class="tw-bg-white tw-p-5 tw-rounded-xl tw-mb-5">
      <a-switch v-model:checked="checked" @click="toggleAll" /> 全部科目
      <div class="tw-float-right tw-flex tw-gap-2">
        <a-button :danger="true" @click="handleDeletePrivilege">删除</a-button>
        <a-button @click="showModal">添加</a-button>
      </div>
    </div>

    <div class="tw-bg-white tw-p-5 tw-rounded-xl">
      <a-table
        rowKey="courseId"
        :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;
          },
        }"
      >
      </a-table>
    </div>

    <a-modal
      v-model:visible="visible"
      title="信息页"
      okText="确定"
      cancelText="取消"
      @ok="handleOk"
    >
      <a-form layout="inline">
        <a-form-item label="科目名称">
          <a-input v-model:value="userObj.name"></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-button class="query-btn" @click="fetchData2">查询</a-button>
      </a-form>
      <div class="tw-bg-white tw-py-5 tw-rounded-xl">
        <a-table
          rowKey="id"
          :columns="columns2"
          :data-source="data2"
          :rowSelection="{
            selectedRowKeys: selectIds2,
            onChange: handleRowSelect2,
          }"
          :pagination="{
            pageSize: pageSize2,
            current: pageNo2,
            total: totalElements2,
            showTotal: () => ``,
            onChange: (pageNoChanged, pageSizeChanged) => {
              selectIds2 = [];
              pageNo2 = pageNoChanged;
              pageSize2 = pageSizeChanged;
            },
          }"
        >
          <template #enable="{ text }">
            <a>{{ $filters.booleanEnableDisableFilter(text) }}</a>
          </template>
        </a-table>
      </div>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import {
  addListForUserPrivilege,
  deleteListForUserPrivilege,
  getToAddListForUserPrivilege,
  getUserPrivilegegDefaultAll,
  getUserPrivilegegList,
  modifyUserPrivilegegDefaultAll,
} from "@/api/userManagementPage";
import { useMainStore } from "@/store";
import { message } from "ant-design-vue";
import { watch, onMounted, reactive } from "vue";
import { useRoute } from "vue-router";

const PRIVI_TYPE = "COURSE";
const store = useMainStore();

const route = useRoute();
const userId = +route.params.userId;

let checked = $ref(false);
async function toggleAll() {
  await modifyUserPrivilegegDefaultAll({
    enabled: checked,
    type: PRIVI_TYPE,
    userId,
  });
  void message.success({ content: "修改成功" });
  await search();
}

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 res0 = await getUserPrivilegegDefaultAll({
    userId,
    type: PRIVI_TYPE,
  });
  checked = res0.data;

  const res = await getUserPrivilegegList({
    ptype: PRIVI_TYPE,
    userId,
    pageSize,
    pageNo,
  });
  // console.log(res);
  data = res.data.content;
  pageNo = res.data.pageNo;
  pageSize = res.data.pageSize;
  totalElements = res.data.totalElements;
}

const columns = [
  {
    title: "科目ID",
    dataIndex: "courseId",
    width: 150,
  },
  {
    title: "科目编码",
    dataIndex: "courseCode",
  },
  {
    title: "科目名称",
    dataIndex: "courseName",
  },
];

onMounted(async () => {
  await search();
});

let visible = $ref<boolean>(false);

const showModal = () => {
  Object.assign(userObj, initUser);
  visible = true;
};

const initUser = {
  code: "",
  name: "",
  enable: true,
  rootOrgId: store.userInfo.rootOrgId,
};
const userObj = reactive({ ...initUser });

function checkEmpty(selectIds: number[]): boolean {
  if (selectIds && selectIds.length > 0) {
    return false;
  } else {
    void message.warn({ content: "请先选择行" });
    return true;
  }
}
async function handleDeletePrivilege() {
  if (checkEmpty(selectIds)) return;
  await deleteListForUserPrivilege({
    type: PRIVI_TYPE,
    userId,
    refIds: selectIds,
  });
  selectIds = [];
  await search();
  void message.success({ content: "操作成功" });
  selectIds = [];
}

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

/** <Modal> */
let data2 = $ref([]);
let pageSize2 = $ref(10);
let pageNo2 = $ref(1);
let totalElements2 = $ref(0);

const columns2 = [
  {
    title: "科目编码",
    dataIndex: "code",
    width: 150,
  },
  {
    title: "科目名称",
    dataIndex: "name",
  },
  {
    title: "状态",
    dataIndex: "enable",
    slots: { customRender: "enable" },
  },
];

watch(() => [pageNo2, pageSize2], fetchData2);

async function fetchData2() {
  const res = await getToAddListForUserPrivilege({
    ptype: PRIVI_TYPE,
    rootOrgId: store.userInfo.rootOrgId,
    userId,
    name: userObj.name,
    // enable: userObj.enable,
    pageSize: pageSize2,
    pageNo: pageNo2,
  });
  // console.log(res);
  data2 = res.data.content;
  pageNo2 = res.data.pageNo;
  pageSize2 = res.data.pageSize;
  totalElements2 = res.data.totalElements;
}

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

function checkEmpty2(): boolean {
  if (selectIds2 && selectIds2.length > 0) {
    return false;
  } else {
    void message.warn({ content: "请先选择行" });
    return true;
  }
}
async function handleOk() {
  if (checkEmpty2()) return;
  await addListForUserPrivilege({
    type: PRIVI_TYPE,
    userId,
    refIds: selectIds2,
  });
  selectIds2 = [];
  await search();
  visible = false;
  void message.success({ content: "操作成功" });
}
/** </Modal> */
const handleRowSelect = (selectedRowKeys: (string | number)[]) => {
  selectIds = selectedRowKeys as number[];
};
const handleRowSelect2 = (selectedRowKeys: (string | number)[]) => {
  selectIds2 = selectedRowKeys as number[];
};
</script>
