<template>
  <el-container>
    <el-main>
      <el-form :model="form.model" :rules="form.rules" ref="formRef" :label-width="formLabelWidth">
        <el-form-item :label="t('dataReport.dashboardName')" prop="name">
          <el-input v-model="form.model.name" :placeholder="t('dataReport.enterDashboardName')"></el-input>
        </el-form-item>
      </el-form>
    </el-main>
    <el-footer class="sa-footer--submit">
      <el-button v-if="modal.params.type == 'add'" type="primary" @click="confirm">
        {{ t('common.save') }}
      </el-button>
      <el-button v-if="modal.params.type == 'edit'" type="primary" @click="confirm">
        {{ t('common.update') }}
      </el-button>
    </el-footer>
  </el-container>
</template>

<script setup>
import { cloneDeep } from 'lodash';
import { onMounted, reactive, ref, unref } from 'vue';
import { ElMessage } from 'element-plus';
import { useI18n } from 'vue-i18n';
import { useFormConfig } from '@/hooks/useFormConfig';
import { api } from '../../data.service.js';

// 使用国际化
const { t } = useI18n();

// 使用表单配置hooks
const { formLabelWidth } = useFormConfig({ enWidth: '140px' });

const emit = defineEmits(['modalCallBack']);
const props = defineProps({
  modal: {
    type: Object,
  },
});

// 添加 编辑 form
let formRef = ref(null);
const form = reactive({
  model: {
    name: '',
  },
  get rules() {
    return {
      name: [
        { required: true, message: t('dataReport.enterDashboardName'), trigger: 'blur' },
        { min: 2, max: 50, message: t('dataReport.dashboardNameLength'), trigger: 'blur' }
      ]
    };
  },
});
const loading = ref(false);

// 获取详情
async function getDetail(id) {
  loading.value = true;
  const { code, data } = await api.report.spectaculars.detail({ id });
  code === '200' && (form.model = data);
  loading.value = false;
}

// 表单关闭时提交
async function confirm() {
  unref(formRef).validate(async (valid) => {
    if (!valid) return;
    let submitForm = cloneDeep(form.model);
    const { code } =
      props.modal.params.type == 'add'
        ? await api.report.spectaculars.add(submitForm)
        : await api.report.spectaculars.update(submitForm);
    if (code == '200') {
      ElMessage.success(t('message.saveSuccess'));
      emit('modalCallBack', { event: 'confirm' });
    }
  });
}

async function init() {
  if (props.modal.params.id) {
    await getDetail(props.modal.params.id);
  }
}

onMounted(() => {
  init();
});
</script>

<style scoped>
.sa-footer--submit {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 16px 24px;
  border-top: 1px solid #e4e7ed;
  background: #fafafa;
}
</style>