<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="pauseType">
        <ElSelect
          v-model="form.pauseType"
          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: 1 },
  { label: '地址异常', value: 2 },
  { label: '素材异常', value: 3 },
  { label: '其他', value: 4 },
]
const customerHandleOptions = [
  { label: '需要客户处理', value: 'CUSTOMER' },
  { label: '无需客户处理', value: 'FACTORY' },
]

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

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

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

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

const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate()
  submitLoading.value = true
  try {
    const res = await suspendOrderApi(orderIds.value, form.pauseReason, form.pauseType)
    if (res.code !== 200) return
    ElMessage.success('挂起订单成功')
    visible.value = false
    emit('success')
  } catch (e) {
    console.error(e)
  } finally {
    submitLoading.value = false
  }
}

defineExpose({ open })
</script>
