<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="reason">
        <ElSelect
          v-model="form.reason"
          placeholder="请选择取消原因"
          style="width: 100%"
          clearable
        >
          <ElOption
            v-for="item in cancelReasons"
            :key="item"
            :label="item"
            :value="item"
          />
        </ElSelect>
      </ElFormItem>
      <div style="color: #f56c6c; margin-left: 100px; margin-top: -10px">
        注意: 取消订单后金额将原路返回
      </div>
    </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 { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { cancelOrderWithReasonApi } 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 cancelReasons = ['协商取消', '客户取消', '其他']

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

const rules: FormRules = {
  reason: [{ required: true, message: '请选择取消原因', trigger: 'change' }],
}

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

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

const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate()
  submitLoading.value = true
  try {
    await cancelOrderWithReasonApi(orderIds.value, form.reason)
    ElMessage.success('取消订单成功')
    visible.value = false
    emit('success')
  } catch (e: unknown) {
    console.error(e)
  } finally {
    submitLoading.value = false
  }
}

defineExpose({ open })
</script>
