<script setup lang="ts">
import {
	readValidation,
	validation_add,
	validation_repair,
	validation_scrap,
} from '@/api/storehouse'
import {computed, nextTick, reactive, ref} from 'vue'
import type {FormInstance} from 'element-plus'
import {ElMessage} from 'element-plus'

const outerVisible = ref(false)

const submitFormRef = ref<FormInstance | null>(null)


const pageSize = ref(8)
const currentPage = ref(1)

const rulesrepaid = reactive({
	T_sn: [{required: true, message: '请输入SN', trigger: 'blur'}]
})

const extractSN = (fullSN: string): string => {
	if (fullSN.length === 24 && fullSN.startsWith('03') && fullSN.endsWith('000001')) {
		return fullSN.substring(2, 18)
	}
	return fullSN
}

/**
 * 处理SN输入，自动提取中间数据并更新输入框显示
 */
const handleSNInput = () => {
	if (data.fromData.T_sn) {
		const extractedSN = extractSN(data.fromData.T_sn)
		// 如果提取的SN与原始SN不同，说明需要自动处理
		if (extractedSN !== data.fromData.T_sn) {
			data.fromData.T_sn = extractedSN
		}
	}
}

/**
 * 处理键盘按下事件，专门处理扫码枪的回车事件
 */
const handleKeyDown = (event: KeyboardEvent) => {
	// 专门处理扫码枪的回车事件
	if (event.key === 'Enter') {
		// 阻止页面跳转和刷新
		event.preventDefault()
		event.stopPropagation()
		
		// 如果是在SN输入框中，触发提交逻辑
		if (event.target instanceof HTMLInputElement && event.target.placeholder === '请输入SN') {
			// 延迟执行，确保输入完成
			setTimeout(() => {
				submitForm()
			}, 500)
		}
		return false
	}

}

const handlePageChange = (page: number) => {
	currentPage.value = page
}

const data:any = reactive({
	title: '',
	snItems: [],
	fromData: {
		T_sn: '',
		Validationnumber: '',
		T_remark: '',
	},
})


const paginatedItems = computed(() => {
	if (data.snItems.length === 0) {
		return
	}
	const start = (currentPage.value - 1) * pageSize.value
	const end = start + pageSize.value
	return data.snItems.slice(start, end)
})

const removeItem = (index: number) => {
	data.snItems.splice(index, 1)
	ElMessage.success('已从待提交列表中移除')
}

const resetForm = () => {
	data.snItems = [];
	data.fromData.T_sn = '';
	emit('successFun', true);
	nextTick(() => {
		outerVisible.value = false;
	});
}

const submitItems = async () => {
	if (data.snItems.length === 0) {
		ElMessage.warning('暂无数据可提交')
		return
	}
	console.log("=========",data)
	const rest = JSON.parse(JSON.stringify(data.snItems))

		switch (data.title) {
			case '维修':
				const repairResult: any = await validation_repair(rest)
				if (repairResult.Code == 200) {
					ElMessage.success('提交成功')
					resetForm()
				} else {
					ElMessage.error('提交失败')
				}
				break
			case '报废':
				const scrapResult: any = await validation_scrap(rest)
				if (scrapResult.Code == 200) {
					ElMessage.success('提交成功')
					resetForm()
				} else {
					ElMessage.error('提交失败')
				}
				break
			case '归还':
				const returnResult: any = await validation_add(rest)
				if (returnResult.Code == 200) {
					ElMessage.success('提交成功')
					resetForm()
				} else {
					ElMessage.error('提交失败')
				}
				break
			default:
				ElMessage.error('未知操作类型');
				break;
		}

}


const submitForm = (event?: Event) => {
	// 阻止默认的表单提交行为
	if (event) {
		event.preventDefault()
		event.stopPropagation()
	}
	submitFormRef.value?.validate(async (valid: boolean) => {
		if (valid) {
			const extractedSN = extractSN(data.fromData.T_sn)
			if (data.snItems.some((item: any) => item.T_sn === extractedSN)) {
				data.fromData.T_sn = ''
				ElMessage.warning('已存在相同的SN，不能添加')
				if ('speechSynthesis' in window) {
					const utterance = new SpeechSynthesisUtterance('重复添加')
					window.speechSynthesis.speak(utterance)
				} else {
					console.warn('Web Speech API 不被支持')
				}
				return
			}
			// 1-已出库 2-待使用(已入库)  3-维修中 4-已报废
			if (data.title == '归还' ) {
				const result: any = await readValidation({sn: extractedSN})
				if (result.Code !== 200) {
					data.fromData.T_sn = ''
					ElMessage.warning('查询SN失败！')
					return
				}
				if (result.Data.T_state == 2) {
					ElMessage.error(`当前SN ${extractedSN} 已入库！`)
					data.fromData.T_sn = ''
					return
				}
				if (result.Data.T_state == 5) {
					ElMessage.warning('设备已损坏')

					if ('speechSynthesis' in window) {
						const utterance = new SpeechSynthesisUtterance('设备已损坏')
						window.speechSynthesis.speak(utterance)
					} else {
						console.warn('Web Speech API 不被支持')
					}
				}
			}
			data.fromData.T_sn = ''
			data.snItems.unshift({...data.fromData, T_sn: extractedSN})
			ElMessage.success('已添加到待提交列表')
			if ('speechSynthesis' in window) {
				const utterance = new SpeechSynthesisUtterance('添加成功')
				window.speechSynthesis.speak(utterance)
			} else {
				console.warn('Web Speech API 不被支持')
			}
			data.snItems.value = data.snItems.value.filter((value:any, index:any, self:any) => {  //去重
				return self.findIndex((t:any) => (t.T_sn === value.T_sn)) === index;
			});


		}
	})
}

// ------------- 维修结束

const emit = defineEmits<{ (event: 'successFun', value:boolean): void }>()

defineExpose({
	outerVisible, data
})
</script>

<template>
	<div class="">
		<el-dialog :title="data.title" v-model="outerVisible" width="50%" draggable destroy-on-close>
			<el-form :model="data.fromData" :rules="rulesrepaid" ref="submitFormRef">
				<el-form-item label="SN" prop="T_sn">
					<el-input 
						v-model="data.fromData.T_sn" 
						placeholder="请输入SN" 
						submitForm
						@keyup.enter.prevent="submitForm"
						@keydown.enter.prevent
						@input="handleSNInput"
					></el-input>
				</el-form-item>
				<el-form-item label="备注">
					<el-input v-model="data.fromData.T_remark" type="textarea" placeholder="请输入备注"></el-input>
				</el-form-item>
			</el-form>
			<!-- 新增数据条数提示 -->
			<div style="margin: 10px 0">
				<span>当前待提交数据条数: {{ data.snItems.length }}</span>
			</div>
			<el-table :data="paginatedItems" style="width: 100%; margin-top: 20px">
				<el-table-column type="index" label="序号" width="80"></el-table-column>
				<!-- 添加序号列 -->
				<el-table-column prop="T_sn" label="SN"></el-table-column>
				<el-table-column prop="T_remark" label="备注"></el-table-column>
				<el-table-column label="操作" width="180">
					<template #default="scope">
						<el-button type="danger" size="small" @click="removeItem(scope.$index)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>
			<el-pagination
				background
				layout="prev, pager, next"
				:total="data.snItems.length"
				:page-size="pageSize"
				:current-page="currentPage"
				@current-change="handlePageChange"
				style="margin-top: 20px; text-align: right"
			/>
			<template #footer>
      <span class="dialog-footer">
        <el-button @click="outerVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">添加到暂存</el-button>
		  <!-- 新增提交按钮 -->
        <el-button type="primary" @click="submitItems">提交</el-button>
      </span>
			</template>
		</el-dialog>
	</div>
</template>
