<!-- 入库审核-弹窗详情 -->
<template>
    <el-dialog title="入库审核" v-model="props.show" @close="handleClose" width="900px">
        <div class="Cneter-box">
            <div class="inspection-details">
                <h3>球机回收核验详情</h3>
                <el-row :gutter="20">
                    <el-col :span="10">
                        <div class="camera-photo">
                            <img v-if="form.photoUrl" :src="form.photoUrl" alt="球机照片" />
                            <div v-else class="no-photo">暂无照片</div>
                        </div>
                    </el-col>
                    <el-col :span="14">
                <div class="info-list">
                  <div class="info-item">
                    <label>球机编号：</label>
                    <span>{{ form.cameraNo }}</span>
                  </div>
                  <div class="info-item">
                    <label>所属项目：</label>
                    <span>{{ form.projectName }}</span>
                  </div>
                  <div class="info-item">
                    <label>回收人：</label>
                    <span>{{ form.returnBy }}</span>
                  </div>
                  <div class="info-item">
                    <label>回收时间：</label>
                    <span>{{ form.returnTime }}</span>
                  </div>
                  <div class="info-item">
                    <label>核验结果：</label>
                    <span>{{ form.remark }}</span>
                  </div>
                </div>
              </el-col>
                </el-row>
            </div>

            <div class="storage-info">
                <h3>入库信息</h3>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form :model="form" :rules="Frules" label-width="100px" ref="formRef">
                            <el-form-item label="入库仓库" required>
                                <el-select v-model="form.warehouse" placeholder="请选择入库仓库">
                                    <el-option label="一号仓库" value="1" />
                                    <el-option label="二号仓库" value="2" />
                                    <el-option label="三号仓库" value="3" />
                                </el-select>
                            </el-form-item>
                            <el-form-item label="入库时间">
                                <el-date-picker v-model="form.inboundTime" type="datetime" style="width: 100%;" />
                            </el-form-item>
                        </el-form>
                    </el-col>
                    <el-col :span="12">
                        <el-form :model="form" label-width="100px">
                            <el-form-item label="入库管理员">
                                <el-input v-model="form.keeper" placeholder="请输入入库管理员" />
                            </el-form-item>
                        </el-form>
                    </el-col>
                </el-row>
            </div>
        </div>

        <!-- 底部按钮 -->
        <template #footer>
            <el-button @click="handleClose">取消</el-button>
            <el-button type="primary" @click="handleSubmit" :loading="submitting">确认入库</el-button>
        </template>
    </el-dialog>
</template>

<script setup>
import { ref, watch } from 'vue'
import { formatDate } from '@/utils'
import { approveInventoryAudit } from '@/api/tenement/inventoryAudit'
import { dayjs, ElMessage } from 'element-plus'

const props = defineProps({
    show: {
        type: Boolean,
        default: false
    },
    CloseDialog: {
        type: Function,
        default: () => { }
    },
    rowData: {
        type: Object,
        default: () => null
    }
})

const emit = defineEmits(['refresh'])

const form = ref({
    cameraNo: '',
    projectName: '',
    returnBy: '',
    returnTime: '',
    remark: '',
    photoUrl: '', // 球机照片
    warehouse: '',
    inboundTime: '',
    keeper: ''
})
const Frules = ref({
    warehouse: [{ required: true, message: '请选择入库仓库', trigger: 'blur' }],
})

const formRef = ref(null)
const submitting = ref(false)

// 监听弹窗显示状态，打开时从表格行数据中获取信息
watch(() => props.show, (newVal) => {
    if (newVal && props.rowData) {
        // 处理照片URL：如果有多个照片，取第一张
        let photoUrl = ''
        if (props.rowData.returnPhotos) {
            if (typeof props.rowData.returnPhotos === 'string') {
                const photos = props.rowData.returnPhotos.split(',').filter(url => url.trim())
                photoUrl = photos[0] || ''
            } else if (Array.isArray(props.rowData.returnPhotos) && props.rowData.returnPhotos.length > 0) {
                photoUrl = props.rowData.returnPhotos[0]
            }
        } else if (props.rowData.photoUrls) {
            if (typeof props.rowData.photoUrls === 'string') {
                const photos = props.rowData.photoUrls.split(',').filter(url => url.trim())
                photoUrl = photos[0] || ''
            } else if (Array.isArray(props.rowData.photoUrls) && props.rowData.photoUrls.length > 0) {
                photoUrl = props.rowData.photoUrls[0]
            }
        }
        
        // 从表格行数据中获取信息
        form.value = {
            cameraNo: props.rowData.cameraNo || '',
            projectName: props.rowData.projectName || '',
            returnBy: props.rowData.returnBy || '',
            returnTime: props.rowData.returnTime ? formatDate(props.rowData.returnTime) : '',
            remark: props.rowData.remark || '',
            photoUrl: photoUrl,
            warehouse: '',
            inboundTime: '',
            keeper: ''
        }
    }
})



const handleClose = () => {
    // 重置表单
    form.value = {
        cameraNo: '',
        projectName: '',
        returnBy: '',
        returnTime: '',
        remark: '',
        photoUrl: '',
        warehouse: '',
        inboundTime: '',
        keeper: ''
    }
    props.CloseDialog()
}

const handleSubmit = async () => {
    // 表单验证
    if (!formRef.value) return
    
    try {
        await formRef.value.validate()
    } catch (error) {
        ElMessage.warning('请完善表单信息')
        return
    }

    // 验证必填项
    if (!form.value.warehouse) {
        ElMessage.warning('请选择入库仓库')
        return
    }

    // 格式化入库时间
    let inboundTimeStr = ''
    if (form.value.inboundTime) {
        if (form.value.inboundTime instanceof Date) {
            const year = form.value.inboundTime.getFullYear()
            const month = String(form.value.inboundTime.getMonth() + 1).padStart(2, '0')
            const day = String(form.value.inboundTime.getDate()).padStart(2, '0')
            const hours = String(form.value.inboundTime.getHours()).padStart(2, '0')
            const minutes = String(form.value.inboundTime.getMinutes()).padStart(2, '0')
            const seconds = String(form.value.inboundTime.getSeconds()).padStart(2, '0')
            inboundTimeStr = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
        } else {
            inboundTimeStr = form.value.inboundTime
        }
    }

    // 构建提交数据
    const submitData = {
        allocId: props.rowData?.allocId, // 记录ID
        cameraId: props.rowData?.cameraId || props.rowData?.id, // 球机ID
        cameraNo: form.value.cameraNo, // 球机编号
        warehouse: form.value.warehouse, // 入库仓库
        inboundTime: form.value.inboundTime ? dayjs(form.value.inboundTime).format('YYYY-MM-DD') : dayjs().format('YYYY-MM-DD'), // 入库时间，如果没有选择则使用当前时间
        keeper: form.value.keeper || '', // 入库管理员
        returnIds: props.rowData?.returnId ? [props.rowData.returnId] : [] // 从表格中的returnId获取
    }
    console.log("传递参数", submitData)

    submitting.value = true
    try {
        const response = await approveInventoryAudit(submitData)
        if (response.code === 200) {
            ElMessage.success('确认入库成功')
            emit('refresh') // 触发父组件刷新列表
            handleClose()
        } else {
            ElMessage.error(response.msg || '确认入库失败')
        }
    } catch (error) {
        console.error('确认入库失败:', error)
        ElMessage.error('确认入库失败，请稍后重试')
    } finally {
        submitting.value = false
    }
}

</script>

<style scoped>
.inspection-details,
.storage-info {
    margin-bottom: 24px;
}

.inspection-details h3,
.storage-info h3 {
    margin-bottom: 16px;
    font-size: 16px;
    font-weight: bold;
}

.camera-photo {
    text-align: center;
    padding: 20px;
    border: 1px solid #e6e6e6;
    border-radius: 4px;
}

.camera-photo img {
  max-width: 100%;
  height: auto;
  border-radius: 4px;
}

.no-photo {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 200px;
  color: #909399;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.info-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.info-item {
  display: flex;
  align-items: center;
  padding: 8px 0;
}

.info-item label {
  width: 100px;
  font-weight: 500;
  color: #606266;
}

.info-item span {
  flex: 1;
  color: #303133;
  margin-left: 12px;
}

.Cneter-box {
    height: 600px;
    padding: 10px;
    box-sizing: border-box;
    overflow: auto;
}

.project-info,
.camera-selection,
.allocation-info {
    margin-bottom: 24px;
}

.project-info h3,
.camera-selection h3,
.allocation-info h3 {
    margin-bottom: 16px;
    font-size: 16px;
    font-weight: bold;
}

.info-item {
    margin-bottom: 12px;
}

.info-item label {
    display: inline-block;
    width: 120px;
    font-weight: 500;
}

.delivery-address {
    margin-top: 16px;
}

.delivery-address label {
    display: block;
    margin-bottom: 8px;
    font-weight: 500;
}
</style>
