<template>
  <vxe-modal
    resize
    v-model="showModal"
    @hide="onHide"
    title="分配成员"
    width="900px"
    show-maximize
    show-footer
    esc-closable
  >
    <div class="mb-1">
      <el-button type="primary" @click="userModalRef?.openModal">新增成员</el-button>
      <el-button type="danger" @click="handleRemove">删除成员</el-button>
    </div>
    <vxe-table ref="xTable" :data="tableData">
      <vxe-column type="checkbox" width="50" />
      <vxe-column field="username" title="用户账号" minWidth="120" />
      <vxe-column field="status" title="状态" width="120">
        <template #default="{ row }">
          <el-tag :type="row.status == 'enable' ? 'primary' : 'danger'">{{
            row.status == 'enable' ? '启用' : '禁用'
          }}</el-tag>
        </template>
      </vxe-column>
    </vxe-table>
    <template #footer>
      <el-button type="default" @click="showModal = false">取消</el-button>
      <el-button :loading="loading" type="primary" @click="submitForm">提交</el-button>
    </template>
  </vxe-modal>

  <UserModal ref="userModalRef" @confirm="hanldeConfirm" />
</template>

<script setup name="AllocationUserModal">
  import { ref } from 'vue';
  import { ElMessage } from 'element-plus';
  import { saveRole } from '@/api/role';
  import UserModal from '@/components/CommonModal/UserModal/index.vue';

  const emits = defineEmits(['success']);

  const xTable = ref(null);
  const showModal = ref(false);
  const userModalRef = ref(null);
  const loading = ref(false);
  const tableData = ref([]);
  const currentRole = ref(null);
  const submitForm = async () => {
    try {
      loading.value = true;
      const params = {
        ...currentRole.value,
        users: tableData.value.map((v) => ({ id: v.id })),
      };
      await saveRole(params);
      emits('success');
      ElMessage({
        type: 'success',
        message: '添加成功!',
        plain: true,
      });
      showModal.value = false;
    } catch {}
    loading.value = false;
  };
  const onHide = () => {
    currentRole.value = null;
    tableData.value = [];
  };
  const openModal = (role) => {
    currentRole.value = role;
    tableData.value = role.users;
    showModal.value = true;
  };

  const hanldeConfirm = (rows) => {
    tableData.value.unshift(...rows.filter((row) => !tableData.value.find((v) => v.id == row.id)));
  };
  const handleRemove = () => {
    const checkedList = xTable.value.getCheckboxRecords();
    if (!checkedList.length) {
      return ElMessage({
        type: 'warning',
        message: '请选择有效数据！',
        plain: true,
      });
    }

    tableData.value = tableData.value.filter((row) => !checkedList.find((v) => v.id == row.id));
  };

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