<template>
	<view>
		<u-navbar :is-back="false" title="数据上传" title-color="#fff" :background="{'background':'#107fc9'}"></u-navbar>

		<view class="content">
			<view class="img">
				<image :src="isConnect ? '/static/wifi.png' : '/static/no-wifi.png'" mode="widthFix"></image>
			</view>

			<u-card>
				<view slot="head">
					<view style="display: flex;align-items: center;">
						<span>当前连接地址：</span>
						<u-input border v-model="path"></u-input>
					</view>
					<u-button type="primary" @click="setPath" style="margin-top: 20rpx;">确认</u-button>
					<view class="status">
						<span class="status__label">服务器连接状态：</span>
						<span
							:class="isConnect ? 'status__value1' : 'status__value0'">{{ isConnect ? '已连接' : '未连接' }}</span>
					</view>
				</view>

				<view slot="body">
					<view class="time">
						<span class="time__label">上次上传时间：</span>
						<span class="time__value">{{baseInfo.syncTime}}</span>
					</view>

					<view class="num">
						<span class="num_label">本机离线盘点数据：</span>
						<span class="num_value">{{baseInfo.num}}</span>
					</view>
				</view>

				<view slot="foot">
					<u-button :disabled="isUpload" :ripple="true" :custom-style="btnStyle" @click="uploadClick">
						{{ isUpload ? "上传中" : "点击开始上传" }}</u-button>
				</view>
			</u-card>
		</view>

	</view>
</template>

<script>
	// #ifdef APP-PLUS
	let androidModule = uni.requireNativePlugin('uhfr')
	// #endif

	import {
		selectFromTable,
		executeSql
	} from '@/common/sqlite.js'
	import {
		ROOTPATH,
		setRootpath,
		getRootpath
	} from '@/common/config.js'
	export default {
		data() {
			return {
				path: getRootpath(),
				baseInfo: {
					syncTime: "",
					num: 0
				},
				isConnect: false,
				isUpload: false,
				btnStyle: {
					"color": "#fff",
					'background': "#107fc9"
				},
			}
		},
		methods: {
			setPath() {
				setRootpath(this.path)

				setTimeout(() => {
					this.testConnect()
				}, 100)
			},

			async uploadClick() {
				if (!this.isConnect) {
					uni.showToast({
						icon: 'none',
						title: '连接服务器失败'
					})
					return
				}
				try {
					let res = await selectFromTable(`
					    select assets_id,position,assets_status,photo,content,worker_id,name from property where is_check = 1;
					`)

					if (res.length === 0) {
						uni.showToast({
							icon: 'none',
							title: "本地无数据上传"
						})
						return
					}

					androidModule.showToast("开始上传...")
					this.isUpload = true

					for (let i = 0; i < res.length; i++) {
						if (res[i].photo) {
							let picRes = await uni.uploadFile({
								url: `${ROOTPATH}/index.php?s=/Home/Worker/upload.html`,
								filePath: res[i].photo,
								name: "file"
							})
							res[i].photo = picRes[1]?.data ? JSON.parse(picRes[1]?.data).data?.id : ""
						}
					}

					let promiseAll = res.map(item => {
						console.log('upload-data', res);
						return this.upload(item)
					})

					let result = await Promise.all(promiseAll)

					androidModule.showToast(`上传成功`)
					this.isUpload = false
					//将是否被盘点状态重置
					await executeSql(`
					    update property set is_check = 0 where is_check = 1;
					`)

					//插入日志
					await executeSql(`
					    INSERT INTO log (remark) VALUES ("数据上传");
					`)

					await this.getInitInfo()

					uni.$emit('uploadSuccess', {
						msg: 'success'
					})
				} catch (err) {
					console.warn('sqlite-err', err)
					androidModule.showToast(err)
					this.isUpload = false
				}
			},

			async getInitInfo() {
				let time;
				let num;
				try {
					time = await selectFromTable(`
					    SELECT * FROM log WHERE remark = "数据上传" ORDER BY created_at DESC;
					`)
					this.baseInfo.syncTime = time[0]?.created_at || ""
					num = await selectFromTable(`
					    SELECT count(*) as count FROM property WHERE is_check = 1;
					`)
					this.baseInfo.num = num[0]?.count || 0
				} catch (err) {
					console.warn('sqlite-err', err);
					androidModule.showToast(err)
				}
			},

			testConnect() {
				uni.showLoading({
					mask: true,
					title: '连接中',
				})
				this.$u.api.test().then(res => {
					uni.hideLoading()
					if (res.data.msg === '链接成功') {
						this.isConnect = true
					} else {
						this.isConnect = false
						uni.showToast({
							icon: 'none',
							title: '连接失败'
						})
					}
				}).catch(err => {
					uni.hideLoading()
					this.isConnect = false
					uni.showToast({
						icon: 'none',
						title: '连接失败'
					})
				})
			},

			upload(data) {
				return new Promise((resolve, reject) => {
					uni.request({
						url: `${ROOTPATH}/index.php?s=/Home/Worker/update_assets.html`,
						data,
						method: 'POST',
						header: {
							'Content-Type': 'application/x-www-form-urlencoded'
						},
						dataType: 'json',
						success: (response) => {
							resolve(response)
						},
						fail: (err) => {
							reject(err)
						}
					})
				})
			}
		},
		onShow() {
			this.testConnect()
			this.getInitInfo()
		}
	}
</script>

<style scoped lang="scss">
	.img {
		height: 400rpx;
		display: flex;
		justify-content: center;
		align-items: center;

		margin: 20rpx 32rpx;

		&>image {
			width: 280rpx;
		}
	}

	.status {
		text-align: center;

		padding: 40rpx 0;

		&__label {}

		&__value {
			color: #fff;
			background-color: green;
			border-radius: 14rpx;

			padding: 6rpx 10rpx;
		}

		&__value0 {
			color: #fff;
			background-color: red;
			border-radius: 14rpx;

			padding: 6rpx 10rpx;
		}

		&__value1 {
			color: #fff;
			background-color: green;
			border-radius: 14rpx;

			padding: 6rpx 10rpx;
		}
	}

	.time {
		@extend .status;

		padding: 20rpx 0;
	}

	.num {
		@extend .time;
	}
</style>
