<template>
  <ElDialog
    v-model="visible"
    title="挂起订单"
    width="500px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <ElForm ref="formRef" :model="form" :rules="rules" label-width="140px">
      <ElFormItem label="挂起原因" prop="pauseReason">
        <ElSelect
          v-model="form.pauseReason"
          placeholder="请选择挂起原因"
          style="width: 100%"
          clearable
        >
          <ElOption
            v-for="item in suspendReasons"
            :key="item"
            :label="item.label"
            :value="item.value"
          />
        </ElSelect>
      </ElFormItem>
      <ElFormItem label="是否需要客户处理" prop="needCustomerHandle">
        <ElSelect
          v-model="form.needCustomerHandle"
          placeholder="请选择"
          style="width: 100%"
          clearable
        >
          <ElOption
            v-for="item in customerHandleOptions"
            :key="item"
            :label="item.label"
            :value="item.value"
          />
        </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 } 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 = [
  { label: '客户拦截', value: 4 },
  { label: '地址异常', value: 3 },
  { label: '素材异常', value: 2 },
  { label: '其他', value: 1 },
]
const customerHandleOptions = [
  { label: '需要客户处理', value: 'NEED_CUSTOMER_HANDLE' },
  { label: '无需客户处理', value: 'NO_CUSTOMER_HANDLE' },
]

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

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

const open = (ids: (number | string)[]) => {
  orderIds.value = ids
  form.pauseReason = ''
  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.pauseReason, form.needCustomerHandle)
    ElMessage.success('挂起订单成功')
    visible.value = false
    emit('success')
  } catch (e) {
    console.error(e)
  } finally {
    submitLoading.value = false
  }
}

defineExpose({ open })
</script>
