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

defineOptions({ name: 'ProjectRequirementActionDialog' });

interface Props {
  action: Api.Project.ProjectRequirementLifecycleAction | null;
  requirementTitle: string;
}

const props = defineProps<Props>();

interface Emits {
  (e: 'submitted', payload: { actionCode: string; reason?: string }): void;
}

const emit = defineEmits<Emits>();

const visible = defineModel<boolean>('visible', { default: false });

const { formRef, validate } = useForm();
const { createRequiredRule } = useFormRules();

const model = ref({
  reason: ''
});
const submitting = ref(false);

const dialogTitle = computed(() => props.action?.actionName || '');
const needReason = computed(() => Boolean(props.action?.needReason));

const rules = computed(() => ({
  reason: needReason.value ? [createRequiredRule('请输入状态变更原因')] : []
}));

watch(
  () => visible.value,
  value => {
    if (value) {
      model.value.reason = '';
    }
  }
);

async function handleSubmit() {
  await validate();

  if (!props.action) {
    return;
  }

  submitting.value = true;

  emit('submitted', {
    actionCode: props.action.actionCode,
    reason: needReason.value ? model.value.reason.trim() : undefined
  });

  submitting.value = false;
  visible.value = false;
}
</script>

<template>
  <BusinessFormDialog
    v-model="visible"
    :title="dialogTitle"
    preset="sm"
    :confirm-loading="submitting"
    @confirm="handleSubmit"
  >
    <ElAlert
      v-if="requirementTitle"
      :title="`需求名称：${requirementTitle}`"
      type="info"
      :closable="false"
      class="mb-16px"
    />

    <ElForm ref="formRef" :model="model" :rules="rules" label-position="top">
      <ElFormItem v-if="needReason" label="变更原因" prop="reason">
        <ElInput
          v-model="model.reason"
          type="textarea"
          :rows="4"
          maxlength="500"
          show-word-limit
          placeholder="请输入状态变更原因（必填）"
        />
      </ElFormItem>
    </ElForm>
  </BusinessFormDialog>
</template>

<style scoped></style>
