<script setup lang="ts">
import {
	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
}

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 = () => {
	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)) {
				ElMessage.warning('已存在相同的SN，不能添加')
				return
			}
			data.snItems.unshift({...data.fromData, T_sn: extractedSN})
			data.fromData.T_sn = ''
			ElMessage.success('已添加到待提交列表')
			if ('speechSynthesis' in window) {
				const utterance = new SpeechSynthesisUtterance('添加成功')
				window.speechSynthesis.speak(utterance)
			} else {
				console.warn('Web Speech API 不被支持')
			}
		}
	})
}

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

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" @keyup.enter="submitForm"></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>
