<template>
  <Dialog draggable custom-show :title="groupForm.group_id ? '编辑分组' : '添加分组'" type="xs" height="auto" hide-footer @close="handleClose">
    <div class="form-item">
      <div class="text1">分组名称</div>
      <el-input v-model="groupForm.group_name" class="custom-input" placeholder="请输入" />
    </div>
    <div class="form-action">
      <div v-if="!groupForm.group_id" class="common-btn-primary" @click="handleAddGroup">保存</div>
      <div v-else class="common-btn-primary" @click="handleUpdateGroup">保存</div>
      <div v-if="groupForm.group_id" class="common-btn-primary" @click="handleDeleteGroup">删除</div>
      <div class="common-btn" @click="handleClose">取消</div>
    </div>
  </Dialog>
</template>

<script lang="ts" setup>
import { addGroup, delGroup, getGroupInfo, updateGroup } from '@/api/globalMap/onlinePlotting';
import { showSuccessMsg } from '@/utils/notification';

const props = defineProps({
  modelValue: Boolean,
  patternId: String,
  groupId: String
});
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const emits = defineEmits(['update:modelValue', 'change']);
let groupForm = ref({
  group_id: '',
  group_name: ''
});
watch(
  () => props.groupId,
  () => {
    if (!!props.groupId) {
      // 获取详情
      getGroupInfo(props.groupId).then((res) => {
        groupForm.value = res.data;
      });
    }
  },
  {
    immediate: true
  }
);
// 新增分组
const handleAddGroup = () => {
  const obj = {
    group_name: groupForm.value.group_name,
    pattern_id: props.patternId
  };
  addGroup(obj).then(() => {
    emits('change');
    showSuccessMsg('新增成功');
    handleClose();
  });
};
// 修改分组
const handleUpdateGroup = () => {
  updateGroup(groupForm.value).then(() => {
    emits('change');
    showSuccessMsg('修改成功');
    handleClose();
  });
};
// 关闭弹窗
const handleClose = () => {
  emits('update:modelValue', false);
};
// 删除分组
const handleDeleteGroup = async () => {
  await proxy?.$modal.confirm('您确定要删除该分组?');
  delGroup(groupForm.value.group_id).then(() => {
    showSuccessMsg('删除成功');
    emits('change');
    handleClose();
  });
};
</script>

<style lang="scss" scoped>
.form-item {
  display: flex;
  align-items: center;
  .text1 {
    flex-shrink: 0;
    margin-right: 10px;
  }
  .custom-input {
    flex: 1;
  }
}
.form-action {
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
