<template>
	<view class="table-container">
		<!-- 查询框 -->
		<view class="container">
			<view class="search-container">
				<uni-easyinput type="text" v-model="stageNum" disabled class="custom-input" style="margin-right: 5px;">
				</uni-easyinput>
				<button class="search-button" @click="handleSave">保存</button>
			</view>
		</view>
		<!-- 表格容器 -->
		<scroll-view class="table-scroll" scroll-x="false" scroll-y>
			<!-- 表头 -->
			<view class="table-header" ref="tableHeader">
				<view class="table-cell">存档编号</view>
				<view class="table-cell header-cell">创建日期</view>
			</view>
			<!-- 表格内容 -->
			<view class="table-body">
				<checkbox-group @change="checkboxChange">
					<view class="table-row" v-for="(item, index) in list" :key="item.id">
						<view class="table-cell1">
							<view class="checkbox-container">
								<checkbox :value="item.stageNum" :checked="item.checked" />
							</view>
							<view>{{ item.stageNum}}</view>
						</view>
						<view class="table-cell header-cell">{{ item.createTime }}</view>
					</view>
				</checkbox-group>
			</view>
		</scroll-view>

		<view class="bottom-bar">
			<button class="mini-btn button" type="primary" size="default" @click="loadhandler">加载</button>
			<button class="mini-btn button" type="warn" size="default" @click="deletehandler">删除</button>
		</view>

	</view>
</template>
<script>
	import {
		playVoice,
		audioUrls
	} from '@/utils/audio2.js';
	import modal from '../../plugins/modal';
	import {
		showConfirm,
		toast
	} from '../../utils/common';
	import {
		addSql,
		deleteSql,
		executeSql,
		isTable,
		openSqlite,
		selectList,
		updateSql
	} from '../../utils/database';
	export default {
		data() {
			return {
				indexList: [],
				billSummary: [], // 这里存放处理后的每个 FBillNo 的统计结果
				selectedItemId: null,
				stageNum: '',
				tableName: "bill",
				list: [],
				selectedStage: [], // 保存每个数据项是否被选中的状态
				todayStages: []
			};
		},
		async onLoad(option) {
			await this.openSqlite()
			await this.createTable()
			await this.getBills()
			this.indexList = JSON.parse(decodeURIComponent(option.Info))
			console.log(this.indexList)
			if (this.indexList.length != 0) {
				this.stageNum = await this.generateStageNumber()
			}


		},

		async onShow(options) {
			// 默认打开数据库,并创建表
			// await this.openSqlite()
			// await this.createTable()
			// await this.createDetailTable()
			// console.log(uni.getDeviceInfo())
		},
		computed: {

		},
		mounted() { //隐藏返回按钮
			// let webView = this.$scope.$getAppWebview();
			// webView.setStyle({
			// 	titleNView: {
			// 		autoBackButton: false
			// 	}
			// })
		},
		methods: {
			async generateStageNumber() {
				if (this.hasMultipleDistinctBillNos(this.indexList)) { //有多个单据编号
					this.todayStages = await this.getTodayStages()
					console.log(this.generateDateWithNumber(this.todayStages.length + 1))
					return this.generateDateWithNumber(this.todayStages.length + 1)
				} else { //单个单据编号
					return this.indexList[0]["FBillNo"]
				}

			},
			generateDateWithNumber(numberPart) {
				const paddedNumberPart = String(numberPart).padStart(4, '0');
				const today = new Date();
				const year = today.getFullYear();
				const month = String(today.getMonth() + 1).padStart(2, '0');
				const day = String(today.getDate()).padStart(2, '0');
				const formattedDate = `${year}${month}${day}`;
				return `${formattedDate}${paddedNumberPart}`;
			},
			getTodayDate() {
				// 获取当前日期
				const today = new Date();

				// 格式化为 YYYY-MM-DD
				const year = today.getFullYear();
				const month = String(today.getMonth() + 1).padStart(2, '0'); // 月份从0开始，所以要加1
				const day = String(today.getDate()).padStart(2, '0');

				const formattedDate = `${year}-${month}-${day}`;
				return formattedDate
			},
			checkboxChange(e) {
				this.selectedStage = e.target.value
				console.log(this.selectedStage)
			},

			async getBills() {
				let where = {}
				this.list = await this.selectList(where)
				console.log(this.list)
			},
			async getTodayStages() {

				let where = {
					createTime: this.getTodayDate(),
				}
				const todayList = await this.selectList(where)
				return todayList

			},
			async selectList(where) {
				try {

					let res = await selectList(this.tableName, where)
					console.log("加载数据", res)
					return res
				} catch (e) {
					uni.showToast({
						title: "报错，请查看控制台",
						icon: "none"
					});
					console.error("报错", e)
				}
			},
			handleSaveSuccess() {
				this.getBills() //重新获取暂存数据
				modal.msgSuccess("存档成功")
				this.indexList = []
				this.stageNum = ''
				playVoice(audioUrls.warningSuccessUrl)
			},
			handleSaveFail(error) {
				modal.msgError(error)
				playVoice(audioUrls.failVoiceUrl)
			},
			handleDeleteSuccess() {
				this.getBills() //重新获取暂存数据
				modal.msgSuccess("删除成功")
				playVoice(audioUrls.warningSuccessUrl)
			},
			handleDeleteFail(error) {
				modal.msgError(error)
				playVoice(audioUrls.failVoiceUrl)
			},
			async editeStage() {
				try {
					await updateSql(this.tableName, {
						stageNum: this.stageNum,
						data: JSON.stringify(this.indexList),
						createTime: this.getTodayDate()
					}, {
						stageNum: this.stageNum
					})
					this.handleSaveSuccess()
				} catch (e) {
					this.handleSaveFail(e)
					console.error("修改报错", e)
				}
			},
			async addStage() {
				try {
					let b = await addSql(this.tableName, {
						stageNum: this.stageNum,
						data: JSON.stringify(this.indexList)
					})
					this.handleSaveSuccess()
				} catch (e) {
					this.handleSaveFail(e)
					console.error("添加数据，报错", e)
				}
			},
			async deleteStages() {
				const result = this.selectedStage.map(item => `"${item}"`).join(', ')
				let condition = `stageNum in (${result})`
				let sql = `delete from ${this.tableName} where ${condition}`
				executeSql(sql).then(result => {
						console.log('结果:', result);
						this.handleDeleteSuccess()
					})
					.catch(error => {
						console.error('捕获错误:', error); // 输出: 捕获错误: 失败的结果
						this.handleDeleteFail(error)
					})
			},
			async handleSave() {
				if (this.stageNum == '' || this.stageNum == undefined) { //是否有待暂存数据
					modal.msgError("请先提取数据")
					playVoice(audioUrls.failVoiceUrl)
					return
				}
				//存档前判断单据编号是否已暂存
				if (this.list.some(item => item.stageNum === this.stageNum)) { //若存在，提示是否覆盖
					showConfirm("存档编号已存在，是否覆盖").then(async (result) => {
						if (result) {
							console.log('用户点击了“确定”');
							this.editeStage() //覆盖已暂存数据
						} else {
							console.log('用户点击了“取消”');
							return
						}
					}).catch((error) => {
						console.error('对话框显示错误:', error)
					})
				} else { //若不存在，保存数据
					this.addStage()
				}
			},
			hasMultipleDistinctBillNos(data) {
				// 提取所有不同的 FBillNo 值
				const billNoSet = new Set(data.map(item => item.FBillNo))

				// 判断是否有多个不同的 FBillNo
				const hasMultipleBillNo = billNoSet.size > 1

				console.log('是否存在多个不同的 FBillNo:', hasMultipleBillNo)
				return hasMultipleBillNo
			},
			async openSqlite() {
				// 打开数据库
				try {
					let b = await openSqlite()
					// uni.showToast({
					// 	title: "打开数据库成功",
					// 	icon: "none"
					// })
				} catch (e) {
					console.error("打开数据库，报错", e)
				}
			},
			// 创建表
			async createTable() {
				let sql = this.createTableSqlBill()
				try {
					let exist = await isTable(this.tableName)
					console.log("表是否存在", exist)
					if (!exist) {
						let res = await executeSql(sql)
						uni.showToast({
							title: "新增数据表成功",
							icon: "none"
						})
						console.log("新增表public", res)
					} else {
						// uni.showToast({
						// 	title: "数据表已存在",
						// 	icon: "none"
						// })
					}
				} catch (e) {
					uni.showToast({
						title: "新增数据表失败",
						icon: "none"
					})
					console.error("新增表报错public", e)
				}
			},
			createTableSqlBill() {
				return "CREATE TABLE IF NOT EXISTS `bill` (" +
					"`id` INTEGER PRIMARY KEY AUTOINCREMENT," +
					"`stageNum` varchar(20) NOT NULL ," +
					"`data` text," +
					"`createTime` date DEFAULT CURRENT_DATE" +
					"); "
			},
			// onScroll(e) {
			// 	const scrollLeft = e.detail.scrollLeft;
			// 	this.headerLeft = -scrollLeft; // 更新表头左侧位置，实现横向滚动时的对齐效果
			// },
			loadhandler() {
				if (this.selectedStage.length == 0) {
					modal.msgError("请选择存档")
					playVoice(audioUrls.failVoiceUrl)
					return
				}
				console.log(this.list)
				// 筛选数据
				// const loadData = this.list.filter(item => this.selectedStage.includes(item.stageNum)).map(item => item
				// 	.data)
				const loadData = this.list.filter(item => this.selectedStage.includes(item.stageNum))
				console.log(loadData)

				uni.navigateBack({
					success: function() {
						// 传递数据给上一页
						uni.$emit('stage', loadData);
					}
				})
			},
			deletehandler() {
				if (this.selectedStage.length == 0) {
					modal.msgError("请选择存档")
					playVoice(audioUrls.failVoiceUrl)
					return
				}
				modal.confirm("确认删除选定的存档吗？").then(async (result) => {
					if (result) {
						console.log('用户点击了“确定”');
						//修改数据库数据
						this.deleteStages()
					} else {
						console.log('用户点击了“取消”');
						return
					}
				}).catch((error) => {
					console.error('对话框显示错误:', error)
				})
			}

		}
	};
</script>

<style>
	.table-container {
		width: 100%;
		height: 100%;
		display: flex;
		flex-direction: column;
	}

	.container {
		display: flex;
		flex-direction: column;
	}

	.search-container {
		display: flex;
		/* justify-content: flex-start; */
		align-items: center;
		/* 垂直居中 */
		flex-direction: row;
		/* align-items: stretch; */
		/* padding: 2px; */
		border-bottom: 1px solid #ccc;
		padding: 5px;
		/* flex-wrap: wrap; */
	}


	.search-button {
		/* padding: 8px 16px; */
		border: none;
		border-radius: 4px;
		background-color: #007bff;
		color: #fff;
		cursor: pointer;
	}

	.search-button:hover {
		background-color: #0056b3;
	}

	.table-scroll {
		/* position: absolute; */
		flex: 1;
		overflow-x: auto;
		overflow-y: hidden;
	}

	.table-header {
		position: sticky;
		top: 0;
		background-color: #f0f0f0;
		font-weight: bold;
		border-bottom: 1px solid #ccc;
		display: flex;
		z-index: 1;
		/* 确保表头在内容之上 */
	}

	.table-cell1 {
		min-width: 50%;
		display: flex;
		justify-content: left;
		align-items: center;
		border-right: 1px solid #ccc;
	}


	.table-cell {
		min-width: 50%;
		padding: 10px;
		display: flex;
		justify-content: center;
		align-items: center;
		border-right: 1px solid #ccc;
	}

	.header-cell {
		border-right: none;
		/* 取消最后一列的右边框 */
	}

	.table-body {
		flex: 1;
		/* width: fit-content; */
		/* 使内容宽度适应内容的宽度 */
	}

	.table-row {
		display: flex;
		border-bottom: 1px solid #ccc;
	}

	.checkbox {
		width: 100%;
		height: 100%;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.bottom-bar {
		display: flex;
		/* justify-content: center; */
		justify-content: flex-end;
		/* 将按钮靠右对齐 */
		align-items: center;
		padding: 3px;
		background-color: #f0f0f0;
	}

	.button {
		margin: 0 10px;
		/* padding: 10px 20px; */
	}


	::v-deep .is-disabled {
		color: black !important;
	}

	.checkbox-container {
		display: flex;
		align-items: center;
		margin-left: 10px;
		margin-right: 10px;
		/* 可根据需要调整间距 */
	}
</style>