<template>
  <el-dialog
    v-model="visible"
    title="选择领取仓库"
    width="500px"
    :before-close="handleClose"
  >
    <div class="warehouse-select-dialog">
      <el-form :model="form" label-width="80px">
        <el-form-item label="仓库选择" required>
          <el-select
            v-model="form.warehouseId"
            placeholder="请选择仓库"
            style="width: 100%"
            filterable
            clearable
          >
            <el-option
              v-for="warehouse in warehouseList"
              :key="warehouse.id"
              :label="warehouse.name"
              :value="warehouse.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
    </div>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleConfirm" :disabled="!form.warehouseId">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { request } from '/@/utils/service'

interface Warehouse {
  id: number
  name: string
}

interface Props {
  modelValue: boolean
  formId: number | null
}

interface Emits {
  (e: 'update:modelValue', value: boolean): void
  (e: 'confirm', data: { formId: number; warehouseId: number }): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const visible = ref(false)
const warehouseList = ref<Warehouse[]>([])
const loading = ref(false)

const form = reactive({
  warehouseId: null as number | null
})

// 获取仓库列表
const getWarehouseList = async () => {
  try {
    loading.value = true
    const response = await request({
      url: '/api/system/warehouse/',
      method: 'get',
      params: {
        page: 1,
        limit: 20
      }
    })
    
    if (response.code === 2000) {
      warehouseList.value = response.data || []
    } else {
      ElMessage.error('获取仓库列表失败')
    }
  } catch (error) {
    console.error('获取仓库列表失败:', error)
    ElMessage.error('获取仓库列表失败')
  } finally {
    loading.value = false
  }
}

// 监听弹窗显示状态
watch(() => props.modelValue, (newVal) => {
  visible.value = newVal
  if (newVal) {
    getWarehouseList()
    form.warehouseId = null
  }
})

// 监听内部visible状态
watch(visible, (newVal) => {
  emit('update:modelValue', newVal)
})

// 关闭弹窗
const handleClose = () => {
  visible.value = false
  form.warehouseId = null
}

// 确认选择
const handleConfirm = () => {
  if (!form.warehouseId) {
    ElMessage.warning('请选择仓库')
    return
  }
  
  if (!props.formId) {
    ElMessage.error('表单ID不存在')
    return
  }
  
  emit('confirm', {
    formId: props.formId,
    warehouseId: form.warehouseId
  })
  
  handleClose()
}
</script>

<style scoped>
.warehouse-select-dialog {
  padding: 20px 0;
}

.dialog-footer {
  text-align: right;
}
</style>
