<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 @click="handleDeletePrivilege" :danger="true">删除</a-button>
        <a-button @click="showModal">添加</a-button>
      </div>
    </div>

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

    <a-modal
      v-model:visible="visible"
      title="信息页"
      @ok="handleOk"
      ok-text="确定"
      cancel-text="取消"
    >
      <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 @click="fetchData2" class="query-btn">查询</a-button>
      </a-form>
      <div class="tw-bg-white tw-py-5 tw-rounded-xl">
        <a-table
          row-key="id"
          :columns="columns2"
          :data-source="data2"
          :row-selection="rowSelection2"
          :pagination="{
          pageSize: pageSize2,
          current: pageNo2,
          total: totalElements2,
          showTotal: (total: number) => `总数：${total}`,
          onChange: (pageNoChanged: number, pageSizeChanged: number) => {
            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-demi";
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,
  });
  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 {
    message.warn({ content: "请先选择行" });
    return true;
  }
}
async function handleDeletePrivilege() {
  if (checkEmpty(selectIds)) return;
  await deleteListForUserPrivilege({
    type: PRIVI_TYPE,
    userId,
    refIds: selectIds,
  });
  await search();
  message.success({ content: "操作成功" });
}

let selectIds = $ref<number[]>([]);
const rowSelection = {
  onChange: (selectedRowKeys: (string | number)[]) => {
    console.log(`selectedRowKeys: ${selectedRowKeys}`);
    selectIds = selectedRowKeys as 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,
    pageNo,
  });
  // console.log(res);
  data2 = res.data.content;
  pageNo2 = res.data.pageNo;
  pageSize2 = res.data.pageSize;
  totalElements2 = res.data.totalElements;
}

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

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