<template>
  <ElDialog
    v-model="visible"
    title="确认接单"
    width="450px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <ElForm ref="formRef" :model="form" :rules="rules" label-width="100px">
      <ElFormItem label="发货仓库" prop="warehouseId">
        <ElSelect
          v-model="form.warehouseId"
          placeholder="请选择发货仓库"
          filterable
          style="width: 100%"
        >
          <ElOption
            v-for="item in warehouseList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </ElSelect>
      </ElFormItem>
    </ElForm>
    <template #footer>
      <div class="dialog-footer" style="text-align: center">
        <ElButton @click="visible = false">取消</ElButton>
        <ElButton type="primary" :loading="submitLoading" @click="handleSubmit">
          确认
        </ElButton>
      </div>
    </template>
  </ElDialog>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { loadWarehouseListApi } from '@/api/common'
import { confirmOrderWithWarehouseApi } from '@/api/factoryOrderNew'
import type { WarehouseListData } from '@/types'

const emit = defineEmits<{
  success: [data: {
    factoryOrderNumber?: string
    message?: string
    id: number | string
    status?: boolean
  }[]]
}>()

const visible = ref(false)
const submitLoading = ref(false)
const formRef = ref<FormInstance>()
const warehouseList = ref<WarehouseListData[]>([])
const orderIds = ref<(number | string)[]>([])

const form = reactive({
  warehouseId: '' as number | string,
})

const rules: FormRules = {
  warehouseId: [
    { required: true, message: '请选择发货仓库', trigger: 'change' },
  ],
}

const loadWarehouseList = async () => {
  try {
    const res = await loadWarehouseListApi()
    warehouseList.value = res.data || []
  } catch (_e) {
    /* empty */
  }
}

const open = (ids: (number | string)[]) => {
  orderIds.value = ids
  form.warehouseId = ''
  visible.value = true
  loadWarehouseList()
}

const handleClose = () => {
  formRef.value?.resetFields()
}

const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate()
  submitLoading.value = true
  try {
    const res = await confirmOrderWithWarehouseApi(
      orderIds.value,
      form.warehouseId,
    )
    if (res.code !== 200) return
    visible.value = false
    emit('success', res.data)
  } catch (e) {
    console.error(e)
  } finally {
    submitLoading.value = false
  }
}

defineExpose({ open })
</script>
