<template>
  <div class="select-group-container">
    <el-form :model="ruleForm" ref="ruleFormRef">
      <el-form-item
        label="选择分组"
        prop="userGroupList"
        :rules="[{ required: true, message: '请选择分组' }]"
        class="user-group-list"
      >
        <el-select
          v-model="ruleForm.userGroupList"
          multiple
          placeholder="请选择分组"
          filterable
          @change="emits('userGroupListChange', ruleForm.userGroupList)"
        >
          <el-option v-for="item in groupOptions" :key="item.id" :value="item.id" :label="item.name" />
        </el-select>
        <span @click="showGroupInfo" v-if="ruleForm.userGroupList.length > 0" class="group-info-span"> 人员详情 </span>
      </el-form-item>
    </el-form>
    <el-dialog
      v-model="groupInfo"
      title="人员详情"
      align-center
      :close-on-click-modal="false"
      :destroy-on-close="true"
      class="customDialog--pushObject"
    >
      <Group :userGroupInfo="userGroupInfo" />
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
  import { ref, reactive, watch } from 'vue';
  import type { FormInstance } from 'element-plus';
  import type { GroupOptionType } from '@/views/disaster/types';
  import type { UserGroupInfo } from '@/types/push-object';
  import { queryUserGroupDetailByIds } from '@/api/push-object';
  import Group from './Group.vue';
  const props = defineProps<{
    userGroupList: number[];
  }>();
  interface RuleForm {
    userGroupList: number[];
  }
  const groupOptions = ref<GroupOptionType[]>([
    {
      id: 1,
      name: '测试1',
    },
    {
      id: 2,
      name: '测试2',
    },
  ]);
  const ruleFormRef = ref<FormInstance>();
  const ruleForm = reactive<RuleForm>({
    userGroupList: [],
  });
  const groupInfo = ref(false);
  const showGroupInfo = () => {
    groupInfo.value = true;
    getUserGroupInfo();
  };
  const userGroupInfo = ref<UserGroupInfo[]>([]);
  const getUserGroupInfo = async () => {
    const res = await queryUserGroupDetailByIds(ruleForm.userGroupList);
    userGroupInfo.value = res.map((item) => ({
      ...item,
      isExpand: false,
      isHidden: false,
    }));
  };
  const emits = defineEmits<{
    (e: 'userGroupListChange', userGroupList: number[]): void;
  }>();
  const validateForm = () => {
    return new Promise((resolve) => {
      ruleFormRef.value?.validate((valid) => {
        resolve(valid);
      });
    });
  };
  defineExpose({
    validateForm,
  });
  watch(
    () => props.userGroupList,
    (newUserGroupList) => {
      ruleForm.userGroupList = newUserGroupList ?? [];
    },
    { immediate: true },
  );
</script>

<style lang="scss" scoped>
  .select-group-container {
    width: 100%;
  }
  .user-group-list {
    position: relative;
  }
  .group-info-span {
    position: absolute;
    left: 0;
    bottom: -30px;
    cursor: pointer;
    font-size: 10cpx;
    color: $primary-color;
  }
</style>
