<template>
  <div class="system-dialog-container">
    <el-dialog
        :title="state.dialog.title"
        v-model="state.dialog.isShowDialog"
        width="450px"
        draggable
        destroy-on-close
        :close-on-click-modal="false"
        align-center>
      <el-form :model="state.ruleForm" label-position="top" ref="formRef" size="default">
        <el-form-item label="分组名称">
          <el-input v-model="state.ruleForm.name" placeholder="如：VIP套餐（可选）" clearable />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="onCancel" size="default">取 消</el-button>
        <el-button :loading="state.btnLoading" type="primary" @click="onSubmit" size="default">{{ state.dialog.submitTxt }}</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="GroupDialog">
import { reactive, ref } from 'vue';
import { Msg } from "/@/utils/message";
import { $body } from "/@/utils/request";
import u from '/@/utils/u'

const emit = defineEmits(['refresh']);
const formRef = ref();

const initState = () => ({
  ruleForm: { id: null as number | null, name: '' },
  btnLoading: false,
  dialog: { isShowDialog: false, type: '', title: '', submitTxt: '' },
})

const state = reactive(initState());

const open = (action: string = 'add', row: any) => {
  state.dialog.title = u.dialog.actions[action].title + "『配置分组』"
  state.dialog.submitTxt = u.dialog.actions[action].btn + "『配置分组』"
  state.dialog.isShowDialog = true;
  if (action !== 'add' && row) {
    state.ruleForm.id = row.id;
    state.ruleForm.name = row.name || '';
  }
};

const onClose = () => {
  state.dialog.isShowDialog = false;
  Object.assign(state, initState());
};
const onCancel = () => onClose();

const onSubmit = () => {
  state.btnLoading = true;
  const url = !!state.ruleForm.id ? "/rechargeConfig/group/modify" : "/rechargeConfig/group/add";
  $body(url, { id: state.ruleForm.id, name: state.ruleForm.name || null, stationIds: [] }).then(() => {
    state.btnLoading = false;
    Msg.message('操作成功');
    onClose();
    emit('refresh');
  }).catch(() => {
    state.btnLoading = false;
    Msg.message('操作失败', 'error');
  });
};

defineExpose({ open });
</script>
