<template>
  <el-dialog title="发货" v-model="show" width="600px">
    <el-form :model="form" ref="formRef" :rules="rules" label-width="80px">
      <el-form-item label="发货仓库" prop="warehouseId">
        <el-select v-model="form.warehouseId" placeholder="选择仓库" filterable>
          <el-option
            v-for="item in warehouseOptions"
            :key="item.warehouseId"
            :label="item.warehouseName"
            :value="item.warehouseId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="备注">
        <Editor v-model:modelValue="form.remark" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span>
        <el-button @click="show = false">取 消</el-button>
        <el-button :disabled="formLoading" type="primary" @click="onSubmit">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup name="DialogDelivery">
import { getSimpleWarehouseList } from '@/api/mall/warehouse'
import { createDelivery } from '@/api/clue/delivery'

const message = useMessage() // 消息弹窗

const warehouseOptions = ref([])
function getOptions() {
  getSimpleWarehouseList().then((data) => {
    warehouseOptions.value = data
  })
}

const show = ref(false)
function open(id) {
  show.value = true
  resetForm(id)
}
defineExpose({
  open
})

const form = ref({})
const rules = ref({
  warehouseId: { required: true, message: '仓库不可为空', trigger: 'change' }
})
function resetForm(id) {
  form.value = {
    signProductId: id,
    warehouseId: undefined,
    remark: undefined
  }
}

const emit = defineEmits(['success'])
const formLoading = ref(false)
const formRef = ref()
async function onSubmit() {
  // 校验表单
  if (!formRef.value) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    await createDelivery(form.value)
    message.success('发货成功！')
    show.value = false
    emit('success')
  } finally {
    formLoading.value = false
  }
}

onMounted(() => {
  getOptions()
})
</script>

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