<template>
	<view class="container">
		<uni-nav-bar fixed :border="false" backgroundColor="#fff" title="常用联系人" :statusBar="true" left-icon="left"
		 @clickLeft="$navBack()" @clickRight="clickRight">
		 <!--  #ifndef MP-WEIXIN -->
			<template v-slot:right>
				<uni-icons type="plusempty" size="20"></uni-icons>
			</template>
		 <!-- #endif -->
		</uni-nav-bar>
		<scroll-view scroll-y="true" :style="{height: `calc(100vh - ${statusBarHeight} - 228rpx)`}">
			<view class="container-body">
				<myEmpty text="暂无联系人" v-show="$isEmpty(phoneList) || phoneList.length == 0"></myEmpty>
				<view class="list">
					<uni-swipe-action ref="swipeAction">
					<uni-swipe-action-item v-for="(item,idx) in phoneList" :key="idx" :right-options="options"
						@click="onClick(idx)">
						<view class="list-item border-line">
							<view class="list-item-left">
								<view class="item-name">{{item.name}}</view>
								<view class="item-phone">{{item.number}}</view>
							</view>
							<view :class="item.sos ? 'list-item-right active':'list-item-right'"
								@click="handleSOS(item)">紧急联系人</view>
						</view>
					</uni-swipe-action-item>
					</uni-swipe-action>
				</view>
				<view class="tipsbox" v-if="phoneList&&phoneList.length>0">
					<view class="tipsbox-title border-line">
						<text>禁止常用联系人以外的号码呼入</text>
						<mySwitch :value="forbid" inactiveColor="#f7f7f7" @change="onSwitchChange"></mySwitch>
					</view>
					<view class="tipsbox-desc">设备未开通来电显示的用户禁止开启</view>
				</view>
			</view>
		</scroll-view>
		<view class="footer">
			<button class="savebtn" :loading="btnLoading" :disabled="btnLoading" @click="handleSend">
				发送到手表
			</button>
			<!--  #ifdef MP-WEIXIN -->
			<view class="footer-add" @click="clickRight">新增联系人</view>
			<!-- #endif -->
		</view>
	</view>
</template>

<script>
	// #ifdef APP-PLUS
	import { nativeContact } from '@/utils/nativeContact';
	// #endif
	import { getSetUpInfoByDeviceId, syncPhonebook,clearPhonebook } from "@/api/pages_watch/index.js";
	import mySwitch from "/pages_watch/components/mySwitch/mySwitch.vue";
	import myEmpty from "@/pages_watch/components/myEmpty/myEmpty.vue";
	
	export default {
		components:{
			mySwitch,
			myEmpty
		},
		data() {
			return {
				statusBarHeight: uni.getSystemInfoSync().statusBarHeight + 'px',
				deviceId: "",
				btnLoading: false,
				phoneList: [],
				// 1 true拦截陌生来电, 2 false不拦截陌生来电。不传的时候不设置陌生来电拦截
				forbid: false,
				options: [{
					text: '删除',
					style: {
						backgroundColor: '#dd524d'
					}
				}],
			}
		},
		onLoad(option) {
			uni.$on('getSaveList', (data) => {
				if (this.$isLogin() && this.deviceId && data && data.length > 0) {
					this.phoneList = this.phoneList.concat(data)
				}
			})
			this.deviceId = uni.getStorageSync("deviceId") || ""
			if (this.$isLogin()) {
				if (this.deviceId) {
					this.getSetUpInfo()
				} else {
					console.log("set.vue ---- deviceId is undefined")
					// uni.showToast({
					// 	title: "deviceId不存在",
					// 	icon: "none"
					// })
				}
			} else {
				this.$showLoginPage()
			}
		},
		onShow() {
			if(this.$refs.swipeAction){
				this.$refs.swipeAction.closeAll()
			}
		},
		onUnload() {
			uni.$off("getSaveList")
		},
		methods: {
			getSetUpInfo() {
				getSetUpInfoByDeviceId({
					deviceId: this.deviceId
				}).then(res => {
					if (res.code == 200 && res.data) {
						this.forbid = res.data.phonebooks.forbid == 1 ? true : false
						this.phoneList = res.data.phonebooks.phoneList && res.data.phonebooks.phoneList.length >
							0 ? res.data.phonebooks.phoneList : []
					} else {
						uni.showToast({
							title: res.msg,
							icon: "none"
						})
					}
				})
			},
			clickRight() {
				uni.showActionSheet({
					// #ifdef H5
					itemList: ['创建联系人'],
					// #endif
					// #ifndef H5
					itemList: ['创建联系人','手机通讯录导入'],
					// #endif
					success: (res) => {
						if (res.tapIndex == 0) {
							const count = 8 - this.phoneList.length
							uni.navigateTo({
								url: "/pages_watch/index/equipment/editEmergencyContact?count=" + count
							})
						} else {
							// #ifdef MP-WEIXIN
							wx.chooseContact({
								success: res => {
									if(!this.phoneList.some(item=>item.number == res.phoneNumber)) {
										this.phoneList.push({
											name: res.displayName,
											number: res.phoneNumber,
											sos: false
										})
									}
								},
								fail: error => {
									console.log('weixin chooseContact error:',error);
								},
							});
							// #endif
							// #ifdef APP-PLUS
							nativeContact.contacts.getContact((name, number) => {
								if(!this.phoneList.some(item=>item.number == number)) {
									this.phoneList.push({
										name,
										number,
										sos: false
									})
								}
							});
							// #endif
						}
					},
					fail: function(res) {
						console.log(res.errMsg);
					}
				});
			},
			handleSOS(item) {
				item.sos = !item.sos
			},
			onClick(index) {
				uni.showModal({
					content: '是否删除选中的联系人',
					success: (res) => {
						if (res.confirm) {
							this.phoneList.splice(index, 1)
							this.$refs.swipeAction.closeAll()
						}
					}
				});
			},
			onSwitchChange(e) {
				this.forbid = e
			},
			handleSend() {
				if (this.phoneList && this.phoneList.length > 0 && this.phoneList.every(item => !item.sos)) {
					uni.showModal({
						content: '请先设置紧急联系人，否则无法使用手表SOS功能',
						showCancel: false,
					});
					return
				}
				uni.showLoading({
					title: ''
				});
				if(this.phoneList && this.phoneList.length > 0) {
					const param = {
						deviceid: this.deviceId,
						phoneList: this.phoneList,
						forbid: this.phoneList && this.phoneList.length == 0 ? 2 : this.forbid ? 1 : 2
					}
					syncPhonebook(param).then(res => {
						uni.hideLoading()
						if (res.code == 200) {
							uni.navigateBack()
						} else {
							uni.showToast({
								title: res.msg,
								icon: "none"
							})
						}
					}).catch(() => {
						uni.hideLoading()
					})
				} else {
					clearPhonebook({deviceId: this.deviceId}).then(res => {
						uni.hideLoading()
						if (res.code == 200) {
							uni.navigateBack()
						} else {
							uni.showToast({
								title: res.msg,
								icon: "none"
							})
						}
					}).catch(() => {
						uni.hideLoading()
					})
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.container-body {
		.list {
			background-color: #fff;

			&-item {
				height: 130rpx;
				padding: 24rpx;
				box-sizing: border-box;
				display: flex;
				align-items: center;
				justify-content: space-between;
				font-family: PingFang SC, PingFang SC;
				font-weight: 400;
				font-size: 28rpx;
				color: #333;

				&-right {
					height: 70rpx;
					padding: 0 30rpx;
					line-height: 70rpx;
					text-align: center;
					background-color: #f5f5f5;
					border-radius: 80rpx;
				}
			}

			.item-name {
				font-weight: 500;
				font-size: 32rpx;
			}

			.item-phone {
				margin-top: 10rpx;
				color: #999;
			}

			.active {
				background-color: #dd524d;
				color: #FFFFFF;
			}
		}

		.tipsbox {
			padding: 0 24rpx;
			margin: 32rpx 24rpx;
			border-radius: 20rpx;
			background-color: #e9e9eb;
			font-family: PingFang SC, PingFang SC;
			font-weight: 400;
			font-size: 28rpx;
			color: #333;

			&-title {
				padding: 24rpx 0;
				font-size: 32rpx;
				display: flex;
				align-items: center;
				justify-content: space-between;

				text {
					flex: 1;
					margin-right: 24rpx;
				}
			}

			.tipsbox-desc {
				padding: 24rpx 0;
			}
		}
	}

	.footer {
		width: 100%;
		height: 140rpx;
		padding: 0 24rpx;
		box-sizing: border-box;
		display: flex;
		flex-direction: row;
		align-items: center;
		justify-content: center;
		box-sizing: border-box;
		position: fixed;
		z-index: 99;
		bottom: var(--window-bottom);
		left: 0;

		.savebtn {
			flex: 1;
			max-width: 622rpx;
			height: 88rpx;
			line-height: 88rpx;
			border-radius: 44rpx 44rpx 44rpx 44rpx;
			background-color: #FF7700;
			font-family: PingFang SC, PingFang SC;
			font-weight: 500;
			font-size: 32rpx;
			color: #FFFFFF;
			margin: 0;
			&::after {
				border: none;
			}
		}
		.footer-add {
			flex: 1;
			height: 88rpx;
			margin-left: 20rpx;
			box-sizing: border-box;
			line-height: 88rpx;
			border-radius: 44rpx 44rpx 44rpx 44rpx;
			border: 2rpx solid #ECECEC;
			display: flex;
			flex-direction: row;
			align-items: center;
			justify-content: center;
			font-family: PingFang SC, PingFang SC;
			font-weight: 500;
			font-size: 32rpx;
			color: #FF7700;
			background-color: #fff;
		}
	}
</style>