<template>
  <!-- 新增编辑 -->
  <common-modal
    :width="700"
    :maskClosable="false"
    :visible="props.visible"
    :confirm-loading="loading"
    :forceRender="true"
    wrapClassName="project-modal"
    :title="isUpdate ? '编辑业务' : '新建业务'"
    :body-style="{ paddingBottom: '8px' }"
    @update:visible="updateVisible"
    @ok="save"
    @close="updateVisible(false)"
  >
    <a-form ref="formRef" :model="form" :rules="rules" layout="vertical">
      <a-form-item label="图纸名称:" name="diagramName">
        <a-input v-model:value="form.diagramName" allow-clear placeholder="请输入图纸名称" />
      </a-form-item>
      <a-form-item label="排序:" name="fldSort">
        <a-input-number v-model:value="form.fldSort" :min="0" style="width: 100%" placeholder="请输入排序" allow-clear autocomplete="off" />
      </a-form-item>
    </a-form>
  </common-modal>
</template>

<script setup name="BusinessAddEdit">
import { ref, onMounted, reactive } from 'vue';
import { message } from 'ant-design-vue';
import { getBusinessMaxSort } from '@/utils/common/util';
import { BusinessGraphApi } from '../api/BusinessGraphApi';

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 formRef = ref(null);

// 验证规则
const rules = reactive({
  diagramName: [{ required: true, message: '请输入图纸名称', type: 'string', trigger: 'blur' }],
  fldSort: [{ required: true, message: '请输入排序', type: 'number', trigger: 'blur' }]
});

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

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

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

// 点击保存
const save = async () => {
  await formRef.value.validate();

  // 修改加载框为正在加载
  loading.value = true;

  let result = null;

  // 执行编辑或修改
  if (isUpdate.value) {
    result = BusinessGraphApi.edit(form.value);
  } else {
    result = BusinessGraphApi.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>
