<template>
  <a-modal
    :width="528"
    :maskClosable="false"
    :visible="props.visible"
    :confirm-loading="loading"
    :forceRender="true"
    :title="isUpdate ? '编辑表格' : '新建表格'"
    :body-style="{ paddingBottom: '8px' }"
    @update:visible="updateVisible"
    @ok="save"
    @close="updateVisible(false)"
  >
    <ExcelForm v-model:form="form" ref="modelFormRef" :isUpdate="isUpdate"></ExcelForm>
  </a-modal>
</template>

<script setup name="ExcelAddEdit">
import { ref, onMounted } from 'vue';
import ExcelForm from './excel-form.vue';
import { message } from 'ant-design-vue';
import { BusinessExcelApi } from '../api/BusinessExcelApi';

const props = defineProps({
  visible: Boolean,
  data: Object,
  businessId: String
});

const emits = defineEmits(['update:visible', 'done']);
// 弹框加载
const loading = ref(false);
// 是否是编辑状态
const isUpdate = ref(false);
// 表单数据
const form = ref({
  businessId: props.businessId
});
// ref
const modelFormRef = ref(null);

onMounted(async () => {
  if (props.data) {
    isUpdate.value = true;
    getDetail();
  } else {
    isUpdate.value = false;
  }
});

// 获取详情
const getDetail = () => {
  BusinessExcelApi.detail({ id: props.data.id }).then(res => {
    form.value = Object.assign({}, res);
  });
};

// 更改弹框状态
const updateVisible = value => {
  emits('update:visible', value);
};

// 点击保存
const save = async () => {
  modelFormRef.value.$refs.formRef.validate().then(async valid => {
    if (valid) {
      loading.value = true;
      let result = null;
      if (isUpdate.value) {
        result = BusinessExcelApi.edit(form.value);
      } else {
        result = BusinessExcelApi.add(form.value);
      }
      result
        .then(async result => {
          loading.value = false;
          message.success(result.message);
          updateVisible(false);
          emits('done');
        })
        .catch(() => {
          loading.value = false;
        });
    }
  });
};
</script>

<style></style>
