<script setup lang="ts">
import { computed, reactive, ref, watch } from 'vue';
import type { FormRules } from 'element-plus';
import { confirmPerformanceSheet, rejectPerformanceSheet } from '@/service/api';
import { useForm, useFormRules } from '@/hooks/common/form';
import BusinessFormDialog from '@/components/custom/business-form-dialog.vue';

defineOptions({ name: 'PerformanceActionDialog' });

interface Props {
  rowData?: Api.Performance.Sheet.Sheet | null;
  actionType: 'confirm' | 'reject';
}

const props = withDefaults(defineProps<Props>(), {
  rowData: null
});

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

const emit = defineEmits<{
  submitted: [];
}>();

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

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

const isReject = computed(() => props.actionType === 'reject');
const title = computed(() => (isReject.value ? '退回绩效表' : '确认绩效表'));
const confirmText = computed(() => (isReject.value ? '确认退回' : '确认'));
const rules = computed<FormRules>(() => ({
  reason: isReject.value ? [createRequiredRule('请输入退回原因')] : []
}));

async function handleSubmit() {
  if (!props.rowData?.id) return;

  if (isReject.value) {
    try {
      await validate();
    } catch {
      return;
    }
  }

  submitting.value = true;
  const result = isReject.value
    ? await rejectPerformanceSheet(props.rowData.id, { reason: form.reason.trim() })
    : await confirmPerformanceSheet(props.rowData.id, { reason: form.reason.trim() || undefined });
  submitting.value = false;

  if (result.error) return;

  window.$message?.success(isReject.value ? '绩效表已退回' : '绩效表已确认');
  visible.value = false;
  emit('submitted');
}

watch(visible, isVisible => {
  if (!isVisible) return;
  form.reason = '';
});
</script>

<template>
  <BusinessFormDialog
    v-model="visible"
    :title="title"
    preset="sm"
    append-to-body
    :confirm-text="confirmText"
    :confirm-loading="submitting"
    @confirm="handleSubmit"
  >
    <ElForm ref="formRef" :model="form" :rules="rules" label-position="top">
      <ElDescriptions :column="1" border>
        <ElDescriptionsItem label="绩效月份">{{ props.rowData?.periodMonth || '--' }}</ElDescriptionsItem>
        <ElDescriptionsItem label="员工">{{ props.rowData?.employeeName || '--' }}</ElDescriptionsItem>
        <ElDescriptionsItem label="实际得分">{{ props.rowData?.actualScoreTotal ?? '--' }}</ElDescriptionsItem>
      </ElDescriptions>

      <ElFormItem class="mt-16px" :label="isReject ? '退回原因' : '确认意见'" prop="reason">
        <ElInput
          v-model="form.reason"
          type="textarea"
          :rows="4"
          maxlength="1000"
          show-word-limit
          :placeholder="isReject ? '请输入退回原因' : '可填写确认意见'"
        />
      </ElFormItem>
    </ElForm>
  </BusinessFormDialog>
</template>
