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

defineOptions({ name: 'PersonalItemStatusActionDialog' });

interface Props {
  action: Api.PersonalItem.PersonalItemLifecycleAction | null;
}

interface Emits {
  (e: 'submit', reason: string | null): void;
}

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

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

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

const model = reactive({
  reason: ''
});

const rules = computed(
  () =>
    ({
      reason: props.action?.needReason ? [createRequiredRule('请输入动作原因')] : []
    }) satisfies Record<string, App.Global.FormRule[]>
);

async function handleConfirm() {
  await validate();
  emit('submit', model.reason.trim() || null);
}

watch(
  () => visible.value,
  async value => {
    if (!value) {
      return;
    }

    model.reason = '';
    await nextTick();
    formRef.value?.clearValidate();
  }
);
</script>

<template>
  <BusinessFormDialog v-model="visible" :title="action?.actionName || '状态变更'" preset="sm" @confirm="handleConfirm">
    <ElForm ref="formRef" :model="model" :rules="rules" label-position="top" :validate-on-rule-change="false">
      <ElFormItem label="动作原因" prop="reason">
        <ElInput
          v-model="model.reason"
          type="textarea"
          :rows="4"
          maxlength="500"
          show-word-limit
          :placeholder="action?.needReason ? '请输入动作原因' : '可选填写动作原因'"
        />
      </ElFormItem>
    </ElForm>
  </BusinessFormDialog>
</template>

<style scoped></style>
