<template>
  <div>
    <div class="n-layout-page-header">
      <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="editRoleTitle">
      <div class="py-3 menu-list">
        <n-tree
          block-line
          cascade
          checkable
          :virtual-scroll="true"
          :data="treeData"
          :expandedKeys="expandedKeys"
          :checked-keys="checkedKeys"
          style="max-height: 950px; overflow: hidden"
          @update:checked-keys="checkedTree"
          @update:expanded-keys="onExpandedKeys"
        />
      </div>
      <template #action>
        <n-space>
          <n-button type="info" ghost icon-placement="left" @click="packHandle">
            全部{{ expandedKeys.length ? '收起' : '展开' }}
          </n-button>

          <n-button type="info" ghost icon-placement="left" @click="checkedAllHandle">
            全部{{ checkedAll ? '取消' : '选择' }}
          </n-button>
          <n-button type="primary" :loading="formBtnLoading" @click="confirmForm">提交</n-button>
        </n-space>
      </template>
    </n-modal>

    <n-modal v-model:show="showModal2" :show-icon="false" preset="dialog" title="添加角色">
      <n-form
        :model="formParams"
        :rules="rules"
        ref="formRef"
        label-placement="left"
        :label-width="80"
        class="py-4"
      >
        <n-form-item label="上级角色" path="pid">
          <n-input placeholder="请输入上级角色ID" v-model:value="formParams.pid" />
        </n-form-item>
        <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="sort">
          <n-input-number v-model:value="formParams.sort" clearable />
        </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="remark">
          <n-input type="textarea" placeholder="请输入" v-model:value="formParams.remark" />
        </n-form-item>
      </n-form>

      <template #action>
        <n-space>
          <n-button @click="() => (showModal2 = false)">取消</n-button>
          <n-button type="info" :loading="formBtnLoading2" @click="confirmForm2">确定</n-button>
        </n-space>
      </template>
    </n-modal>

    <n-modal
      v-model:show="showDataModal"
      :show-icon="false"
      preset="dialog"
      :title="'修改 ' + dataForm?.name + ' 的数据权限'"
    >
      <n-form
        :model="dataForm"
        ref="dataFormRef"
        label-placement="left"
        :label-width="120"
        class="py-4"
      >
        <n-form-item label="数据范围" path="dataScope">
          <n-select
            v-model:value="dataForm.dataScope"
            :options="dataScopeOption"
            @update:value="handleUpdateDataScopeValue"
          />
        </n-form-item>
        <n-form-item label="自定义权限" path="customDept" v-if="dataForm.dataScope === 4">
          <n-tree-select
            multiple
            :options="deptList"
            :default-value="dataForm.customDept"
            :default-expand-all="true"
            @update:value="handleUpdateDeptValue"
          />
        </n-form-item>
      </n-form>

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

<script lang="ts" setup>
  import { h, onMounted, reactive, ref } from 'vue';
  import { TreeSelectOption, useDialog, useMessage, SelectOption } from 'naive-ui';
  import { BasicTable, TableAction } from '@/components/Table';
  import {
    Delete,
    Edit,
    GetPermissions,
    getRoleList,
    UpdatePermissions,
    DataScopeSelect,
    DataScopeEdit,
  } from '@/api/system/role';
  import { getMenuList } from '@/api/system/menu';
  import { columns } from './columns';
  import { PlusOutlined } from '@vicons/antd';
  import { getTreeAll } from '@/utils';
  import { statusOptions } from '@/enums/optionsiEnum';
  import { cloneDeep } from 'lodash-es';
  import { getDeptList } from '@/api/org/dept';

  const formRef: any = ref(null);
  const message = useMessage();
  const actionRef = ref();
  const dialog = useDialog();
  const showModal2 = ref(false);
  const showModal = ref(false);
  const formBtnLoading = ref(false);
  const formBtnLoading2 = ref(false);
  const checkedAll = ref<any>(false);
  const editRoleTitle = ref('');
  const treeData = ref([]);
  const expandedKeys = ref([]);
  const checkedKeys = ref<any>([]);
  const updatePermissionsParams = ref<any>({});

  const rules = {
    name: {
      required: true,
      trigger: ['blur', 'input'],
      message: '请输入名称',
    },
    key: {
      required: true,
      trigger: ['blur', 'input'],
      message: '请输入角色编码',
    },
  };

  const defaultState = {
    id: 0,
    pid: 0,
    level: 1,
    tree: '',
    name: '',
    key: '',
    remark: null,
    status: 1,
    sort: 0,
    dataScope: 1,
    customDept: [],
  };

  let formParams = ref<any>(cloneDeep(defaultState));

  const actionColumn = reactive({
    width: 320,
    title: '操作',
    key: 'action',
    fixed: 'right',
    render(record) {
      return h(TableAction, {
        style: 'primary',
        actions: [
          {
            label: '菜单权限',
            onClick: handleMenuAuth.bind(null, record),
            ifShow: () => {
              return record.key !== 'super';
            },
          },
          {
            label: '数据权限',
            onClick: handleDataAuth.bind(null, record),
            ifShow: () => {
              return record.key !== 'super';
            },
          },
          {
            label: '编辑',
            onClick: handleEdit.bind(null, record),
            ifShow: () => {
              return record.key !== 'super';
            },
          },
          {
            label: '删除',
            onClick: handleDelete.bind(null, record),
            ifShow: () => {
              return record.key !== 'super';
            },
          },
        ],
      });
    },
  });

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

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

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

  function confirmForm(e: any) {
    e.preventDefault();
    formBtnLoading.value = true;
    UpdatePermissions({
      ...{
        id: updatePermissionsParams.value.id,
        menuIds:
          checkedKeys.value === undefined || checkedKeys.value == null ? [] : checkedKeys.value,
      },
    }).then((_res) => {
      message.success('操作成功');
      reloadTable();
      showModal.value = false;
      formBtnLoading.value = false;
    });
  }

  function confirmForm2(e) {
    e.preventDefault();
    formBtnLoading2.value = true;
    formRef.value.validate((errors) => {
      if (!errors) {
        Edit(formParams.value).then((_res) => {
          message.success('操作成功');
          setTimeout(() => {
            showModal2.value = false;
            reloadTable();
          });
        });
      } else {
        message.error('请填写完整信息');
      }
      formBtnLoading2.value = false;
    });
  }

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

  function handleEdit(record: Recordable) {
    showModal2.value = true;
    formParams.value = cloneDeep(record);
  }

  function handleDelete(record: Recordable) {
    dialog.warning({
      title: '警告',
      content: '你确定要删除？',
      positiveText: '确定',
      negativeText: '取消',
      onPositiveClick: () => {
        Delete(record).then((_res) => {
          message.success('操作成功');
          reloadTable();
        });
      },
      onNegativeClick: () => {
        // message.error('取消');
      },
    });
  }

  async function handleMenuAuth(record: Recordable) {
    editRoleTitle.value = `分配 ${record.name} 的菜单权限`;
    const data = await GetPermissions({ ...{ id: record.id } });
    checkedKeys.value = data.menuIds; //record.menu_keys;
    updatePermissionsParams.value.id = record.id;
    showModal.value = true;
  }

  const dataScopeOption = ref<any>();
  const deptList = ref<any>([]);
  const dataFormRef = ref<any>();
  const dataFormBtnLoading = ref(false);
  const showDataModal = ref(false);
  const dataForm = ref<any>();
  function handleDataAuth(record: Recordable) {
    dataForm.value = cloneDeep(record);
    showDataModal.value = true;
  }

  function handleUpdateDataScopeValue(value: string, option: SelectOption) {}

  function handleUpdateDeptValue(
    value: string | number | Array<string | number> | null,
    _option: TreeSelectOption | null | Array<TreeSelectOption | null>
  ) {
    dataForm.value.customDept = value;
  }

  function confirmDataForm(e) {
    e.preventDefault();
    dataFormBtnLoading.value = true;
    dataFormRef.value.validate((errors) => {
      if (!errors) {
        console.log('dataForm.value:' + JSON.stringify(dataForm.value));
        DataScopeEdit(dataForm.value).then((_res) => {
          message.success('操作成功');
          setTimeout(() => {
            showDataModal.value = false;
            reloadTable();
          });
        });
      } else {
        message.error('请填写完整信息');
      }
      dataFormBtnLoading.value = false;
    });
  }

  function checkedTree(keys) {
    checkedKeys.value = keys;
  }

  function onExpandedKeys(keys) {
    expandedKeys.value = keys;
  }

  function packHandle() {
    if (expandedKeys.value.length) {
      expandedKeys.value = [];
    } else {
      expandedKeys.value = treeData.value.map((item: any) => item.key) as [];
    }
  }

  function checkedAllHandle() {
    if (!checkedAll.value) {
      checkedKeys.value = getTreeAll(treeData.value);
      checkedAll.value = true;
    } else {
      checkedKeys.value = [];
      checkedAll.value = false;
    }
  }

  onMounted(async () => {
    await loadMenuList();
    await loadDeptList();
    await loadDataScopeSelect();
  });

  async function loadMenuList() {
    const treeMenuList = await getMenuList();
    expandedKeys.value = treeMenuList.list.map((item) => item.key);
    treeData.value = treeMenuList.list;
  }

  async function loadDeptList() {
    deptList.value = await getDeptList({});
    if (deptList.value === undefined || deptList.value === null) {
      deptList.value = [];
    }
  }

  async function loadDataScopeSelect() {
    const option = await DataScopeSelect();
    dataScopeOption.value = option.list;
  }
</script>

<style lang="less" scoped></style>
