<template>
  <a-modal
    :open="modal.open"
    :title="modal.title"
    :width="600"
    :confirm-loading="modal.confirmLoading"
    :after-close="onAfterClose"
    :cancel-text="cancelText"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <a-form ref="formRef" :model="formData" :rules="formRules">
      <a-row :gutter="24">
        <!-- 分配到 -->
        <a-col :span="24">
          <a-form-item
            label="分配到"
            name="name"
            :rules="[{ required: true, message: '请选择节点' }]"
          >
            <a-select
              v-model:value="formData.name"
              style="width: 100%"
              :options="options"
              placeholder="请选择站点"
              allow-clear
            />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </a-modal>
</template>

<script setup>
import { ref } from 'vue'
import { config } from '@/config'
import apis from '@/apis'
import { useForm, useModal,usePagination } from '@/hooks'


const emit = defineEmits(['ok'])

const { modal, showModal, hideModal, showLoading, hideLoading } = useModal()
const { listData, loading, paginationState, resetPagination, searchFormData } = usePagination()
const { formData, formRef, resetForm } = useForm()

const cancelText = ref('取消')

// 普通下拉选项（value + label）
const options = ref([]);
const currentRecord = ref(null)

/**
 * 新建（暴露给父组件调用）
 */
function handleCreate(record) {
  currentRecord.value = record // 👈 保存传入的行数据
  showModal({
    type: 'create',
    title: '分配节点',
  })
  getData() // 可选：每次打开都重新加载站点列表
}

getData()
async function getData() {
    try {
        const { data, success } = await apis.serviceMenu.getServiceSiteList({
            pageSize: 999,
            current: 1
        })
        if (success) {
            options.value = data.map(item => ({ value: item.id, label: item.name }))
        }
    } catch (error) {
        console.error('获取服务站点列表失败:', error)
    }
}
/**
 * 确定
 */
async function handleOk() {
    console.log("formData",modal.value.type)
  try {
    await formRef.value.validateFields()
    showLoading()

    const params = { ...formData.value }

    let result
    if (modal.value.type === 'create') {
                console.log("====",params)
      result = await apis.serverObj.changeItem(currentRecord.value?.id,{stationId:formData.value.name})
      if (result.success) {
        emit('ok')
        hideModal()
      }
    } else if (modal.value.type === 'edit') {
        console.log("====",params)
    result = await apis.serverObj.updateItem(params)
    }

    hideLoading()

    if (config('http.code.success') === result?.code) {
      hideModal()
      emit('ok')
    }
  } catch (error) {
    hideLoading()
  }
}

/**
 * 取消
 */
function handleCancel() {
  hideModal()
}

/**
 * 关闭后重置表单
 */
function onAfterClose() {
  resetForm()
}

// 暴露方法给父组件
defineExpose({
  handleCreate,
})
</script>

<style lang="less" scoped></style>