<template>
  <div>
    <BasicTable @register="registerTable" :searchInfo="searchInfo">
      <template #toolbar>
        <PermissionBtn @btn-event="onBtnClicked" />
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <TableAction
            :actions="[
              {
                // icon: 'ant-design:ellipsis-outlined',
                label: '查看',
                onClick: viewAccount.bind(null, record),
              },
            ]"
          />
        </template>
      </template>
    </BasicTable>
    <RoleModal @register="registerModal" @success="handleSuccess" />
    <AccountModal @register="registerAccountModal" @success="handleSuccess" />
    <a-modal
      width="60%"
      v-model:open="accountOpen"
      wrap-class-name="full-modal-children"
      title="分配组员"
      @ok="accountHandleOk"
      :destroyOnClose="true"
    >
      <SelectAccount ref="accountRef" :selectListValue="groupList" />
    </a-modal>
  </div>
</template>
<script lang="ts" setup>
  import { reactive, ref } from 'vue';

  import { BasicTable, useTable, TableAction } from '@/components/Table';
  import {
    getLoadGroupList,
    deleteGroup,
    assignGroupUser,
    getLoadUserListByGroupid,
  } from '@/api/demo/system';

  import { useMessage } from '@/hooks/web/useMessage';
  import { useModal } from '@/components/Modal';
  import { RoleModal, AccountModal } from './page';
  import { PermissionBtn } from '@/components/PermissionBtn/index';
  import { SelectAccount } from '@/components/SelectAccount';
  import { columns, searchFormSchema } from './role.data';

  defineOptions({ name: 'RoleManagement' });

  const { createConfirm, createMessage } = useMessage();
  const [registerModal, { openModal: openRoleModal }] = useModal();
  const [registerAccountModal, { openModal: openAccountModal }] = useModal();
  const searchInfo = reactive<Recordable>({});
  const groupList = ref([]);
  const [registerTable, { reload, getSelectRows, clearSelectedRowKeys }] = useTable({
    // 表格名称
    title: '组列表',
    // 获取数据的接口
    api: getLoadGroupList,
    // 表单列信息 BasicColumn[]
    columns,
    rowKey: 'id',
    formConfig: {
      labelWidth: 120,
      schemas: searchFormSchema,
    },
    // 使用搜索表单
    useSearchForm: true,
    // 显示表格设置工具
    showTableSetting: true,
    // 是否显示表格边框
    bordered: true,
    // 序号列
    showIndexColumn: false,
    // 勾选列
    rowSelection: {
      //多选框
      // type: 'checkbox',
      type: 'radio',
    },
    // 搜索
    handleSearchInfoFn(info) {
      return info;
    },
    actionColumn: {
      width: 80,
      title: '查看组员',
      dataIndex: 'action',
      // slots: { customRender: 'action' },
      fixed: undefined,
    },
  });
  const accountOpen = ref(false);
  const groupId = ref('');
  function handleCreate() {
    openRoleModal(true, {
      isUpdate: false,
    });
  }
  function viewAccount(record: Recordable) {
    openAccountModal(true, {
      record,
    });
  }

  function handleEdit() {
    let rows = getSelectRows();
    if (rows.length == 0) {
      return createMessage.warn('请勾选一个组进行编辑');
    }
    const record = rows[0];
    openRoleModal(true, {
      record,
      isUpdate: true,
    });
  }

  async function handleDelete() {
    let rows = getSelectRows();
    if (rows.length == 0) {
      return createMessage.warn('请勾选一个组进行删除');
    }
    createConfirm({
      iconType: 'info',
      title: '删除',
      content: '确定要删除当前组吗',
      onOk: async () => {
        const data = await deleteGroup(rows[0].id);
        if (data) {
          handleSuccess();
          createMessage.success('删除成功');
        } else {
          createMessage.error('删除失败');
        }
      },
    });
  }

  function handleSuccess() {
    clearSelectedRowKeys();
    reload();
  }
  function onBtnClicked(domId) {
    switch (domId) {
      case 'btnAdd':
        handleCreate();
        break;
      case 'btnEdit':
        handleEdit();
        break;
      case 'btnDelete':
        handleDelete();
        break;
      case 'btnAccounts':
        handleAccount();
        break;
      default:
        break;
    }
  }
  async function handleAccount() {
    let rows = getSelectRows();
    if (rows.length == 0) {
      return createMessage.warn('请勾选一个组进行编辑');
    }
    groupId.value = rows[0].id;
    accountOpen.value = true;
    const data = await getLoadUserListByGroupid({
      groupid: groupId.value,
      page: 1,
      limit: 99999,
    });
    groupList.value = data.items.map((item) => item.id);
  }
  const accountRef = ref<any>();
  async function accountHandleOk() {
    const list = accountRef.value.getRow();
    if (list.length > 0) {
      let selectData = accountRef.value.getRow().map((t) => {
        return t.id;
      });
      const query = {
        groupId: groupId.value,
        userIds: selectData,
      };
      const data = await assignGroupUser(query);
      if (data) {
        createMessage.success('分配成功');
        accountOpen.value = false;
      } else {
        return createMessage.error('分配失败');
      }
    } else {
      return createMessage.error('请选择至少一个组员');
    }
  }
</script>
