<template>
	<view class="container">
		<view class="header">
			<text style="color: white;padding: 20px;font-size: 16px;">欢迎使用展会选样系统</text>
		</view>
		<scroll-view class="scroll-view" scroll-y="true">
			<view class="content">
				<u--form labelPosition="left" :model="baseData" ref="uForm" labelWidth='40' :rules="rules"
					:errorType="errorType">
					<u-form-item left-icon="../../static/meeting.png" leftIconStyle="width:60rpx;height:60rpx"
						prop="exhibitionName" borderBottom @click="">
						<u--input v-model="baseData.exhibitionName" placeholder="请输入展会名称" border="none"></u--input>
					</u-form-item><u-form-item left-icon="../../static/customer.png"
						leftIconStyle="width:60rpx;height:60rpx" prop="customerName" borderBottom @click="">
						<u--input v-model.trim="baseData.customerName" :focus="focus" placeholder="请输入客户名称"
							border="none"></u--input>
					</u-form-item><u-form-item left-icon="../../static/receiver.png"
						leftIconStyle="width:60rpx;height:60rpx" prop="receiver" borderBottom @click="">
						<u--input v-model.trim="baseData.receiver" placeholder="请输入接待人姓名" border="none"></u--input>
					</u-form-item>
					<u-form-item prop="exhibitionNote" borderBottom @click="">
						<u--textarea :confirmType="null" v-model="baseData.exhibitionNote" placeholder="展会备注信息"></u--textarea>
					</u-form-item>
					<uni-section  required>
						<uni-file-picker v-model="baseData.fileList" :image-styles="imageStyles"
							:source-type="['album', 'camera']" @select="handleFileSelect" @delete="handleDelete"
							ref="filePicker"><view style="color: #c0c4cc ;font-size: 15px;">上传图片</view>
						</uni-file-picker>

					</uni-section>
					<u-button style="margin-top: 5px;" @click="handleSave" type="primary" color="#253a6f"
						text="开始选样"></u-button>
				</u--form>
			</view>
		</scroll-view>
	</view>
</template>
<script>
	import {
		openSqlite,
		executeSql,
		closedb,
		getTable,
		isTable,
		getAllField,
		insertAll,
		addSql,
		getPageList,
		selectList,
		deleteSql,
		updateSql,
		selectSql,
		batchUpdate
	} from "@/utils/database";
	export default {
		data() {
			return {
				tableName: "public",
				baseData: {
					uid: '',
					exhibitionName: '',
					customerName: '',
					receiver: '',
					exhibitionNote: "",
					fileList: [],
				},
				errorType: 'toast',
				focus: false,
				rules: {
					exhibitionName: [{
						required: true,
						message: '请输入展会名称',
						// trigger: ['blur', 'change']
					}],
					customerName: [{
						required: true,
						message: '请输入客户名称',
						// trigger: ['blur', 'change']
					}],
					receiver: [{
						required: true,
						message: '请输入接待人姓名',
						// trigger: ['blur', 'change']
					}]
				},
				imageStyles: {
					border: {
						color: "#dadbde",
						width: 1,
						style: '',
						radius: '2px'
					}
				},
				shouldExecuteOnShow: true

			};
		},
		async onShow(options) {
			// pointblur() {
			// 	this.focus = false
			// 	this.$nextTick(() => {
			// 		this.focus = true
			// 	})
			// },
			/**
			 * 数据库设置名称 在 database.js 文件中
			 */
			// console.log("所有表名称",await getTable())
			// 默认打开数据库,并创建表
			await this.openSqlite()
			await this.createTable()
			await this.createDetailTable()
			console.log(uni.getDeviceInfo())
			// console.log('应该执行onshow', this.shouldExecuteOnShow)
			// if (this.shouldExecuteOnShow) {
			// 	// 执行onShow逻辑
			// 	console.log('页面显示了');
			// 	let self = this
			// 	uni.getStorage({
			// 		key: 'exhibitionName',
			// 		success: function(res) {
			// 			console.log(res.data)
			// 			self.baseData.exhibitionName = res.data
			// 		}
			// 	});
			// 	uni.getStorage({
			// 		key: 'receiver',
			// 		success: function(res) {
			// 			self.baseData.receiver = res.data
			// 			self.focus = false
			// 			self.$nextTick(() => {
			// 				self.focus = true
			// 			})
			// 		}
			// 	});
			// 	this.baseData.customerName = ''
			// } else {
			// 	// 不执行onShow逻辑
			// 	// this.shouldExecuteOnShow = true; // 重置标志位
			// }

			// if(this.baseData.exhibitionName!==''&& this.baseData.receiver!==''){

			// }
		},
		onUnload() {
			console.log('程序退出了')
		},
		onLoad() {

			let self = this
			uni.getStorage({
				key: 'exhibitionName',
				success: function(res) {
					console.log(res.data)
					self.baseData.exhibitionName = res.data
				}
			});
			uni.getStorage({
				key: 'receiver',
				success: function(res) {
					if(res.data == '')return
					self.baseData.receiver = res.data
					self.focus = false
					self.$nextTick(() => {
						self.focus = true
					})
				}
			});
			this.baseData.customerName = ''
			this.baseData.exhibitionNote = ''
			this.baseData.fileList = []
			uni.$on('refreshData', () => {
				console.log('执行返回代码')
				// 调用列表接口
				this.initData();
			})
			// console.log(plus.io.convertLocalFileSystemURL('_HBuilder/'))
			// console.log(plus.io.convertLocalFileSystemURL('_doc/'))
		},
		methods: {
			initData() {
				let self = this
				uni.getStorage({
					key: 'exhibitionName',
					success: function(res) {
						console.log(res.data)
						self.baseData.exhibitionName = res.data
					}
				});
				uni.getStorage({
					key: 'receiver',
					success: function(res) {
						self.baseData.receiver = res.data
						self.focus = false
						self.$nextTick(() => {
							self.focus = true
						})
					}
				});
				this.baseData.customerName = ''
				this.baseData.exhibitionNote = ''
				this.baseData.fileList = []

			},
			async openSqlite() {
				// 打开数据库
				try {
					let b = await openSqlite()
					// uni.showToast({
					// 	title: "打开数据库成功",
					// 	icon: "none"
					// })
				} catch (e) {
					console.error("打开数据库，报错", e)
				}
			},
			// 创建表
			async createTable() {
				let sql = this.createTableSql_outbound()
				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)
				}
			},
			async createDetailTable() {
				let sql = this.createTableSql_detail()
				try {
					let exist = await isTable('detail')
					console.log("表是否存在", exist)
					if (!exist) {
						let res = await executeSql(sql)
						uni.showToast({
							title: "新增数据表成功",
							icon: "none"
						})
						console.log("新增表detail", res)
					} else {
						// uni.showToast({
						// 	title: "数据表已存在",
						// 	icon: "none"
						// })
					}
				} catch (e) {
					uni.showToast({
						title: "新增数据表失败",
						icon: "none"
					})
					console.error("新增表报错ord_storage_order", e)
				}
			},
			/**
			 * 创建表， 仅供参考
			 * @returns {string}
			 * 因为java后台用的id，所以这里用fid 作为自增id
			 */

			createTableSql_outbound() {
				return "CREATE TABLE IF NOT EXISTS `public` (" +
					"  `id` INTEGER PRIMARY KEY AUTOINCREMENT," +
					"  `uid` varchar(20) DEFAULT NULL ," +
					"  `exhibitionName` varchar(50) DEFAULT NULL ," +
					"  `customerName` varchar(50) DEFAULT NULL ," +
					"  `receiver` varchar(50) DEFAULT NULL ," +
					"  `exhibitionNote` varchar(500) DEFAULT NULL ," +
					"  `fileSavePath` varchar(2000) DEFAULT NULL ," +
					"  `editUser` varchar(50) DEFAULT NULL ," +
					"  `createTime` datetime DEFAULT CURRENT_TIMESTAMP ," +
					"  `updateTime` datetime DEFAULT NULL default(datetime('now','localtime')) ," +
					"  `deleted` char(1) DEFAULT '0' ," +
					"  `uploaded` char(1) DEFAULT '0' " +
					"); "
			},
			createTableSql_detail() {
				return "CREATE TABLE IF NOT EXISTS `detail` (" +
					"  `id` INTEGER PRIMARY KEY AUTOINCREMENT," +
					"  `publicId` varchar(20) NOT NULL ," +
					"  `barCode` varchar(50) NOT NULL ," +
					"  `bpQuantity` INT  NOT NULL ," +
					"  `gyQuantity` INT  NOT NULL ," +
					"  `myQuantity` INT  NOT NULL ," +
					"  `note` varchar(500) DEFAULT NULL ," +
					"  `fileSavePath` varchar(2000) DEFAULT NULL ," +
					"  `createTime` TEXT  DEFAULT NULL default(datetime('now','localtime')) ," +
					"  `updateTime` TEXT  DEFAULT NULL default(datetime('now','localtime')) ," +
					"  `deleted` char(1) DEFAULT '0' " +
					"); "
			},
			// 更新表字段
			async addProp() {
				// 更新app时，可以增加字段
				try {
					// let res = await executeSql(`ALTER TABLE public ADD uploaded char(1) DEFAULT '0'`)
					let res2 = await executeSql(`ALTER TABLE public ADD editUser varchar(50) DEFAULT NULL`)
					// console.log("增加字段", res)
					console.log("增加字段", res2)
					uni.showToast({
						title: "新增字段成功",
						icon: "none"
					})
				} catch (e) {
					uni.showToast({
						title: "字段已存在，或者未打开数据库，或者数据表不存在",
						icon: "none"
					})
				}
			},
			handleFileSelect(e) {
				this.shouldExecuteOnShow = false; // 选择图片后，将标志位设置为 false
				console.log(e.tempFiles)
				const self = this
				this.handleSaveImages(e)
					.then(e => {
						console.log('returneeeee', e);
						self.baseData.fileList = self.baseData.fileList.concat(e.tempFiles)
						console.log('fileList', self.baseData.fileList)
						// console.log('selectImages', this.selectedImages)
						// this.images = base64Images;
						// this.baseFormData.FPicture1 = this.images[0]
						// this.baseFormData.FPicture2 = this.images.length > 1 ? this.images[1] : ''
						// this.baseFormData.FPicture3 = this.images.length > 2 ? this.images[2] : ''

						// const jsonData = JSON.stringify(this.baseFormData);
						// let data = {
						// 	usertoken: this.usertoken,
						// 	jsonData: jsonData
						// }
						// console.log(data)


					})
				// this.baseData.fileList.concat(e.tempFiles);
				// this.baseData.fileList = this.baseData.fileList.concat(e.tempFiles)
				// console.log(this.baseData.fileList)
			},
			// 定义一个异步函数上传图片
			async saveImage(filePath) {
				console.log(filePath)
				return new Promise((resolve, reject) => {
					uni.saveFile({
						tempFilePath: filePath,
						success: res => {
							console.log('文件保存成功', res);
							// self.fileSavePath.push(res.savedFilePath);
							// 执行上传成功后的操作
							// doSomethingAfterSaveFile();
							resolve(res.savedFilePath);
						},
						fail: err => reject(err)
					})
				});
			},
			async handleSaveImages(e) {
				console.log('eeee', e)
				for (const item of e.tempFiles) {
					console.log('bbbb', item)
					try {
						const trueurl = await this.saveImage(item.path);
						item.url = trueurl;
						console.log('item', item)

					} catch (error) {
						console.error(`Failed to convert image to Base64:`, error);
					}
				}
				return e

			},
			handleDelete(e) {
				this.baseData.fileList = this.baseData.fileList.filter(item => item.name !== e.tempFile.name);
				console.log('delete', this.baseData.fileList)
			},
			async getPublicCount() {
				try {
					let res = await selectSql('SELECT COUNT(*) FROM public;')
					console.log('count', res[0]['COUNT(*)'])
					return res[0]['COUNT(*)']

				} catch (e) {
					console.error("添加数据，报错", e)
				}

			},
			//获取设备序列号
			getSerialNumber() {
				var Build = plus.android.importClass("android.os.Build");
				var Manifest = plus.android.importClass("android.Manifest");
				var MainActivity = plus.android.runtimeMainActivity();
				var SystemProperties = plus.android.importClass("android.os.SystemProperties")
				var serial = ''
				if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { //9.0+
					var ArrPermissions = [
						Manifest.permission.READ_PHONE_STATE,
					];
			
					function PermissionCheck(permission) {
						if (Build.VERSION.SDK_INT >= 23) {
							if (MainActivity.checkSelfPermission(permission) == -1) {
								return false;
							}
						}
						return true;
					}
			
					function PermissionChecks(Arr) {
						var HasPermission = true;
						for (var index in Arr) {
							var permission = Arr[index];
							//如果此处没有权限,则是用户拒绝了
							if (!PermissionCheck(permission)) {
								HasPermission = false;
								break;
							}
						}
						return HasPermission;
					}
			
					function PermissionRequest(Arr) {
						var REQUEST_CODE_CONTACT = 101;
						if (Build.VERSION.SDK_INT >= 23) {
							MainActivity.requestPermissions(Arr, REQUEST_CODE_CONTACT);
						}
					}
					//如果没有权限，则申请权限
					if (!PermissionChecks(ArrPermissions)) {
						PermissionRequest(ArrPermissions); //此处申请权限，会弹出一个让你授权可获取设备号信息权限框
					} else { //如果拥有权限
						serial = Build.getSerial()
					}
				} else if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N) { //8.0+
					if (Build.SERIAL) {
						serial = Build.SERIAL;
					}
				} else {
					if (SystemProperties.get('ro.serialno')) {
						serial = SystemProperties.get('ro.serialno')
					}
				}
				console.log(123, serial)
				return serial
			},
			getUniqueId(count) {
				const formattedNumber = String(count).padStart(6, '0');
				console.log("设备序列号：",this.getSerialNumber())
				return this.getSerialNumber() + "-" + formattedNumber
			},

			async handleSave() {
				console.log(this.$refs['uForm'])
				this.$refs['uForm'].validate().then(async () => {
					// const uniqueId = Date.now().toString();
					// console.log(uni.getDeviceInfo().deviceId)
					let count = await this.getPublicCount()
					// console.log(count)
					const uniqueId = this.getUniqueId(count + 1)
					console.log(uniqueId)
					this.baseData.uid = uniqueId
					const urls = this.baseData.fileList.map(item => item.url);
					const fileSavePath = urls.join(',');
					// console.log(fileSavePath);
					try {
						let b = await addSql(this.tableName, {
							uid: uniqueId,
							exhibitionName: this.baseData.exhibitionName,
							customerName: this.baseData.customerName,
							receiver: this.baseData.receiver,
							exhibitionNote: this.baseData.exhibitionNote,
							fileSavePath: fileSavePath
						})
						const self = this
						uni.showToast({
							title: "添加成功",
							icon: "none",
							success: function() {
								uni.setStorage({
									key: 'exhibitionName',
									data: self.baseData.exhibitionName,

								});
								uni.setStorage({
									key: 'receiver',
									data: self.baseData.receiver,

								});
								uni.navigateTo({
									url: '/pages/collections/sample-collection-detail?uid=' +
										uniqueId
								});
							}
						});
					} catch (e) {
						console.error("添加数据，报错", e)
					}
				}).catch(errors => {
					console.log(errors)
					uni.$u.toast(errors[0].message)
				})

			}
		}
	}
</script>
<style>
	.container {
		position: relative;
		width: 100%;
		height: 100vh;
		overflow: hidden;
		background-color: #EDEDED
			/* 隐藏溢出内容，禁止滚动 */
	}

	.header {
		position: fixed;
		background-color: #253a6f;
		height: 170rpx;
		width: 100%;
		z-index: 1;

	}

	.scroll-view {
		position: absolute;
		left: 50%;
		top: 60%;
		transform: translate(-50%, -50%);
		width: 90%;
		height: 100%;
		overflow: auto;
		/* 设置滚动 */
		background-color: white;
		border-radius: 5px;
		/* border: 1px solid red; */
		padding: 0 20px;
		z-index: 999;

	}

	.content {
		width: 100%;
		margin-bottom: 50px;
	}
</style>