<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)"
  >
    <PortalConfigForm v-model:form="form" ref="hostFormRef" :isUpdate="isUpdate" :iconList="props.iconList"></PortalConfigForm>

    <template #footer>
      <a-button class="border-radius grey" @click="updateVisible(false)" type="link">取消</a-button>
      <a-button class="border-radius" type="primary" @click="save">确定</a-button>
    </template>
  </common-modal>
</template>

<script setup name="PortalConfigAddEdit">
import { ref, onMounted } from 'vue';
import PortalConfigForm from './config-form.vue';
import { message } from 'ant-design-vue';
import { PortalBackendConfigApi } from '../api/PortalBackendConfigApi';

const props = defineProps({
  visible: Boolean,
  data: Object,
  iconList: Array
});

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

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

// 获取详情
const getDetail = () => {
  PortalBackendConfigApi.detail({ designId: props.data.designId }).then(res => {
    form.value = Object.assign({}, res);
    if (form.value.designLogo) {
      hostFormRef.value.modelIconSet(form.value.designLogo);
    }
  });
};

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

// 点击保存
const save = async () => {
  hostFormRef.value.$refs.formRef.validate().then(async valid => {
    if (valid) {
      // 修改加载框为正在加载
      loading.value = true;

      let result = null;

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