<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)"
  >
    <FlowForm v-model:form="form" ref="modelFormRef" :isUpdate="isUpdate"></FlowForm>
  </a-modal>
</template>

<script setup name="FlowAddEdit">
import { ref, onMounted } from 'vue';
import FlowForm from './flow-form.vue';
import { message } from 'ant-design-vue';
import { BusinessFlowApi } from '../api/BusinessFlowApi';

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 = () => {
  BusinessFlowApi.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 = BusinessFlowApi.edit(form.value);
      } else {
        result = BusinessFlowApi.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>
