<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 { updateComplaintRemark } from '#/api/complaint';

interface Props {
  data?: ComplaintApi.Complaint;
}

const props = defineProps<Props>();

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

const [Modal, modalApi] = useVbenModal();

const formData = ref<ComplaintApi.UpdateRemarkRequest>({
  remark: '',
});

const loading = ref(false);

watch(
  () => props.data,
  (data) => {
    if (data) {
      formData.value = {
        remark: data.remark || '',
      };
    }
  },
  { immediate: true },
);

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

  loading.value = true;
  try {
    await updateComplaintRemark(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 = {
      remark: data.remark || '',
    };
    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="处理备注">
        <a-textarea v-model:value="formData.remark" :rows="5" placeholder="请输入处理备注" />
      </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>
