<template>
	<page-meta><navigation-bar :title="$tt('linkDevice.linkDevice')" title-align="center" background-color="#007AFF" /></page-meta>
	<view class="container">
		<u--form labelWidth="100" labelAlign="left">
			<view class="card" v-for="(item, index) in form.deviceNumberAndProductIds" :key="index">
				<view style="display:flex;justify-content: flex-start;">
					<u-button type="error" :text="$tt('common.delete')" icon="minus-circle" size="small" customStyle="width:70px;margin:0;" v-if="index != 0" @click="removeDeviceNumber(index)"></u-button>
					<u-button type="primary" :text="$tt('common.add')" icon="plus-circle" size="small" customStyle="width:70px;margin:0;" v-if="index == 0" @click="addDeviceNumber"></u-button>
					<u-button
						type="success"
						:text="$tt('linkDevice.scan')"
						icon="scan"
						size="small"
						customStyle="margin-left:20px;width:90px;"
						@click="openScan(form.deviceNumberAndProductIds[index])"
					></u-button>
				</view>
				<u-form-item :label="$tt('linkDevice.deviceNum')"><u-input v-model="form.deviceNumberAndProductIds[index].deviceNumber" :placeholder="$tt('linkDevice.inputDeviceId')"></u-input></u-form-item>
				<u-form-item :label="$tt('linkDevice.productNum')"><u-input v-model="form.deviceNumberAndProductIds[index].productId" :placeholder="$tt('linkDevice.inputProductId')"></u-input></u-form-item>
				<u-form-item :label="$tt('linkDevice.productName')"><u-input v-model="form.deviceNumberAndProductIds[index].productName" disabled :placeholder="$tt('linkDevice.product')"></u-input></u-form-item>
			</view>
		</u--form>

		<view class="card">
			<view style="display:flex;">
				<u-button type="warning" @click="goBack" customStyle="margin:10px;">{{$tt('common.back')}}</u-button>
				<u-button type="primary" @click="submitForm" customStyle="margin:10px;">{{$tt('common.save')}}</u-button>
			</view>
		</view>

		<u-modal :show="modal.show" :content="modal.content" @confirm="confirm"></u-modal>
	</view>
</template>

<script>
import { deviceRelateUser } from '@/apis/modules/device';
export default {
	data() {
		return {
			// 模态窗
			modal: {
				show: false,
				content: ''
			},
			// 表单内容
			form: {
				deviceNumberAndProductIds: [
					{
						deviceNumber: '',
						productId: null,
						productName: ''
					}
				],
				userId: null
			}
		};
	},
	created() {
		//获取登录用户信息
		if (this.profile == null) {
			this.getProfile();
		} else {
			this.form.userId = this.profile.userId;
		}
	},
	onUnload() {},
	methods: {
		// 获取登录用户信息
		getProfile() {
			// 调用用户信息接口
			this.$api.common
				.getProfile()
				.then(res => {
					//存储用户信息,TODO 需要调用一次，不然其他页面调用返回空
					uni.$u.vuex('profile', res.data);
					this.profile;
					this.form.userId = this.profile.userId;
				})
				.catch(err => {
					this.$u.toast(err.msg);
				});
		},
		// 添加一项
		addDeviceNumber() {
			this.form.deviceNumberAndProductIds.push({ deviceNumber: '', productId: null, productName: '' });
		},
		// 移除一项
		removeDeviceNumber(index) {
			this.form.deviceNumberAndProductIds.splice(index, 1);
		},
		// 返回
		goBack() {
			getApp().globalData.operate = 'operate';
			uni.navigateBack({
				delta: 1
			});
		},
		// 模态窗取消
		confirm() {
			this.modal = {
				show: false,
				content: ''
			};
		},
		// 全部保存
		submitForm() {
			if (this.form.userId == null || this.form.userId == 0) {
				uni.showToast({ icon: 'none', title: this.$tt('linkDevice.userName') });
				return;
			}
			for (let i = 0; i < this.form.deviceNumberAndProductIds.length; i++) {
				if (this.form.deviceNumberAndProductIds[i].deviceNumber == '') {
					uni.showToast({ icon: 'none', title: this.$tt('linkDevice.deviceEmpty') });
					return;
				}
				if (this.form.deviceNumberAndProductIds[i].productId == null || this.form.deviceNumberAndProductIds[i].productId == 0) {
					uni.showToast({ icon: 'none', title: this.$tt('linkDevice.productIdEmpty') });
					return;
				}
			}
			deviceRelateUser(this.form).then(res => {
				if (res.code == 200) {
					uni.showToast({ icon: 'success', title: this.$tt('common.saveSuccessful') });
					setTimeout(() => {
						this.goBack();
					}, 1000);
				} else {
					this.modal = {
						show: true,
						content:res.msg
					};
				}
			});
		},
		// 扫码
		openScan(item) {
			// #ifndef MP-WEIXIN || APP-PLUS
			uni.showToast({
				icon: 'none',
				title: this.$tt('user.scanning')
			});
			return;
			// #endif

			// 允许从相机和相册扫码
			uni.scanCode({
				success: res => {
					console.log('条码类型：' + res.scanType);
					console.log('条码内容：' + res.result);
					if (res.result.substr(0, 1) != '{') {
						console.log('坑点：解析二维码后第一个位置包含一个特殊字符，大部分编译器和调试工具识别不了这个特殊字符');
						res.result = res.result.substring(1);
					}
					// 解析JSON
					try {
						let json = JSON.parse(res.result);
						// type=1 代表扫码关联设备
						if (json.type == 1) {
							item.deviceNumber = json.deviceNumber;
							item.productId = json.productId;
							item.productName = json.productName;
							return;
						}
						uni.showToast({ icon: 'none', title: this.$tt('linlDevice.format') });
					} catch (error) {
						uni.showToast({ icon: 'none', title: this.$tt('linlDevice.format') });
					}
				}
			});
		}
	}
};
</script>

<style lang="scss">
page {
	background: #eef3f7;
}
.container {
	padding-bottom: 50px;
}
.card {
	box-shadow: 0 1px 0px 0 rgba(0, 0, 0, 0.1);
	border-radius: 6px;
	background-color: #fff;
	margin: 10px;
	padding: 10px;
}
</style>
