<template>
	<view class="container">
		<view class="header">
			<view class="segmented-control-item" :class="{ 'active': activeTab === 0 }" @click="switchTab(0)">接待信息
				<view class="underline" v-show="activeTab === 0"></view>
			</view>
			<view class="segmented-control-item" :class="{ 'active': activeTab === 1 }" @click="switchTab(1)">选样扫描
				<view class="underline" v-show="activeTab === 1"></view>
			</view>
			<view class="segmented-control-item" :class="{ 'active': activeTab === 2 }" @click="switchTab(2)">选样列表
				<view class="underline" v-show="activeTab === 2"></view>
			</view>

		</view>

		<!-- <view class="absolute-element"> -->
		<scroll-view class="scroll-view" scroll-y="true">
			<!-- 根据 activeTab 显示不同的页面 -->
			<!-- <view v-if="activeTab === 0"> -->
			<view class="content" v-if="activeTab === 0">
				<u--form labelPosition="left" v-model="baseData" ref="uForm" labelWidth='40'>
					<u-form-item left-icon="../../static/logo.png" prop="" borderBottom @click="" ref="uItem">
						<u--input v-model.trim="baseData.exhibitionName" placeholder="请输入展会名称" border="none"></u--input>
					</u-form-item><u-form-item left-icon="../../static/logo.png" prop="" borderBottom @click=""
						ref="uItem">
						<u--input v-model.trim="baseData.customerName" placeholder="请输入客户名称" border="none"></u--input>
					</u-form-item><u-form-item left-icon="../../static/logo.png" prop="" borderBottom @click=""
						ref="uItem">
						<u--input v-model.trim="baseData.receiver" placeholder="请输入接待人姓名" border="none"></u--input>
					</u-form-item><u-form-item prop="" borderBottom @click="" ref="uItem">
						<u--textarea v-model="baseData.exhibitionNote" placeholder="展会备注信息"></u--textarea>
					</u-form-item>
					<uni-section title="添加图片" type="line" required>
						<uni-file-picker :value="baseData.fileList" :source-type="['album', 'camera']"
							@select="handleFileSelect" @delete="handleDelete" ref="filePicker">
						</uni-file-picker>
					</uni-section>
					<u-button style="margin-top: 5px;" @click="handleSave" type="primary" color="#253a6f"
						text="保存接待信息"></u-button>
				</u--form>
			</view>
			<view class="content" v-if="activeTab === 1">
				<u--form labelPosition="left" v-model="detailData" ref="uForm" labelWidth='40'>
					<u-form-item left-icon="../../static/logo.png" prop="" borderBottom @click="" ref="uItem">
						<u--input readonly v-model.trim="detailData.customerName" placeholder=""
							border="none"></u--input>
					</u-form-item><u-form-item left-icon="../../static/logo.png" prop="" borderBottom @click=""
						ref="uItem">
						<u--input type="text" v-model.trim="detailData.barCode" @confirm="getScanValue" :focus="focus"
							placeholder="样品条码序列号" border="none"></u--input>
					</u-form-item>
					<u-form-item left-icon="../../static/logo.png" prop="" borderBottom @click="" ref="uItem">
						<u--input type="text" v-model.trim="detailData.barCode" @confirm="getScanValue" :focus="focus"
							placeholder="样品条码序列号" border="none"></u--input>
						<u-button slot="right" type="primary" hairline size="small" @click="scan()">扫描条码</u-button>
					</u-form-item>
					<u-form-item left-icon="../../static/logo.png" prop="" borderBottom @click="" ref="uItem">
						<u--input type="number" v-model.trim="detailData.bpQuantity" placeholder="布片数量(默认为1)"
							border="none"></u--input>
					</u-form-item><u-form-item left-icon="../../static/logo.png" prop="" borderBottom @click=""
						ref="uItem">
						<u--input type="number" v-model.trim="detailData.gyQuantity" placeholder="挂样数量(默认为0)"
							border="none"></u--input>
					</u-form-item><u-form-item left-icon="../../static/logo.png" prop="" borderBottom @click=""
						ref="uItem">
						<u--input type="number" v-model.trim="detailData.myQuantity" placeholder="米样数量(默认为0)"
							border="none"></u--input>
					</u-form-item><u-form-item prop="" borderBottom @click="" ref="uItem">
						<u--textarea v-model="detailData.note" placeholder="样品备注信息"></u--textarea>
					</u-form-item>
					<uni-section title="添加图片" type="line" required>
						<uni-file-picker :value="detailData.fileList" :source-type="['album', 'camera']"
							@select="handleDetailFileSelect" @delete="handleDelete" ref="filePicker">
						</uni-file-picker>
					</uni-section>
					<u-button style="margin-top: 5px;" @click="handleSaveDetail" type="primary" color="#253a6f"
						text="保存选样"></u-button>
				</u--form>
			</view>
			<view v-if="activeTab === 2">
				<u-swipe-action>
					<u-swipe-action-item v-for="(item, index) in indexList" :options="options" @click="showDetail"
						:index="index" :key="index" :name="index">
						<view class="swipe-action u-border-top"
							:class="[index === indexList.length - 1 && 'u-border-bottom']">
							<view class="swipe-action__content" :style="item.msg ? 'background-color:red' : ''">
								<text class="swipe-action__content__text">包装号:{{ item.PackNO }}</text>
							</view>
						</view>
					</u-swipe-action-item>
				</u-swipe-action>
				<view class="card-bottom" style="">
					<view style="font-size: 14px;">
						<view>
							<uni-forms-item label="出货口" label-width="80px" required name="WarehouseGuid"
								style="padding: 0;margin: 0;">
								<uni-data-picker v-model="OutWarehousePort" :localdata="outWarehousePortList"
									@change="">
								</uni-data-picker>
							</uni-forms-item>
						</view>

						<view style="display: flex;">
							<button style="width: 100%;" type="primary" @click="delivery">准备出库</button>
							<button style="width:100%;" type="default" @click="queue">出库排队</button>
						</view>
						<!-- <button class="mini-btn" type="warn" size="mini" @click="cancelstorage" v-if="BillNO != null">入库</button> -->
						<!-- <button class="mini-btn" type="warn" size="mini">返回</button> -->
					</view>


				</view>


			</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: {},
				detailData: {
					barCode: '',
					bpQuantity: '',
					gyQuantity: '',
					myQuantity: '',
					note: "",
					fileList: [],
				},
				customStyle: {
					// marginTop: '20px', // 注意驼峰命名，并且值必须用引号包括，因为这是对象
					// color: 'red',
					border: '1px solid black'
				},
				focus: true,
				// baseData: {
				// 	exhibitionName: '',
				// 	customerName: '',
				// 	receiver: '',
				// 	exhibitionNote: "",
				// 	fileList: [],
				// },
				activeTab: 0, // 当前选中的页面索引
				imageUrl: 'file:///storage/emulated/0/Android/data/io.dcloud.HBuilder/apps/HBuilder/doc/uniapp_save/17049440506630.jpg',
				fileSavePath: []
			};
		},

		async onShow() {
			/**
			 * 数据库设置名称 在 database.js 文件中
			 */
			// console.log("所有表名称",await getTable())
			// 默认打开数据库,并创建表
			await this.openSqlite()
			await this.createTable()
			await this.createDetailTable()
		},
		computed: {

		},
		//获取上一页传过来的参数
		onLoad(option) {
			console.log(option.data)
			this.baseData = JSON.parse(decodeURIComponent(option.data));
			console.log(this.baseData.fileList)
			const dbPath = plus.io.convertLocalFileSystemURL('_doc/sample_storage.db');
			console.log(dbPath); // 输出类似"/storage/emulated/0/Android/data/com.example.myapp/files/database/test.db"的路径

		},
		methods: {
			getScanValue(event) {
				setTimeout(() => {
					console.log(this.detailData.barCode)
					// console.log(event)
					this.handleSaveDetail1()
				}, 500)
				// this.handleSaveDetail()
				// this.pointblur();
				// console.log('hahahha')
			},
			pointblur() {
				this.focus = false
				this.$nextTick(() => {
					this.focus = true
				})
			},
			//扫描设备二维码
			scan() {
				uni.scanCode({
					scanType: ['CODE_128'],
					success: qrcode => {
						let scanRedult = qrcode.result
						console.log(qrcode)
						// if (scanRedult.indexOf('/')>0) {
						// 	const scanResultArray = scanRedult.split('/')
						// 	let code = scanResultArray[1]
						// 	if(code.indexOf(':')>0){
						// 		code = code.substr(code.indexOf(':')+1)
						// 	}
						// 	this.model1.bill.equipmentCode = code
						// }else{
						// 	this.model1.bill.equipmentCode = scanRedult
						// }
						// if (this.isVerified) {
						// 	this.getEquipmentInfo()
						// }
					}
				})
			},
			handleFileSelect(e) {
				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)
					})

			},
			handleDetailFileSelect(e) {
				console.log(e.tempFiles)
				const self = this
				this.handleSaveImages(e) //上传图片
					.then(e => {
						console.log('returneeeee', e);
						self.detailData.fileList = self.detailData.fileList.concat(e.tempFiles)
						console.log('fileList', self.detailData.fileList)
					})

			},
			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

			},
			// 定义一个异步函数上传图片
			async saveImage(filePath) {
				console.log(filePath)
				return new Promise((resolve, reject) => {
					uni.saveFile({
						tempFilePath: filePath,
						success: res => {
							console.log('文件保存成功', res);
							resolve(res.savedFilePath);
						},
						fail: err => reject(err)
					})
				});
			},

			handleDelete(e) {
				console.log(e)
				// uni.removeSavedFile({
				// 	filePath: res.fileList[0].filePath,
				// 	complete: function(res) {
				// 		console.log(res);
				// 	}
				// });
				this.baseData.fileList = this.baseData.fileList.filter(item => item !== e.tempFile)
			},
			async handleSave() {
				// 修改数据
				// baseData: {
				// 	exhibitionName: '',
				// 	customerName: '',
				// 	receiver: '',
				// 	exhibitionNote: "",
				// 	fileList: [],
				// },
				const urls = this.baseData.fileList.map(item => item.url);
				// 使用 join 方法将剩余元素以逗号拼接为字符串
				const fileSavePath = urls.join(', ');
				console.log(fileSavePath);
				try {
					await updateSql(this.tableName, {
						exhibitionName: this.baseData.exhibitionName,
						customerName: this.baseData.customerName,
						receiver: this.baseData.receiver,
						exhibitionNote: this.baseData.exhibitionNote,
						fileSavePath: fileSavePath
					}, {
						uid: this.baseData.uid
					})
					const self = this
					uni.showToast({
						title: "修改成功",
						icon: "none",
						success: function() {
							self.detailData.customerName = self.baseData.customerName
							// showToast 弹窗关闭后执行跳转
							self.switchTab(1)
						}
					});
				} catch (e) {
					uni.showToast({
						title: "修改报错，请查看控制台",
						icon: "none"
					});
					console.error("修改报错", e)
				}
			},
			async handleSaveDetail1() {
				// 使用 map 方法提取需要的属性值
				const urls = this.detailData.fileList.map(item => item.url);
				// 使用 join 方法将剩余元素以逗号拼接为字符串
				const fileSavePath = urls.join(', ');
				console.log(fileSavePath); // 输出 "Alice, Charlie"
				try {
					// detailData: {
					// 	barCode: '',
					// 	bpQuantity: '',
					// 	gyQuantity: '',
					// 	myQuantity: '',
					// 	note: "",
					// 	fileList: [],
					// },
					let b = await addSql('detail', {
						publicId: this.baseData.uid,
						barCode: this.detailData.barCode,
						bpQuantity: this.detailData.bpQuantity || 1,
						gyQuantity: this.detailData.gyQuantity || 0,
						myQuantity: this.detailData.myQuantity || 0,
						note: this.detailData.note,
						fileSavePath: fileSavePath
					})
					const self = this
					uni.showToast({
						title: "添加成功",
						icon: "none",
						success: function() {
							self.detailData.barCode = ''
							self.pointblur()
							// showToast 弹窗关闭后执行跳转
							self.switchTab(1)
						}
					});
				} catch (e) {
					console.error("添加数据，报错", e)
				}
			},
			async handleSaveDetail() {
				// 使用 map 方法提取需要的属性值
				const urls = this.detailData.fileList.map(item => item.url);
				// 使用 join 方法将剩余元素以逗号拼接为字符串
				const fileSavePath = urls.join(', ');
				console.log(fileSavePath); // 输出 "Alice, Charlie"
				try {
					// detailData: {
					// 	barCode: '',
					// 	bpQuantity: '',
					// 	gyQuantity: '',
					// 	myQuantity: '',
					// 	note: "",
					// 	fileList: [],
					// },
					let b = await addSql('detail', {
						publicId: this.baseData.uid,
						barCode: this.detailData.barCode,
						bpQuantity: this.detailData.bpQuantity || 1,
						gyQuantity: this.detailData.gyQuantity || 0,
						myQuantity: this.detailData.myQuantity || 0,
						note: this.detailData.note,
						fileSavePath: fileSavePath
					})
					const self = this
					uni.showToast({
						title: "添加成功",
						icon: "none",
						success: function() {
							// showToast 弹窗关闭后执行跳转
							self.switchTab(2)
						}
					});
				} catch (e) {
					console.error("添加数据，报错", e)
				}
			},
			switchTab(index) {
				this.activeTab = index; // 切换页面
			},
			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("新增表ord_storage_order", res)
					} else {
						// uni.showToast({
						// 	title: "数据表已存在",
						// 	icon: "none"
						// })
					}
				} catch (e) {
					uni.showToast({
						title: "新增数据表失败",
						icon: "none"
					})
					console.error("新增表报错ord_storage_order", 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 ," +
					"  `createTime` datetime  DEFAULT NULL default(datetime('now','localtime')) ," +
					"  `updateTime` datetime DEFAULT NULL default(datetime('now','localtime')) ," +
					"  `deleted` 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 addData() {
				const uniqueId = Date.now().toString();
				const result = this.fileSavePath.join(','); // 使用逗号作为分隔符
				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: result
					})
					console.log('vvvvvv', b)
					uni.showToast({
						title: "添加成功",
						icon: "none"
					});
					this.switchTab(1)
				} catch (e) {
					console.error("添加数据，报错", e)
				}

			},

		},
	};
</script>

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

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


	/* 	.second-element {
		position: fixed;
		top: 170rpx;
		background-color: #253a6f;
		height: 100rpx;
		width: 100%;
	}

	.absolute-element {
		position: absolute;
		padding: 0 20px;
		width: 100%;
		top: 80px;

	} */

	.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: 100px;
		/* 此处设置滚动区域的内容样式 */
	}

	/* 	.segmented-control {
		display: flex;
		border-bottom: 1px solid #ccc;
	} */

	.segmented-control-item {
		flex: 1;
		text-align: center;
		padding: 10px;
		color: white;
	}

	/* 	.segmented-control-item.active {
		background-color: #ccc;
	} */
	.underline {
		bottom: 0;
		left: 0;
		width: 20%;
		height: 1px;
		background-color: white;
		/* 设置下划线的颜色 */
		display: none;
		margin: 0 auto;
	}

	.segmented-control-item.active .underline {
		display: block;
	}
	.card-bottom {
		touch-action: none;
	
		// height: 60px;
		position: fixed;
		bottom: 0;
		width: 100%;
		z-index: 999;
		background-color: white;
		border-top: 1px;
		display: flex;
		flex-direction: column;
	}
</style>