<template>
  <div class="select-group-container">
    <el-form :model="ruleForm" ref="ruleFormRef">
      <el-form-item label="选择分组：" prop="userGroupList" :rules="[{ required: true, message: '请选择分组' }]">
        <GroupSelect
          v-model="ruleForm.userGroupList"
          :groupOptions="groupOptions"
          @change="emits('userGroupListChange', $event)"
        />
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
  import { ref, reactive, watch, onMounted } from 'vue';
  import GroupSelect from './components/GroupSelect.vue';
  import type { FormInstance } from 'element-plus';
  import { useGroupInfoHook } from './hook/groupInfo';

  const props = defineProps<{
    userGroupList: number[];
  }>();

  interface RuleForm {
    userGroupList: number[];
  }

  const { getUserGroupList, groupOptions } = useGroupInfoHook();

  const ruleFormRef = ref<FormInstance>();
  const ruleForm = reactive<RuleForm>({
    userGroupList: [],
  });

  const emits = defineEmits<{
    (e: 'userGroupListChange', userGroupList: number[]): void;
  }>();

  const validateForm = () => {
    return new Promise((resolve) => {
      ruleFormRef.value?.validate((valid) => {
        resolve(valid);
      });
    });
  };

  const clearValidate = () => {
    ruleFormRef.value?.resetFields();
  };

  defineExpose({
    validateForm,
    clearValidate,
  });

  onMounted(() => {
    getUserGroupList();
  });

  watch(
    () => props.userGroupList,
    (newUserGroupList) => {
      ruleForm.userGroupList = newUserGroupList ?? [];
    },
    { immediate: true },
  );
</script>

<style lang="scss" scoped>
  .select-group-container {
    width: 100%;
  }
</style>
