<template>
  <!--引用表格-->
  <BasicTable @register="registerTable" :rowSelection="rowSelection">
    <!--插槽:table标题-->
    <template #tableTitle>
      <c-button
        v-show="hasPermission('system:departUser:addRole')"
        type="primary"
        preIcon="ant-design:plus-outlined"
        @click="addDepartRole"
      >
        添加部门角色
      </c-button>
      <template v-if="selectedRowKeys.length > 0">
        <Dropdown>
          <template #overlay>
            <Menu>
              <MenuItem v-if="hasPermission('system:departUser:deleteBatch')" key="1" @click="onDeleteDepartRoleBatch">
                <Icon icon="ant-design:delete-outlined" />
                <span>删除</span>
              </MenuItem>
            </Menu>
          </template>
          <c-button>
            <span>批量操作 </span>
            <Icon icon="akar-icons:chevron-down" />
          </c-button>
        </Dropdown>
      </template>
    </template>
    <!-- 插槽：行内操作按钮 -->
    <template #action="{ record }">
      <TableAction :actions="getTableAction(record)" />
    </template>
  </BasicTable>
  <!-- 添加部门弹窗 -->
  <DepartRoleModal :departId="departId" @register="registerFormModal" @success="onFormModalSuccess" />
  <!--功能、数据权限配置-->
  <RoleDataConfigDrawer @register="roleDataConfigDrawer" />
</template>

<script lang="ts" setup>
  import { computed, watch, onMounted, unref } from 'vue';
  import { ActionItem, BasicTable, TableAction, useModal, useDrawer, useListPage, ColEx } from '@jdlinker/ui';
  import DepartRoleModal from './DepartRoleModal.vue';
  import { deleteBatchDepartRole, departRoleList } from '../depart.user.api';
  import { departRoleColumns, departRoleSearchFormSchema } from '../depart.user.data';
  import { usePermission } from '@jdlinker/func';
  import RoleDataConfigDrawer from '../../components/RoleDataConfigDrawer.vue';
  import { Dropdown, Menu, MenuItem } from 'ant-design-vue';

  const [roleDataConfigDrawer, { openDrawer: openRoleDataConfigDrawer }] = useDrawer();
  const { hasPermission } = usePermission();
  const props = defineProps({
    data: { require: true, type: Object }
  });
  defineEmits(['register']);
  // 当前选中的部门ID，可能会为空，代表未选择部门
  // @ts-ignore
  const departId = computed(() => props.data?.id);

  // 自适应列配置
  const adaptiveColProps: Partial<ColEx> = {
    xs: 24, // <576px
    sm: 24, // ≥576px
    md: 24, // ≥768px
    lg: 12, // ≥992px
    xl: 8, // ≥1200px
    xxl: 8 // ≥1600px
  };
  // 列表页面公共参数、方法
  const { tableContext, createMessage } = useListPage({
    tableProps: {
      api: departRoleList,
      columns: departRoleColumns,
      formConfig: {
        schemas: departRoleSearchFormSchema,
        baseColProps: adaptiveColProps,
        // 操作按钮配置
        actionColOptions: {
          style: { paddingLeft: '0px', paddingRight: '0px' }
        }
      },
      // 请求之前对参数做处理
      beforeFetch(params) {
        params.deptId = departId.value;
      }
    }
  });

  // 注册 ListTable
  const [registerTable, { reload, setLoading, updateTableDataRecord }, { rowSelection, selectedRowKeys }] = tableContext;

  // 注册Form弹窗
  const [registerFormModal, formModal] = useModal();

  // 监听 data 更改，重新加载数据
  watch(
    () => props.data,
    () => reload()
  );
  onMounted(() => {
    reload();
  });

  // 清空选择的行
  function clearSelection() {
    selectedRowKeys.value = [];
  }

  // 添加部门角色
  function addDepartRole() {
    formModal.openModal(true, {
      isUpdate: false,
      record: {}
    });
  }

  // 编辑部门角色
  function editDepartRole(record) {
    formModal.openModal(true, {
      isUpdate: true,
      record: record
    });
  }

  // 授权部门角色
  function permissionDepartRole(record) {
    openRoleDataConfigDrawer(true, { departRoleId: record.id, departId: record.departId, type: '3' });
  }

  // 批量删除部门角色
  async function deleteDepartRole(idList, confirm) {
    if (!departId.value) {
      createMessage.warning('请先选择一个部门');
    } else {
      setLoading(true);
      let ids = unref(idList).join(',');
      try {
        await deleteBatchDepartRole({ ids }, confirm);
        return reload();
      } finally {
        setLoading(false);
      }
    }
    return Promise.reject();
  }

  // 批量删除部门角色事件
  async function onDeleteDepartRoleBatch() {
    try {
      await deleteDepartRole(selectedRowKeys, true);
      // 批量删除成功后清空选择
      clearSelection();
    } catch (e) {}
  }

  // 表单弹窗成功后的回调
  function onFormModalSuccess({ isUpdate, values }) {
    isUpdate ? updateTableDataRecord(values.id, values) : reload();
  }

  /**
   * 操作栏
   */
  function getTableAction(record): ActionItem[] {
    return [
      {
        icon: 'clarity:note-edit-line',
        tooltip: '编辑',
        onClick: editDepartRole.bind(null, record),
        ifShow: () => hasPermission('system:departUser:editRole')
      },
      {
        icon: 'ant-design:appstore-add-outlined',
        tooltip: '授权',
        onClick: permissionDepartRole.bind(null, record),
        ifShow: () => hasPermission('system:departUser:authRole')
      },
      {
        icon: 'ant-design:delete-outlined',
        tooltip: '删除',
        color: 'error',
        popConfirm: {
          title: '确认要删除吗？',
          placement: 'left',
          confirm: deleteDepartRole.bind(null, [record.id], false)
        },
        ifShow: () => hasPermission('system:departUser:deleteRole')
      }
    ];
  }
</script>
