<script lang="ts" setup>
import type { ComplaintApi } from '#/api/complaint';
import { ref, watch } from 'vue';

import { useVbenModal } from '@vben/common-ui';
import { message } from 'ant-design-vue';

import { updateComplaintStatus } from '#/api/complaint';

interface Props {
  data?: ComplaintApi.Complaint;
}

const props = defineProps<Props>();

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

const [Modal, modalApi] = useVbenModal();

const formData = ref<ComplaintApi.UpdateStatusRequest>({
  status: 'pending',
  status_description: '',
  handler_id: '',
});

const loading = ref(false);

watch(
  () => props.data,
  (data) => {
    if (data) {
      formData.value = {
        status: (data.status as any) || 'pending',
        status_description: data.status_description || '',
        handler_id: data.handler_id || '',
      };
    }
  },
  { immediate: true },
);

async function handleSubmit() {
  if (!props.data) return;

  loading.value = true;
  try {
    await updateComplaintStatus(props.data.id, formData.value);
    message.success('更新状态成功');
    emit('success');
    modalApi.close();
  } catch (error) {
    message.error('更新状态失败');
  } finally {
    loading.value = false;
  }
}

defineExpose({
  setData: (data: ComplaintApi.Complaint) => {
    formData.value = {
      status: (data.status as any) || 'pending',
      status_description: data.status_description || '',
      handler_id: data.handler_id || '',
    };
    modalApi.open();
    return modalApi;
  },
  open: () => modalApi.open(),
  close: () => modalApi.close(),
});
</script>

<template>
  <Modal title="更新投诉状态" width="600px">
    <a-form :model="formData" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
      <a-form-item label="投诉状态" required>
        <a-select v-model:value="formData.status">
          <a-select-option value="pending">待处理</a-select-option>
          <a-select-option value="processing">处理中</a-select-option>
          <a-select-option value="resolved">已解决</a-select-option>
          <a-select-option value="closed">已关闭</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="状态描述">
        <a-textarea v-model:value="formData.status_description" :rows="3" placeholder="请输入状态描述" />
      </a-form-item>
      <a-form-item label="处理人ID">
        <a-input v-model:value="formData.handler_id" placeholder="请输入处理人ID" />
      </a-form-item>
    </a-form>
    <template #footer>
      <a-button @click="modalApi.close()">取消</a-button>
      <a-button type="primary" :loading="loading" @click="handleSubmit">
        确定
      </a-button>
    </template>
  </Modal>
</template>
