<template>
    <el-config-provider :locale="zhCn">
        <el-container class="content">
            <div class="work-area">
                <fieldset class="main-area">
                    <legend>出库单信息</legend>
                    <el-form ref="orderOutFormRef" :model="orderOutForm" :rules="rules" label-width="70px" :label-position="labelPosition" status-icon>
                        <el-row :gutter="5" class="form-row">
                            <el-col :xs="24" :sm="4" :md="4" :lg="4">
                                <el-form-item label="物料编号" prop="goodsId">
                                    <el-input v-model="orderOutForm.goodsId" clearable @keyup.enter="handleEnter('batch')" ref="goodsIdRef" class="custom-input" />
                                </el-form-item>
                            </el-col>
                            <el-col :xs="24" :sm="4" :md="4" :lg="4">
                                <el-form-item label="批次" prop="batch">
                                    <el-input v-model="orderOutForm.batch" clearable @keyup.enter="handleEnter('specification')" ref="batchRef" class="custom-input" />
                                </el-form-item>
                            </el-col>
                            <el-col :xs="24" :sm="4" :md="4" :lg="4">
                                <el-form-item label="规格" prop="specification">
                                    <el-input v-model="orderOutForm.specification" placeholder="请输入规格" clearable @keyup.enter="handleEnter('quantity')" ref="specificationRef" class="custom-input" />
                                </el-form-item>
                            </el-col>
                            <el-col :xs="24" :sm="4" :md="4" :lg="4">
                                <el-form-item label="数量" prop="quantity">
                                    <el-input-number v-model="orderOutForm.quantity" :min="1" controls-position="right" clearable ref="quantityRef" class="custom-input" />
                                </el-form-item>
                            </el-col>
                            <el-col :xs="24" :sm="4" :md="4" :lg="4" class="btn-col">
                                <el-button type="success" @click="submitOrderOut">提交</el-button>
                                <el-button type="warning" @click="resetForm">重置</el-button>
                            </el-col>
                        </el-row>
                    </el-form>
                </fieldset>

                <el-dialog v-model="responseDialogVisible" title="请求结果" width="500px">
                    <pre>{{ responseResult }}</pre>
                    <template #footer>
                        <span class="dialog-footer">
                            <el-button type="primary" @click="responseDialogVisible = false">确定</el-button>
                        </span>
                    </template>
                </el-dialog>
            </div>
        </el-container>
    </el-config-provider>
</template>

<script setup>
import { reactive, ref, onMounted, nextTick, onBeforeUnmount } from 'vue'
import { ElMessage } from 'element-plus'
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
import { loading } from '@/utils/loading.js'
import { errorBox } from '@/utils/myMessageBox.js'
import { labelPosition } from '@/constant/form'
import { submitOrderOutForm } from '@/api/orderOut.js'

// 生成订单号方法
const generateOrderId = () => {
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  const hours = String(now.getHours()).padStart(2, '0')
  const minutes = String(now.getMinutes()).padStart(2, '0')
  const seconds = String(now.getSeconds()).padStart(2, '0')
  const milliseconds = String(now.getMilliseconds()).padStart(3, '0')
  return `baokai${year}${month}${day}${hours}${minutes}${seconds}${milliseconds}`
}

// 表单数据
const orderOutFormRef = ref()
const orderOutForm = reactive({
    orderId: generateOrderId(),
    goodsId: '',
    batch: '',
    specification: '',
    quantity: null
})

// 表单规则
const rules = reactive({
    goodsId: [{ required: true, message: '请输入物料编号', trigger: 'blur' }],
    batch: [{ required: true, message: '请输入批次', trigger: 'blur' }],
    specification: [{ required: true, message: '请输入规格', trigger: 'blur' }],
    quantity: [{ required: true, message: '请输入数量', trigger: 'blur' }]
})

// 引用DOM元素
const goodsIdRef = ref()
const batchRef = ref()
const specificationRef = ref()
const quantityRef = ref()

// 响应结果对话框
const responseDialogVisible = ref(false)
const responseResult = ref({})

// 初始化时聚焦第一个输入框
onMounted(() => {
    nextTick(() => {
        goodsIdRef.value.focus()
        window.addEventListener('resize', resizeHeight)
    })
})

onBeforeUnmount(() => {
    window.removeEventListener('resize', resizeHeight)
})

// 调整高度
const resizeHeight = () => {
    // 如果需要可以在这里添加高度调整逻辑
}

// 处理回车事件
const handleEnter = (nextField) => {
    const refMap = {
        'goodsId': goodsIdRef,
        'batch': batchRef,
        'specification': specificationRef,
        'quantity': quantityRef
    }
    
    if (refMap[nextField]) {
        refMap[nextField].value.focus()
    }
}

// 重置表单
const resetForm = () => {
    orderOutFormRef.value.resetFields()
    // 重新生成订单号
    orderOutForm.orderId = generateOrderId()
    nextTick(() => {
        goodsIdRef.value.focus()
    })
}

// 提交出库单
const submitOrderOut = () => {
    orderOutFormRef.value.validate((valid) => {
        if (valid) {
            // 发送请求
            loading.open()
            submitOrderOutForm(orderOutForm)
                .then(res => {
                    responseResult.value = res.data
                    responseDialogVisible.value = true
                    
                    if (res.data.code === 0) {
                        ElMessage.success('出库单提交成功')
                        resetForm() // 提交成功后重置表单
                    } else {
                        errorBox(`出库单提交失败: ${res.data.message}`)
                    }
                })
                .catch(err => {
                    console.error(err)
                    errorBox('提交出库单时发生错误')
                })
                .finally(() => {
                    loading.close()
                })
        } else {
            errorBox('请填写完整的出库单信息')
        }
    })
}
</script>

<style scoped>
.content {
    display: flex;
    width: 100%;
    overflow-x: hidden;
}

.work-area {
    width: 100%;
    height: calc(100vh - 160px);
    padding: 15px;
    overflow-y: auto;
    overflow-x: hidden;
    box-sizing: border-box;
}

.main-area {
    width: 100%;
    margin-bottom: 20px;
    padding: 15px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    box-sizing: border-box;
}

legend {
    padding: 0 10px;
    font-weight: bold;
}

pre {
    white-space: pre-wrap;
    word-wrap: break-word;
    background-color: #f8f8f8;
    padding: 15px;
    border-radius: 4px;
    max-height: 300px;
    overflow-y: auto;
}

:deep(.el-input),
:deep(.el-input-number) {
    width: 100%;
}

.form-row {
    display: flex;
    align-items: center;
}

:deep(.custom-input) {
    width: 100%;
}

:deep(.custom-input .el-input__inner),
:deep(.custom-input .el-input-number__decrease),
:deep(.custom-input .el-input-number__increase),
:deep(.custom-input .el-input-number__inner) {
    height: 40px;
    line-height: 40px;
}

.btn-col {
    display: flex;
    align-items: center;
    justify-content: space-around;
}

.btn-col .el-button {
    margin-left: 0;
    height: 40px;
}
</style> 