<template>
  <el-drawer :title="title" v-model="drawerOpened" destroy-on-close>
    <div class="drawer-content">
      <div class="export-button-wrapper">
        <el-button class="export-button" type="primary" @click="handleExport">导出分组名单</el-button>
      </div>
      <el-table :data="personList" style="width: 100%" height="600">
        <el-table-column prop="staffNo" label="工号" show-overflow-tooltip />
        <el-table-column prop="realname" label="姓名" show-overflow-tooltip />
        <el-table-column prop="deptName" label="部门" show-overflow-tooltip>
          <template #default="{ row }">
            {{ row.deptName ? row.deptName : '--' }}
          </template>
        </el-table-column>
        <el-table-column prop="jobName" label="岗位" show-overflow-tooltip>
          <template #default="{ row }">
            {{ row.jobName ? row.jobName : '--' }}
          </template>
        </el-table-column>
      </el-table>
    </div>
  </el-drawer>
</template>

<script setup lang="ts">
  import { ref } from 'vue';
  import { ElMessage } from 'element-plus';
  import { downloadByData } from '@/utils/file/download';
  import { PersonGroupItem, PersonGroupListItem } from '@/types/person-group/type';
  import { queryUserGroupDetail, exportUserGroupList } from '@/api/system/person-group';

  defineProps<{
    title: string;
  }>();

  const drawerOpened = ref(false);

  const userGroupId = ref<number>(0);
  const personList = ref<PersonGroupItem[]>([]);

  const open = async (row: PersonGroupListItem) => {
    userGroupId.value = row.id;
    const res = await queryUserGroupDetail(row.id);
    personList.value = res.userList;
    drawerOpened.value = true;
  };

  // 导出
  const handleExport = () => {
    exportUserGroupList(userGroupId.value).then(async (responnse) => {
      if (!responnse) {
        throw new Error('下载文件失败');
      }
      downloadByData(responnse, '导出分组名单.xlsx');
      ElMessage.success('下载文件成功');
    });
  };

  defineExpose({
    open,
  });
</script>

<style lang="scss" scoped>
  .drawer-content {
    display: flex;
    flex-direction: column;
    height: 100%;
  }

  .export-button-wrapper {
    position: sticky;
    top: 0;
    z-index: 10;
    background: #fff;
    margin-bottom: 20px;
    display: flex;
    justify-content: flex-end;
  }

  :deep(.el-table) {
    flex: 1;
    overflow: auto;
  }
</style>
