<template>
	<view>
		<u-navbar :is-back="false" title="资产扫码" title-color="#fff" :background="{'background':'#107fc9'}"></u-navbar>

		<view class="content">
			<u-swiper :list="list" :border-radius="0"></u-swiper>

			<u-button :ripple="true" :type="flag ? 'error' : 'primary'" :custom-style="{'margin':'20rpx 30rpx 0 30rpx'}"
				@click="scanClick">{{ flag ? "停止扫描" : "开始扫描" }}</u-button>

			<u-card title="资产列表" v-show="info.length > 0">
				<view slot="head" style="display: flex;justify-content: space-between;align-items: center;">
					<view style="flex: 1;">资产列表</view>
					<u-button size="medium" type="primary" @click="clear">清空</u-button>
				</view>
				<view class="card-body" slot="body">
					<view v-for="(item,index) in info" :key="item.id"
						style="display: flex;justify-content: space-between;padding: 10rpx 0;align-items: center;">
						<view style="flex:1">{{ item.name }}</view>
						<u-button :plain="true" size="medium" type="primary" @click="fund = item">选择
						</u-button>
					</view>
				</view>
			</u-card>

			<u-card title="资产信息">
				<view class="card-body" slot="body">
					<view class="info">
						<view class="info__name">名称：</view>
						<view class="info__value">{{fund.name || " "}}</view>
					</view>
					<view class="info">
						<view class="info__name">编号：</view>
						<view class="info__value">{{fund.serial || " "}}</view>
					</view>
					<view class="info">
						<view class="info__name">存放位置：</view>
						<view class="info__value">{{fund.position || " "}}</view>
					</view>
					<view class="info">
						<view class="info__name">保管人：</view>
						<view class="info__value">{{fund.worker_name || " "}}</view>
					</view>
					<view class="info">
						<view class="info__name">资产状态：</view>
						<view class="info__value">{{activeStatusFormat(fund.assets_status) || " "}}</view>
					</view>

					<u-button type="primary" :ripple="true" :custom-style="btnStyle" @click="isShowPop = true">
						盘 点
					</u-button>
				</view>

				<view class="card-footer" slot="foot">
					<view class="footer-title">盘点记录</view>
					<u-time-line>
						<u-time-line-item v-for="(item,index) in logs" :key="index">
							<!-- 此处没有自定义左边的内容，会默认显示一个点 -->
							<template v-slot:content>
								<view>
									<view class="u-order-desc">{{ item.remark }}</view>
									<view class="u-order-time">
										{{$moment(item.created_at).format('YYYY-MM-DD HH:mm:SS')}}
									</view>
								</view>
							</template>
						</u-time-line-item>
					</u-time-line>
				</view>
			</u-card>
		</view>

		<u-popup width="76%" v-model="isShowPop" mode="center" :border-radius="10">
			<view style="padding: 20rpx 40rpx;">
				<u-form :model="fund" ref="form" label-position="top">
					<u-form-item label="名称">
						<u-input disabled v-model="fund.name" placeholder="资产名称"></u-input>
					</u-form-item>
					<u-form-item label="盘点时间">
						<u-input disabled :value="$moment(new Date()).format('YYYY-MM-DD')" placeholder="盘点时间">
						</u-input>
					</u-form-item>
					<u-form-item label="存放位置" required>
						<u-input v-model="fund.position" placeholder="请输入存放位置">
						</u-input>
					</u-form-item>
					<u-form-item label="保管人">
						<u-input :value="activeWorkerFormat(fund.worker_id)" type="select"
							@click="isShowWorkerSelect = true" placeholder="请选择保管人"></u-input>
					</u-form-item>
					<u-form-item label="资产状态" required>
						<u-input :value="activeStatusFormat(fund.assets_status)" type="select"
							@click="isShowSelect = true" placeholder="请选择资产状态"></u-input>
					</u-form-item>
					<u-form-item label="备注">
						<u-input v-model="fund.content" type="textarea" :auto-height="true" placeholder="请输入备注">
						</u-input>
					</u-form-item>
					<u-form-item label="图片上传">
						<u-upload :show-progress="false" :auto-upload="false" :max-count="1" ref="uUpload"
							:file-list="fund.photo ? [{url:fund.photo}] : []">
						</u-upload>
					</u-form-item>
				</u-form>

				<view style="display: flex;margin-top: 20rpx;">
					<u-button type="primary" size="medium" @click="confirm">确认</u-button>
					<u-button size="medium" @click="isShowPop = false">
						取消</u-button>
				</view>
			</view>
		</u-popup>

		<u-select :list="statusList" v-model="isShowSelect" @confirm="e => fund.assets_status = e[0].value"></u-select>
		<u-select :list="workers" label-name="name" value-name="id" v-model="isShowWorkerSelect"
			@confirm="e => fund.worker_id = e[0].value"></u-select>
	</view>
</template>

<script>
	// #ifdef APP-PLUS
	let androidModule = uni.requireNativePlugin('uhfr')
	let receiver;
	let receiverQR;
	let timerQR;
	let main = plus.android.runtimeMainActivity();
	let intent = plus.android.importClass('android.content.Intent');
	// #endif

	import {
		openSqlite,
		isOpenSqlite,
		closeSqlite,
		executeSql,
		selectFromTable
	} from '@/common/sqlite.js'
	import {
		byteToString
	} from '@/common/util.js'
	import {
		ROOTPATH
	} from '@/common/config.js'
	export default {
		data() {
			return {
				isShowPop: false,
				isShowSelect: false,
				action: `${ROOTPATH}/index.php?s=/Home/Worker/upload.html`,
				statusList: [{
						value: 1,
						label: "正常"
					},
					{
						value: 2,
						label: "维修"
					}
				],

				isShowWorkerSelect: false,
				workers: [],

				btnStyle: {
					'margin': '60rpx 30rpx 0 30rpx'
				},
				list: [{
						image: '/static/1.jpg'
					},
					{
						image: '/static/2.jpg'
					},
					{
						image: '/static/3.jpg'
					}, {
						image: '/static/4.jpg'
					},
				],

				flag: 0, //当前扫码状态0未开始，1进行中
				fund: {
					assets_id: 0,
					name: '',
					serial: '',
					position: '',
					worker_name: '',
					worker_id: '',
					assets_status: '',
					photo: '',
					content: ''
				},
				rules: {
					position: [{
						required: true,
						message: "请输入存放位置"
					}],
					worker_name: [{
						required: true,
						message: "请输入保管人"
					}],
					assets_status: [{
						required: true,
						message: "请选择资产状态"
					}],
				},

				qrIdList: [],
				info: [],
				logs: []
			}
		},
		methods: {
			clear() {
				this.info = []
				this.fund = {
					assets_id: 0,
					name: '',
					serial: '',
					position: '',
					worker_name: '',
					worker_id: '',
					assets_status: '',
					photo: '',
					content: ''
				}
			},

			async getWorkers() {
				try {
					this.workers = await selectFromTable(`
					    select * from worker;
					`)
				} catch (err) {
					console.error('sql-err', err)
				}
			},

			async getLogs() {
				this.logs = await selectFromTable(`
				    select * from log where type = 1;
				`)
			},

			async confirm() {
				if (!this.fund.position || !this.fund.assets_status) {
					androidModule.showToast("请填写完整信息")
				}
				try {
					if (this.$refs.uUpload.lists[0]?.url) {
						const filePath = await uni.saveFile({
							tempFilePath: this.$refs.uUpload.lists[0]?.url
						})
						console.log(filePath);
						this.fund.photo = filePath[1]?.savedFilePath
					}
					await executeSql(`
					    update property set position = "${this.fund.position}",worker_id = ${this.fund.worker_id},assets_status = "${this.fund.assets_status}",content = "${this.fund.content}",is_check = 1${this.fund.photo ? ',photo = "' + this.fund.photo + '"' : '' } where assets_id = ${this.fund.assets_id};
					`)
					uni.showToast({
						icon: 'success',
						title: '本地保存成功'
					})
					this.isShowPop = false

					await executeSql(`
					    INSERT INTO log (remark,type) VALUES ('本地盘点:${this.fund.name}',1);
					`)

					await this.getLogs()
				} catch (err) {
					console.warn('sqlite-err', err)
					androidModule.showToast(err)
				}
			},

			listenRegist() {
				receiver = plus.android.implements('io.dcloud.feature.internal.reflect.BroadcastReceiver', {
					onReceive: (context, intent) => {
						plus.android.importClass(intent)
						let action = intent.getAction()
						switch (action) {
							case "com.rfid.SCAN":
								let id = byteToString(intent.getExtra("data"))
								this.qrIdList.push(id)
								break;
							case "android.rfid.FUN_KEY":
								let keydown = intent.getBooleanExtra("keydown", false);
								if (!keydown) {
									this.scanClick()
								}
								break;
						}
					}
				})
				let intentFilter = plus.android.importClass('android.content.IntentFilter')
				let filter = new intentFilter()
				filter.addAction("android.rfid.FUN_KEY")
				filter.addAction("com.rfid.SCAN")
				main.registerReceiver(receiver, filter)
			},

			init() {
				androidModule.initUhfrManage()

				//二维码扫描初始化
				let intentStart = new intent("com.rfid.SCAN_INIT")
				main.sendBroadcast(intentStart)
				let intentTime = new intent("com.rfid.SCAN_TIME")
				intentTime.putExtra("time", 1000)
				let intentBroad = new intent("com.rfid.SET_SCAN_MODE")
				intentBroad.putExtra("mode", 0)
				main.sendBroadcast(intentBroad)
			},

			async scanClick() {
				if (!this.flag) {
					this.flag = 1

					//二维码扫描
					this.qrIdList = []
					let intentScan = new intent("com.rfid.SCAN_CMD")
					timerQR = setInterval(() => {
						main.sendBroadcast(intentScan)
					}, 500)

					//rfid扫描
					androidModule.asyncStartReading()

				} else {
					this.flag = 0

					clearInterval(timerQR)

					//rfid标签盘点
					androidModule.asyncStopReading()

					androidModule.tagInventoryRealTime(async res => {
						let dataList = JSON.parse(res)

						const getSqlIn = () => {
							return Array.from(new Set([...dataList, ...this.qrIdList])).map(item => {
								return `"${item.replace(/^1(0+)/g,"")}"`
							}).toString()
						}
						try {
							let propertys = await selectFromTable(`
							  select * from property where assets_id in (${getSqlIn()});
							`)
							androidModule.showToast(
								`扫描到：${propertys.length}件资产，扫描到编号：${Array.from(new Set([...dataList, ...this.qrIdList])).toString()}`
								)
							this.info = propertys
							this.fund = propertys[0]
						} catch (e) {
							console.warn('sqlite-err', e);
							androidModule.showToast(err)
						}
					})
				}
			}
		},
		computed: {
			activeStatusFormat() {
				let map = new Map([
					[1, '正常'],
					[2, '维修'],
				])
				return function(status) {
					return map.get(status)
				}
			},
			activeWorkerFormat() {
				return function(worker_id) { 
					return this.workers.find(i => i.id == worker_id)?.name || ""
				}
			}
		},
		onLoad() {
			// #ifdef APP-PLUS
			this.init()
			this.listenRegist()
			// #endif
		},
		onUnload() {
			// #ifdef APP-PLUS
			//关闭二维码扫描
			let intentClose = new intent("com.rfid.CLOSE_SCAN")
			main.sendBroadcast(intentClose)

			androidModule.stopTagInventory()
			androidModule.close()
			main.unregisterReceiver(receiver)
			// #endif
		},
		onShow() {
		  	this.getWorkers();
		},
		mounted() {
			// #ifdef APP-PLUS
			try {
				this.getLogs()
			} catch (e) {
				console.warn('sqlite-err', e);
				androidModule.showToast(err)
			}
			// #endif

			uni.$on('uploadSuccess', () => {
				this.clear()
			})
			// uni.$on('assetsSync', async () => {
			// 	try {
			// 		await executeSql(`
			// 		    DELETE from log;
			// 		`)
			// 		await executeSql(`
			// 		    UPDATE sqlite_sequence SET seq = 0 where name = 'log';
			// 		`)
			// 	} catch (err) {

			// 	}
			// })
		},
		destroyed() {
			uni.$off()
		}
	}
</script>

<style lang="scss" scoped>
	::v-deep .u-drawer {
		z-index: 999 !important;
	}

	.info {
		display: flex;

		padding-bottom: 30rpx;

		&__name {
			white-space: nowrap;

			font-weight: bold;

		}

		&__value {
			overflow: hidden;
			text-overflow: ellipsis;
			white-space: nowrap;

			padding-left: 10rpx;
		}

		&:nth-last-child() {
			padding-bottom: 0;
		}
	}

	.footer-title {
		color: #303133;

		padding-bottom: 32rpx;
	}

	.u-order-desc {
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}
</style>
