<template>
    <el-form-item label="年份批次">
        <div style="display: flex; gap: 8px; align-items: center;">
            <!-- <el-select v-model="selectedYear" clearable placeholder="请选择年份" style="width: 80px">
                <el-option v-for="year in yearList" :key="year" :label="year" :value="year"/>
            </el-select> -->
            <el-select v-model="localBatchId" clearable placeholder="请选择批次" style="width: 157px">
                <el-option v-for="b in filteredBatchList" :key="b.batchId" :label="formatBatchName(b)" :value="b.batchId"/>
            </el-select>
            <el-button type="primary" @click="handleAddBatch">新增</el-button>
        </div>
    </el-form-item>
    
    <!-- 新增批次弹窗 -->
    <el-dialog v-model="batchDialogVisible" title="新增批次" width="500px" append-to-body>
        <el-form ref="batchFormRef" :model="batchForm" :rules="batchRules" label-width="80px">
            <el-form-item label="年份" prop="year">
                <el-input-number v-model="batchForm.year" :min="2000" :max="2100" placeholder="请输入年份" style="width: 100%"/>
            </el-form-item>
            <el-form-item label="批次" prop="name">
                <el-input v-model="batchForm.name" placeholder="请输入批次名称" maxlength="100"/>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="batchDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="handleSaveBatch" :loading="batchSaving">保 存</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup>
import { ref, watch } from 'vue'
import { useBatchYear } from '@/views/dz/papers/hooks/useBatchYear.js'

const props = defineProps({
    batchId: {
        required: false,
        default: null
    },
    batchList: {
        required: false,
        default: null
    }
})

const emit = defineEmits(['update:batchId'])

// 创建本地 ref，用于双向绑定
// 注意：在 Vue 3 中，当父组件传递 ref 时，Vue 会自动解包，所以 props.batchId 是值，不是 ref
const localBatchId = ref(props.batchId)
const localBatchList = ref(Array.isArray(props.batchList) ? props.batchList : [])

// 监听 props 变化，同步到本地 ref
watch(() => props.batchId, (val) => {
    if (localBatchId.value !== val) {
        localBatchId.value = val
    }
}, { immediate: true })

watch(() => props.batchList, (val) => {
    const listValue = Array.isArray(val) ? val : []
    localBatchList.value = listValue
}, { immediate: true, deep: true })

const {
    selectedYear,
    yearList,
    filteredBatchList,
    batchDialogVisible,
    batchFormRef,
    batchSaving,
    batchForm,
    batchRules,
    handleAddBatch,
    handleSaveBatch,
    formatBatchName
} = useBatchYear(localBatchId, localBatchList)

// 监听 localBatchId 的变化，同步回父组件
watch(localBatchId, (val) => {
    emit('update:batchId', val)
})
</script>

<style scoped>
</style>
