<template>
  <div>
    <div>
      <n-card :bordered="false" title="角色权限管理">
        为后台用户分配不同的角色权限，以达到操作隔离的目的
      </n-card>
    </div>
    <n-card :bordered="false" class="mt-4 proCard">
      <BasicTable
        :columns="columns"
        :request="loadDataTable"
        :row-key="(row) => row.id"
        ref="actionRef"
        :actionColumn="actionColumn"
        @update:checked-row-keys="onCheckedRow"
      >
        <template #tableTitle>
          <n-button type="primary" @click="addTable">
            <template #icon>
              <n-icon>
                <PlusOutlined />
              </n-icon>
            </template>
            添加角色
          </n-button>
        </template>

        <template #action>
          <TableAction />
        </template>
      </BasicTable>
    </n-card>

    <n-modal
      v-model:show="showModal"
      :show-icon="false"
      preset="dialog"
      :title="formParams?.id > 0 ? '编辑角色 #' + formParams?.id : '添加角色'"
      style="width: 800px"
    >
      <n-form
        :model="formParams"
        ref="formRef"
        label-placement="left"
        :label-width="80"
        class="py-4"
      >
        <n-form-item label="角色名称" path="name">
          <n-input placeholder="角色名称" v-model:value="formParams.name" />
        </n-form-item>

        <n-form-item label="角色编码" path="key">
          <n-input placeholder="填字母或数字,不能重复" v-model:value="formParams.key" />
        </n-form-item>
        <n-form-item label="备注" path="remark">
          <n-input type="textarea" placeholder="请输入备注内容" v-model:value="formParams.remark" />
        </n-form-item>

        <n-form-item label="排序" path="sort">
          <n-input-number placeholder="请输入排序" v-model:value="formParams.sort" />
        </n-form-item>

        <n-form-item label="状态" path="status">
          <n-radio-group v-model:value="formParams.status" name="status">
            <n-radio-button
              v-for="status in statusOptions"
              :key="status.value"
              :value="status.value"
              :label="status.label"
            />
          </n-radio-group>
        </n-form-item>

        <n-form-item label="系统分配" path="key">
          <n-checkbox-group v-model:value="formSystems" @update:value="handleUpdateValue">
            <n-space item-style="display: flex;">
              <n-checkbox
                v-for="item in systems"
                :key="item.id"
                :value="item.id"
                :label="item.name"
              />
            </n-space>
          </n-checkbox-group>
        </n-form-item>

        <n-card title="权限分配">
          <n-tabs animated type="card" v-model:value="activeTab">
            <n-tab-pane
              v-for="item in activeTabPanes"
              :key="item.id"
              :name="item.id"
              :tab="item.name || item.id"
            >
              <n-form-item label="权限分配">
                <div class="checkbox-group-wrapper">
                  <n-space vertical>
                    <n-checkbox
                      :indeterminate="isIndeterminate(item.id)"
                      :checked="isAllChecked(item.id)"
                      @update:checked="(checked) => handleCheckAll(checked, item.id)"
                    >
                      全选
                    </n-checkbox>
                    <n-checkbox-group
                      v-model:value="permissions[item.id]"
                      @update:value="(newValue) => handlePermissionsUpdateValue(newValue, item.id)"
                    >
                      <n-space
                        item-style="display: flex;"
                        align="center"
                        class="checkbox-container"
                      >
                        <n-checkbox
                          v-for="option in optionsPermissions"
                          :key="option.value"
                          :value="option.value"
                          :label="option.label"
                        />
                      </n-space>
                    </n-checkbox-group>
                  </n-space>
                </div>
              </n-form-item>

              <!--              <n-form-item label="权限分配">
                <n-select
                  multiple
                  v-model:value="formParams.permissions[item.id]"
                  :options="optionsPermissions"
                  @update:value="(newValue) => handlePermissionsUpdateValue(newValue, item.id)"
                />
              </n-form-item>-->

              <n-form-item label="页面分配">
                <n-tree-select
                  multiple
                  cascade
                  checkable
                  v-model:value="formParams.pages[item.id]"
                  :options="optionsPages[item.id]"
                  @update:value="(newValue) => handlePagesUpdateValue(newValue, item.id)"
                />
              </n-form-item>
            </n-tab-pane>
          </n-tabs>
        </n-card>
      </n-form>

      <template #action>
        <n-space>
          <n-button @click="() => (showModal = false)">取消</n-button>
          <n-button type="info" :loading="formBtnLoading" @click="confirmForm">确定</n-button>
        </n-space>
      </template>
    </n-modal>
  </div>
</template>

<script lang="ts" setup>
  import { reactive, ref, h, onMounted, computed } from 'vue';
  import { useMessage } from 'naive-ui';
  import { BasicTable, TableAction } from '@/components/Table';
  import { getRoleList, RoleAuthOption, RoleEdit, RolePageOption } from '@/api/system/role';
  import { columns } from './columns';
  import { PlusOutlined } from '@vicons/antd';
  import { cloneDeep } from 'lodash-es';
  import { statusOptions } from '@/enums/optionsiEnum';
  import { GetServiceList } from '@/api/service/service';

  const formRef: any = ref(null);
  const message = useMessage();
  const actionRef = ref();
  const showModal = ref(false);
  const formBtnLoading = ref(false);
  const formParams = ref<any>();
  const optionsPermissions = ref<any>();
  const optionsPages = ref<any>();

  // 当前激活的tab
  const activeTab = ref<number>(0);

  type SystemTab = {
    id: number;
    name: string;
  };

  const systems = ref<SystemTab[]>([]);

  // 根据选中的checkbox生成active的tab panes
  const activeTabPanes = computed(() => {
    if (!formSystems.value) {
      formSystems.value = [];
    }
    return systems.value.filter((tab) => formSystems.value.includes(tab.id));
  });

  const selectSystem = ref<any>([]);

  function handleUpdateValue(values) {
    // 找出新增的选项
    const added = values.filter((item) => !selectSystem.value.includes(item));
    // 如果有新增的tab，默认激活第一个新增的tab
    if (added.length > 0) {
      activeTab.value = added[0];
      added.forEach((item) => {
        pages.value[item] = formParams.value.pages[item] || [];
        permissions.value[item] = formParams.value.permissions[item] || [];
      });
    }
    // 如果当前激活的tab被移除了，则激活第一个可用的tab
    else if (!values.includes(activeTab.value)) {
      activeTab.value = values[0] || null;
    }
    for (let valueKey in pages.value) {
      if (!values.includes(Number(valueKey))) {
        delete pages.value[valueKey];
      }
    }
    for (let valueKey in permissions.value) {
      if (!values.includes(Number(valueKey))) {
        delete permissions.value[valueKey];
      }
    }
    selectSystem.value = values;
  }

  const pages = ref<object>({});
  const permissions = ref<object>({});
  const formSystems = ref<any>([]);

  // 检查是否全部选中
  const isAllChecked = (id) => {
    return permissions.value[id]?.length === optionsPermissions.value.length;
  };

  // 检查是否是部分选中（不确定状态）
  const isIndeterminate = (id) => {
    const selectedCount = permissions.value[id]?.length || 0;
    return selectedCount > 0 && selectedCount < optionsPermissions.value.length;
  };

  // 处理全选/全不选
  const handleCheckAll = (checked, sysId) => {
    if (checked) {
      permissions.value[sysId] = optionsPermissions.value.map((opt) => opt.value);
      // formParams.value.permissions[sysId] = optionsPermissions.value.map((opt) => opt.value);
    } else {
      permissions.value[sysId] = [];
    }
  };

  function handlePermissionsUpdateValue(val: any, sysId: number) {
    permissions.value[sysId] = val;
  }

  function handlePagesUpdateValue(val: any, sysId: number) {
    pages.value[sysId] = val;
  }

  const defaultState = {
    id: 0,
    key: '',
    name: '',
    permissions: [],
    pages: [],
    remark: '',
    sort: 0,
    status: 1,
  };

  const actionColumn = reactive({
    width: 200,
    title: '操作',
    key: 'action',
    fixed: 'right',
    render(record) {
      return h(TableAction, {
        style: 'button',
        actions: [
          {
            label: '编辑',
            onClick: handleEdit.bind(null, record),
            ifShow: function () {
              return record.id > 1;
            },
          },
          // {
          //   label: '删除',
          //   onClick: handleDelete.bind(null, record),
          // },
        ],
      });
    },
  });

  const loadDataTable = async (_res: any) => {
    return await getRoleList();
  };

  function addTable() {
    showModal.value = true;
    formParams.value = cloneDeep(defaultState);
  }

  function onCheckedRow(rowKeys: any[]) {
    console.log(rowKeys);
  }

  function reloadTable() {
    actionRef.value.reload();
  }

  function confirmForm(e: any) {
    formParams.value.systems = formSystems.value;
    formParams.value.permissions = permissions.value;
    formParams.value.pages = pages.value;
    e.preventDefault();
    formBtnLoading.value = true;
    formRef.value.validate((errors) => {
      if (!errors) {
        RoleEdit(formParams.value)
          .then((_res) => {
            message.success('操作成功');
            setTimeout(() => {
              showModal.value = false;
              reloadTable();
            });
          })
          .catch((e: Error) => {
            message.error(e.message ?? '操作失败');
          });
      } else {
        message.error('请填写完整信息');
      }
      formBtnLoading.value = false;
    });
  }

  function handleEdit(record: Recordable) {
    showModal.value = true;
    formParams.value = cloneDeep(record);
    pages.value = record.pages;
    permissions.value = record.permissions;
    formSystems.value = record.systems;
    selectSystem.value = record.systems;
    activeTab.value = record.systems[0];
  }

  function handleDelete(record: Recordable) {
    console.log('点击了删除', record);
    message.info('点击了删除');
  }

  onMounted(async () => {
    optionsPermissions.value = await RoleAuthOption();
    optionsPages.value = await RolePageOption();
    systems.value = await GetServiceList();
  });
</script>

<style lang="less" scoped>
  .checkbox-group-wrapper {
    border: 1px solid #eee;
    padding: 12px;
    border-radius: 3px;
  }

  .checkbox-container {
    max-height: 300px; /* 设置最大高度 */
    overflow-y: auto; /* 超出时显示垂直滚动条 */
    padding-right: 8px; /* 为滚动条留出空间 */
    display: flex;
    flex-direction: column;
    gap: 8px; /* 设置选项之间的间距 */
  }

  /* 滚动条样式 */
  .checkbox-container::-webkit-scrollbar {
    width: 6px;
  }
  .checkbox-container::-webkit-scrollbar-thumb {
    background-color: #d9d9d9;
    border-radius: 3px;
  }
  .checkbox-container::-webkit-scrollbar-thumb:hover {
    background-color: #c1c1c1;
  }
</style>
