<script setup lang="ts">
import { computed, reactive, ref, watch } from 'vue';
import BusinessFormDialog from '@/components/custom/business-form-dialog.vue';

defineOptions({ name: 'ObjectDeleteDialog' });

interface Props {
  /** 是否显示（v-model:visible） */
  visible: boolean;
  /** 对象类型：影响标题、字段标签、警示文案 */
  objectType: 'execution' | 'task';
  /** 当前对象的名称，用作输入框 placeholder 参照；提交时校验完全一致 */
  objectName: string;
  /** 下挂数据摘要，由 precheck 计算后传入（如 "下含 3 个子任务 + 5 条工作日志"）；null/空则走兜底文案 */
  dependentSummary?: string | null;
  /** 删除确认回调，async；接收三个字段；resolve 后由调用方决定刷新/关闭 */
  onConfirm: (payload: { name: string; confirmText: string; reason: string }) => Promise<void>;
}

interface Emits {
  (e: 'update:visible', value: boolean): void;
}

const props = defineProps<Props>();
const emit = defineEmits<Emits>();

const VALID_CONFIRM_TEXTS = new Set(['删除', 'DELETE']);

const dialogVisible = computed({
  get: () => props.visible,
  set: val => emit('update:visible', val)
});

const objectTypeLabel = computed(() => (props.objectType === 'execution' ? '执行' : '任务'));

const form = reactive({
  name: '',
  confirmText: '',
  reason: ''
});

const submitting = ref(false);

watch(
  () => props.visible,
  val => {
    if (val) {
      form.name = '';
      form.confirmText = '';
      form.reason = '';
      submitting.value = false;
    }
  }
);

const canSubmit = computed(
  () => form.name === props.objectName && VALID_CONFIRM_TEXTS.has(form.confirmText) && form.reason.trim().length > 0
);

async function handleConfirm() {
  submitting.value = true;
  try {
    await props.onConfirm({
      name: form.name,
      confirmText: form.confirmText,
      reason: form.reason
    });
  } finally {
    submitting.value = false;
  }
}
</script>

<template>
  <BusinessFormDialog
    v-model="dialogVisible"
    :title="`删除${objectTypeLabel}`"
    preset="sm"
    :confirm-loading="submitting"
    :confirm-disabled="!canSubmit"
    @confirm="handleConfirm"
  >
    <ElAlert type="error" :closable="false" show-icon>
      <template v-if="dependentSummary">
        此操作不可撤销，{{ objectTypeLabel }}{{ dependentSummary }}，删除后将一并不可见
      </template>
      <template v-else>此操作不可撤销，删除后{{ objectTypeLabel }}下挂数据将不可见</template>
    </ElAlert>

    <ElForm label-position="top" class="mt-3">
      <ElFormItem :label="`请再次输入${objectTypeLabel}名称（与当前名称完全一致）`" required>
        <ElInput v-model="form.name" :placeholder="objectName" />
      </ElFormItem>
      <ElFormItem label="删除确认口令" required>
        <ElInput v-model="form.confirmText" placeholder='请输入"删除"以确认' />
      </ElFormItem>
      <ElFormItem label="删除原因" required>
        <ElInput v-model="form.reason" type="textarea" :rows="3" maxlength="500" show-word-limit />
      </ElFormItem>
    </ElForm>
  </BusinessFormDialog>
</template>
