<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 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="isSync" :ripple="true" :custom-style="btnStyle" @click="getAllAssets">{{ isSync ? "同步中..." : "点击开始同步" }}</u-button>
				</view>
			</u-card>
		</view>
	</view>
</template>

<script>
	// #ifdef APP-PLUS
	let androidModule = uni.requireNativePlugin('uhfr')
	// #endif
	
	import { executeSql,selectFromTable } from '@/common/sqlite.js'
	export default {
		data() {
			return {
				baseInfo:{
				    syncTime:"",
					num:0	
				},
				isConnect: false,
				btnStyle: {
					"color": "#fff",
					'background': "#107fc9"
				},
				isSync:false,
			}
		},
		methods: {
			
			async getInitInfo(){
				let time;
				let num;
				try{
					time = await selectFromTable(`
					    SELECT * FROM log WHERE remark = "同步资产" ORDER BY created_at DESC;
					`)
				}catch(err){
					console.warn('sqlite-err',err);
				}
				this.baseInfo.syncTime = time[0]?.created_at || ""
				try{
					num = await selectFromTable(`
					    SELECT count(*) as count FROM property;
					`)
				}catch(err){
					console.warn('sqlite-err',err);
				}
				this.baseInfo.num = num[0]?.count || 0
			},
			
			testConnect() {
				this.$u.api.test().then(res => {
					if(res.data.msg === '链接成功'){
						this.isConnect = true
					}else{
						this.isConnect = false
					}
				}).catch(err => {
					this.isConnect = false
				})
			},
			
			async getAllAssets(){
				if(!this.isConnect){
					uni.showToast({
						icon:'none',
						title:'连接服务器失败'
					})
					return
				}
				const getSql = () => {
					let sql = ""
					res.data?.forEach(item => {
						sql += `INSERT INTO property (id,serial,name,position,worker_name,remark) 
						VALUES (
						${item.id},
						${item.serial},
						${item.name},
						${item.position},
						${item.worker_name}),
						${item.remark}; `
					})
					return sql;
				}
				try{
					// #ifdef APP-PLUS
					androidModule.showToast("开始同步资产...")
					// #endif
					this.isSync = true
					let res = await this.$u.api.getAll()
					//先清空表
					await executeSql(`
					    DELETE from property;
					`)
					await executeSql(`
					    UPDATE sqlite_sequence SET seq = 0 where name = 'property';
					`)
					//插入表
					await executeSql(`
					    BEGIN;
					`)
					for(let i = 0;i < res?.data.length;i++){
						let item = res?.data[i]
						await executeSql(`
						    insert into property (id,serial,name,position,worker_name,active_status) 
							values (
							${item.id},
							"${item.serial}",
							"${item.name}",
							"${item.position}",
							"${item.worker_name}",
							${item.active_status}
							);
						`)
					}
					await executeSql(`
					    COMMIT;
					`)
					//日志
					await executeSql(`
					    INSERT INTO log (remark) VALUES ("同步资产");
					`)
					
					await this.getInitInfo();
					
					// #ifdef APP-PLUS
					androidModule.showToast(`获取到${this.baseInfo.num}条资产`)
					this.isSync = false
					uni.hideLoading()
					console.log(await selectFromTable(`select * from property;`));
					// #endif
					
					uni.$emit('assetsSync',{msg:'success'})
				}catch(err){
					console.warn('sqlite-err',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 {}

		&__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>
