<template>
  <!-- 新增编辑 -->
  <a-modal
    :width="800"
    :maskClosable="false"
    :visible="props.visible"
    :confirm-loading="loading"
    :forceRender="true"
    style="top: 40px"
    :title="isUpdate ? '编辑表' : '新建表'"
    :body-style="{ paddingBottom: '8px', height: '650px', overflowY: 'auto' }"
    @update:visible="updateVisible"
    @ok="save"
    @close="updateVisible(false)"
  >
    <SheetForm v-model:form="form" ref="modelFormRef" :isUpdate="isUpdate"></SheetForm>
  </a-modal>
</template>

<script setup name="SheetAddEdit">
import { ref, onMounted } from 'vue';
import SheetForm from './sheet-form.vue';
import { message } from 'ant-design-vue';
import { ModelApi } from '../../api/ModelApi';
import { CommonApi } from '@/api/CommonApi';
import { getBusinessMaxSort } from '@/utils/common/util';

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

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

onMounted(async() => {
  if (props.data) {
    isUpdate.value = true;
    getDetail();
  } else {
    form.value.fldSort = await getBusinessMaxSort('DEVOPS_META_MODEL');
    getSystemCode();
    isUpdate.value = false;
  }
});

// 获取系统编码code
const getSystemCode = async () => {
  const res = await CommonApi.getSystemCode({ systemType: 'TB' });
  const { systemCodeShow, systemCode } = res.data;
  form.value.systemCode = systemCode;
  form.value.systemCodeShow = systemCodeShow;
};

// 获取详情
const getDetail = () => {
  ModelApi.detail({ metaModelId: props.data.metaModelId }).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 = ModelApi.edit(form.value);
      } else {
        result = ModelApi.add(form.value);
      }
      result
        .then(async result => {
          // 移除加载框
          loading.value = false;

          // 提示添加成功
          message.success(result.message);
          // 关闭弹框，通过控制visible的值，传递给父组件
          updateVisible(false);

          // 触发父组件done事件
          emits('done');
        })
        .catch(() => {
          loading.value = false;
        });
    }
  });
};
</script>

<style></style>
