<template>
  <ElDialog
    v-model="visible"
    title="挂起订单"
    width="500px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <ElForm ref="formRef" :model="form" :rules="rules" label-width="130px">
      <ElFormItem label="挂起原因" prop="reason">
        <ElSelect
          v-model="form.reason"
          placeholder="请选择挂起原因"
          style="width: 100%"
        >
          <ElOption
            v-for="item in suspendReasons"
            :key="item"
            :label="item"
            :value="item"
          />
        </ElSelect>
      </ElFormItem>
      <ElFormItem label="是否需要客户处理" prop="needCustomerHandle">
        <ElSelect
          v-model="form.needCustomerHandle"
          placeholder="请选择"
          style="width: 100%"
        >
          <ElOption
            v-for="item in customerHandleOptions"
            :key="item"
            :label="item"
            :value="item"
          />
        </ElSelect>
      </ElFormItem>
    </ElForm>
    <template #footer>
      <ElButton @click="visible = false">取消</ElButton>
      <ElButton type="primary" :loading="submitLoading" @click="handleSubmit">
        确认
      </ElButton>
    </template>
  </ElDialog>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { suspendOrderApi } from '@/api/factoryOrderNew'

const emit = defineEmits<{
  success: []
}>()

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

const suspendReasons = ['客户拦截', '地址异常', '素材异常', '其他']
const customerHandleOptions = ['需要客户处理', '无需客户处理']

const form = reactive({
  reason: '',
  needCustomerHandle: '',
})

const rules: FormRules = {
  reason: [{ required: true, message: '请选择挂起原因', trigger: 'change' }],
  needCustomerHandle: [
    { required: true, message: '请选择是否需要客户处理', trigger: 'change' },
  ],
}

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

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

const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate()
  submitLoading.value = true
  try {
    await suspendOrderApi(
      orderIds.value,
      form.reason,
      form.needCustomerHandle,
    )
    ElMessage.success('挂起订单成功')
    visible.value = false
    emit('success')
  } catch (e: any) {
    ElMessageBox.alert(e?.message || '挂起订单失败', '挂起订单失败', {
      type: 'error',
    })
  } finally {
    submitLoading.value = false
  }
}

defineExpose({ open })
</script>
