<template>
  <el-container>
    <el-main>
      <el-form :model="form.model" :rules="form.rules" ref="formRef" :label-width="formLabelWidth">
        <el-form-item :label="t('modules.goods.categoryName')" prop="name">
          <el-input v-model="form.model.name" :placeholder="t('form.inputCategoryName')"></el-input>
        </el-form-item>
        <el-form-item :label="t('form.sort')" prop="sort">
          <el-input v-model="form.model.sort" :placeholder="t('form.inputSort')"></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 { useI18n } from 'vue-i18n';
import { ElMessage } from 'element-plus';
import { useFormConfig } from '@/hooks/useFormConfig';
import { api } from '../goods.service';

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: '',
    sort: '0',
  },
  get rules() {
    return {
      name: [{ required: true, message: t('form.categoryNameRequired'), trigger: 'blur' }],
    };
  },
});
const loading = ref(false);
// 获取详情
async function getDetail(id) {
  loading.value = true;
  const { code, data } = await api.category.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.category.add(submitForm)
        : await api.category.edit(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>
