<template>
	<view @touchstart="refreshStart" @touchmove="refreshMove" @touchend="refreshEnd">
		<refresh ref="refresh" @isRefresh='isRefresh'></refresh>
		<mSearch :mode="2" button="inside" @search="setSearch($event)" ></mSearch>
		<scroll-view scroll-y="true" style="height:1000upx" @scrolltolower="scrolltolower" show-scrollbar="true">
			<view class="cu-list menu-avatar margin-top">
				<view class="cu-item" :class="modalName=='move-box-'+ index?'move-cur':''"  v-for="(item,index) in deviceList" :key="index"
				@touchstart="ListTouchStart" @touchmove="ListTouchMove" @touchend="ListTouchEnd" :data-target="'move-box-' + index">
					<image src="/static/lora.png" class="cu-avatar round lg"></image>
					<view class="content padding-tb-sm">
						<view>
							<text class="text-lg">{{item.devEUI}}</text> 
						</view>
						<view class="flex">
							<text class="flex-sub text-df text-black">{{item.devAddr}}</text>
							<text class="flex-sub text-df text-grey">{{item.username}}</text>
						</view>
					</view>
					<view class="action">
						<view class="text-grey text-xs">{{item.createAt | dateFilter(true)}}</view>
						<view class="text-grey text-xs">{{item.createAt | dateFilter(false)}}</view>
					</view>
					<view class="move">
						<view class="bg-red" @click="handleDeleteItem(item.id,index)">删除</view>
					</view>
				</view>
			</view>
			<view v-if="offset >= total" style="text-align: center;">----------------底线----------------</view>
		</scroll-view>
		<uni-fab :pattern="pattern" :content="content" horizontal="right" vertical="bottom" direction="vertical" @trigger="trigger"></uni-fab>
	</view>
</template>

<script>
import refresh from '@/components/refresh/refresh.vue';
import mSearch from '@/components/mehaotian-search/mehaotian-search.vue';
import uniFab from '@/components/uni-fab/uni-fab.vue';
import { getDevice,postDevice,delDevice } from '@/api/device.js'; 

export default {
	components: {
		refresh,
		mSearch,
		uniFab
	},
	data() {
		return {
			deviceList: [],
			pattern: {
                color: '#7A7E83',
                backgroundColor: '#fff',
                selectedColor: '#007AFF',
                buttonColor:"#007AFF"
            },
			content: [
                {
                    iconPath: '/static/lora.png',
                    selectedIconPath: '/static/lora.png',
                    text: '添加终端',
                    active: false
                }
            ],
			userInfo: {},
			listTouchStart: 0,
			listTouchDirection: null,
			modalName: null,
			total: 0,
			offset: 0,
			pageNum: 1,
			limit: 10,
			query: ""
		};
	},
	onLoad(){
		this.getUserInfo();
		this.search(false);
	},
	filters:{
		dateFilter(msg,flag){
			const d = new Date(msg);
			if(flag){
				return d.format('yyyy/MM/dd')
			}else{
				return d.format('hh:mm:ss')
			}
		}
	},
	methods: {
		fetchDeviceList(content,limit,offset,isAppend){
			getDevice(content,limit,offset).then(response => {
				this.total = response.data.data.total
				if(isAppend){
					if(this.deviceList.length < this.total){
						this.deviceList.push(...response.data.data.result)
					}
				}else{
					this.deviceList = response.data.data.result
				}
			})
		},
		handleDeleteItem(id,index){
			delDevice(id).then(response => {
				if(response.data && response.data.code == 0){
					this.deviceList.splice(index, 1)
				}
			})
		},
		refreshStart(e) {
			this.$refs.refresh.refreshStart(e);
		},
		refreshMove(e){
			this.$refs.refresh.refreshMove(e);
		},
		refreshEnd(e) {
			this.$refs.refresh.refreshEnd(e);
		},
		isRefresh(){
			setTimeout(() => {
				this.search(false)
				uni.showToast({
				icon: 'success',
				title: '刷新成功'
				})
				this.$refs.refresh.endAfter() //刷新结束调用
			}, 1000)
		},
		setSearch(val) {
			this.query = val
			this.search(false)
		},
		search(isAppend){
			if(!isAppend){
				this.offset = 0
				this.pageNum = 1
			}
			this.fetchDeviceList(this.query,this.limit,this.offset,isAppend)
			this.pageNum ++
			this.offset = (this.pageNum - 1) * this.limit
		},
		getUserInfo() {
			uni.getUserInfo({
				provider: 'weixin',
				success: (result) => {
					this.userInfo = result.userInfo;
					console.log(result);
				},
				fail: (error) => {
					console.log('getUserInfo fail', error);
				}
			});
		},
		// ListTouch触摸开始
		ListTouchStart(e) {
			this.listTouchStart = e.touches[0].pageX
		},
		
		// ListTouch计算方向
		ListTouchMove(e) {
			this.listTouchDirection = this.listTouchStart - e.touches[0].pageX > 80 ? 'left' : 'right'
		},
		
		// ListTouch计算滚动
		ListTouchEnd(e) {
			if (this.listTouchDirection == 'left') {
				this.modalName = e.currentTarget.dataset.target
			} else {
				this.modalName = null
			}
			this.listTouchDirection = null
		},
		scrolltolower(e){
			if(this.offset >= this.total) {
				uni.showToast({
				icon: 'none',
				title: '已经到底啦'
				})
				return;
			}
			this.search(true)
		},
		trigger(e) {
			console.log(e);
			this.content[e.index].active = !e.item.active;
			const that = this
			uni.scanCode({
			    onlyFromCamera: true,
			    success: function (res) {
					console.log(res)
					if(res.scanType == 'QR_CODE' && res.result){
						const arr = res.result.split('|')
						if(arr.length >= 2){
							const dev = {devEUI:arr[0],devAddr:arr[1]}
							if(that.userInfo){
								dev.username = that.userInfo.nickName
							}
							postDevice(dev).then(response => {
								if(response.data){
									if(response.data.code == 0){
										that.search(false)
										uni.showToast({
										icon: 'success',
										title: '添加终端成功'
										})
									}else{
										uni.showToast({
										icon: 'none',
										title: '终端已存在'
										})
									}
								}
							})
						} 
					}
			    }
			});
        }
	}
};
</script>

<style>
	.content {
		margin-top: 10upx;
		width: 100%;
	}
</style>
