<template>
  <div class="apps-form">
    <el-dialog
      append-to-body :title="t('marketingApps.editDomain')" width="880" v-model="visible" :close-on-click-modal="false" :destroy-on-close="true"
      draggable>
      <DomainCollapse :data=domains @domains="updateDomains"
        @delDomains="handleDelDomains"></DomainCollapse>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="visible = false">{{ t('common.cancelButtonText') }}</el-button>
          <el-button type="primary" @click="onSubmit" :disabled="loading">{{ t('common.confirmButtonText')
          }}</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="domainForm">
import { useMessage } from '/@/hooks/message';
import { useI18n } from 'vue-i18n';
import { updateModDomains } from '/@/api/marketing/apps';
import { DomainItem } from '../types';

const DomainCollapse = defineAsyncComponent(() => import('./domainCollapse.vue'));

// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh']);
const { t } = useI18n();

// 定义变量内容
const visible = ref(false);
const loading = ref(false);
const domains = ref<DomainItem[]>([]);
const childDomains = ref();
const delDomains = ref<string[]>([]);
const rowData = ref();

// 打开弹窗
const openDialog = async (data: any, row) => {
  visible.value = true;
  domains.value = data;
  childDomains.value = [];
  delDomains.value = [];
  rowData.value = row;
};

const updateDomains = (data: DomainItem[])=>{
  childDomains.value = data;
}
const handleDelDomains = (data: string[]) => {
  delDomains.value = data;
}

// 保存数据
const onSubmit = async () => {
  try {
    updateModDomains({ domains: childDomains.value, delDomains: delDomains.value, id: rowData.value.id})
    emit('refresh');
    useMessage().success(t('marketingApps.submitSuccess'));
    visible.value = false;
  } catch (error) {
    useMessage().error(t('marketingApps.submitFail'));
    console.error(error);
  }
};

// 暴露变量 只有暴漏出来的变量 父组件才能使用
defineExpose({
  openDialog,
});
</script>
<style lang="scss">
.el-overlay {
  .el-overlay-dialog {
    .el-dialog {
      .el-dialog__body {
        padding: 0 !important;
      }
    }
  }
}
</style>