<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>
						<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>
					<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'
	import { getRootpath,setRootpath } from '@/common/config.js'
	export default {
		data() {
			return {
				path:getRootpath(),
				baseInfo:{
				    syncTime:"",
					num:0	
				},
				isConnect: false,
				btnStyle: {
					"color": "#fff",
					'background': "#107fc9"
				},
				isSync:false,
			}
		},
		methods: {
			setPath(){
			    setRootpath(this.path)	
				
				setTimeout(()=>{
					this.testConnect()
				},100)
			},
			
			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 => {
					console.log(res);
					if(res.data.msg === '链接成功'){
						this.isConnect = true
					}else{
						this.isConnect = false
						uni.showToast({
							icon:'none',
							title:'连接失败'
						})
					}
				}).catch(err => {
					console.log(err);
					this.isConnect = false
					uni.showToast({
						icon:'none',
						title:'连接失败'
					})
				})
			},
			
			async getAllAssets(){
				if(!this.isConnect){
					uni.showToast({
						icon:'none',
						title:'连接服务器失败'
					})
					return
				}
				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 (assets_id,serial,name,position,worker_name,worker_id,content,assets_status) 
							values (
							${item.id},
							"${item.serial}",
							"${item.name}",
							"${item.position}",
							"${item.worker_name}",
							"${item.worker_id}",
							"${item.checks?.content || ''}",
							"${item.checks?.assets_status || ''}"
							);
						`)
					}
					await executeSql(`
					    COMMIT;
					`)
					//日志
					await executeSql(`
					    INSERT INTO log (remark) VALUES ("同步资产");
					`)
					
					//
					await this.getInitInfo();
					
					//获取工作人员
					let workers = await this.$u.api.worker()
					//先清空表
					await executeSql(`
					    DELETE from worker;
					`)
					await executeSql(`
					    UPDATE sqlite_sequence SET seq = 0 where name = 'worker';
					`)
					//插入表
					await executeSql(`
					    BEGIN;
					`)
					for(let i = 0;i < workers?.data?.data?.length;i++){
						let item = workers?.data?.data[i]
						await executeSql(`
						    insert into worker (id,name) 
							values (
							${item.id},
							"${item.name}"
							);
						`)
					}
					await executeSql(`
					    COMMIT;
					`)
					//日志
					await executeSql(`
					    INSERT INTO log (remark) VALUES ("同步人员");
					`)
					
					// #ifdef APP-PLUS
					androidModule.showToast(`获取到${this.baseInfo.num}条资产`)
					this.isSync = false
					uni.hideLoading()
					// #endif
					
					uni.$emit('assetsSync',{msg:'success'})
				}catch(err){
					console.warn('sqlite-err',err)
					androidModule.showToast(err)
					this.isSync = false
				}	
			}
		},
		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>
