<template>
  <n-modal v-model:show="showModal" preset="card" title="发布任务" class="w-400px" :bordered="false">
    <div class="p-4">
      <n-form ref="formRef" :model="form" :rules="rules">
        <n-form-item label="接收人" path="operatorId">
          <n-select
            v-model:value="form.operatorId"
            filterable
            remote
            :options="operatorOptions"
            :loading="loading"
            placeholder="请选择接收人"
            label-field="name"
            value-field="id"
            @search="handleSearch"
          />
        </n-form-item>
        
        <div class="flex justify-end gap-2 mt-4">
          <n-button @click="hide">取消</n-button>
          <n-button type="primary" :loading="affirmLoading" @click="handleAffirm">提交</n-button>
        </div>
      </n-form>
    </div>
  </n-modal>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useMessage } from 'naive-ui';
import type { FormInst, FormRules } from 'naive-ui';
import { type BookReviewInput, releaseTaskAxios, fetchBookCategoryList } from '@/service/api/book';

const message = useMessage();
const showModal = ref(false);
const formRef = ref<FormInst | null>(null);
const affirmLoading = ref(false);
const loading = ref(false);
const operatorOptions = ref<any[]>([]);

let releaseTaskData: BookReviewInput | undefined = undefined;

const form = ref<BookReviewInput>({
  operatorId: undefined,
  bookId: 0, // Default values to satisfy type, will be overwritten
  bookPageId: 0
});

const rules: FormRules = {
  operatorId: [{ required: true, type: 'number', message: '请选择操作人', trigger: ['change', 'blur'] }],
};

async function handleSearch(query: string) {
  loading.value = true;
  try {
    const res = await fetchBookCategoryList({ name: query });
    operatorOptions.value = res || []; // Adjust based on actual API response structure (res.records or res)
  } catch (error) {
    console.error(error);
  } finally {
    loading.value = false;
  }
}

async function handleAffirm() {
  try {
    await formRef.value?.validate();
  } catch (error) {
    message.warning('请检查表单数据是否正确');
    return;
  }

  try {
    affirmLoading.value = true;
    await releaseTaskAxios({ ...releaseTaskData!, ...form.value });
    message.success('操作成功');
    hide();
  } catch (error: any) {
    console.error('error====', error);
    message.error(error.msg || '操作失败');
  } finally {
    affirmLoading.value = false;
  }
}

function show(data: { releaseTaskData?: BookReviewInput }) {
  releaseTaskData = data.releaseTaskData;
  showModal.value = true;
  handleSearch(''); // Load initial list
}

function hide() {
  showModal.value = false;
}

defineExpose({
  show,
  hide,
});
</script>

<style scoped>
</style>
