<template>
	<view class="contact_choose_container">
		<uni-nav-bar 
			left-icon="back" 
			@clickLeft="uni.$u.route({type:'back'})"
			statusBar
			title="联系人">
			<template v-slot:right>
				<u-button type="primary" size="mini" @click="confirm" :disabled="!isConfirmEnable">确定</u-button>
			</template>
		</uni-nav-bar>
		<view class="search_bar_wrap">
			<u-search shape="square" placeholder="搜索" :showAction="false" v-model="keyword" />
		</view>

		<view class="tab_container">
			<template v-if="activeTab === 0">
                <div @click="tabChange(tabs[0].idx)" style="display: flex; align-items: center;justify-content: space-between;padding: 20rpx 40rpx;">
                    {{ tabs[0].title }}
                    <u-icon name="arrow-right" />
                </div>
				<view class="tab_pane">
					<template v-for="cell in conversationList">
						<template v-if="cell.groupID && type!='Invite'">
							<user-item 
								v-if="allowGroup"
								@itemClick="updateCheckedUserOrGroup"
								@updateCheck="updateCheckedUserOrGroup"
								:checked="checkedGroupIDList.includes(cell.groupID)" 
								:disabled="disabledGroupIDList.includes(cell.groupID)"
								:checkVisible="muitple" 
								:item="cell" :key="cell.groupID" />
						</template>
						<template v-if="cell.userID && !cell.userID.startsWith('system')">
							<user-item 
								@itemClick="updateCheckedUserOrGroup"
								@updateCheck="updateCheckedUserOrGroup"
								:checked="checkedUserIDList.includes(cell.userID)" 
								:disabled="disabledUserIDList.includes(cell.userID)"
								:checkVisible="muitple" 
								:item="cell" :key="cell.userID" />
						</template>
					</template>
				</view>
			</template>

			<template v-else>
				<view class="tab_pane" v-show="activeTab === 1">
					<choose-index-list 
						@updateCheck="updateCheckedUser" 
						:indexList="getChooseData.indexList"
						:itemArr="getChooseData.dataList" 
						:checkedIDList="checkedUserIDList"
						:disabledIDList="disabledUserIDList" 
						:showCheck="muitple" />
				</view>
			</template>
		</view>
	</view>
</template>

<script>
	import { mapGetters } from "vuex";
	import {ContactChooseTypes} from "@/constant";
	import {formatChooseData,toastWithCallback} from "@/util/common";
	import IMSDK from "openim-uniapp-polyfill"
	import UserItem from "@/components/UserItem/index.vue";
	import ChooseIndexList from "@/components/ChooseIndexList/index.vue";
	import ChooseIndexFooter from "@/components/ChooseIndexFooter/index.vue";

	export default {
		components: {
			UserItem,
			ChooseIndexList,
			ChooseIndexFooter
		},
		data() {
			return {
				keyword: "",
				type: ContactChooseTypes.Card,
				activeTab: 0,
				groupID: "",
				checkedUserIDList: [],
				disabledUserIDList: [],
				checkedGroupIDList: [],
				disabledGroupIDList: [],
				comfirmLoading: false,
				tabs: [
					{
						idx: 1,
						title: "我的好友",
					}, 
				],
				muitple:true,
				allowGroup:true,
			};
		},
		computed: {
			...mapGetters(["storeCurrentUserID","storeFriendList","storeConversationList",'storeCurrentConversation']),
			getChooseData() {
				const _this = this;
				let list = [...this.storeFriendList];
				list = list.filter((item)=>{
					return !item.userID.startsWith('system') && !item.userID.startsWith('official_team') && item.userID !== this.storeCurrentUserID
				});
				if(!this.allowGroup){
					list = list.filter((item)=>{
						return !item.groupID
					});
				}
				if (this.keyword) {
					return {
						indexList: ["#"],
						dataList: [
							list.filter(
								(friend) =>
								friend.nickname.includes(this.keyword) ||
								friend.remark.includes(this.keyword)
							),
						],
					};
				}
				return formatChooseData(list);
			},
			
			conversationList(){
				const _this = this;
				let list = [...this.storeConversationList];
				list = list.filter((item)=>{
					return !item.userID.startsWith('system') && !item.userID.startsWith('official_team') && item.userID !== this.storeCurrentUserID
				});
				if(!this.allowGroup){
					list = list.filter((item)=>{
						return !item.groupID
					});
				}
				if(this.keyword){
					list = list.filter((item)=>{
						return item.showName.indexOf(_this.kw)>-1 || item.userID.indexOf(_this.kw)>-1 || item.groupID.indexOf(_this.kw)>-1
					})
				}
				return list;
			},
			getCheckedUserInfo() {
				const tmpUserIDList = [...this.checkedUserIDList];
				const checkedFriends = this.storeFriendList.filter((friend) => {
					const idx = tmpUserIDList.findIndex(
						(userID) => userID === friend.userID
					);
					if (idx > -1) {
						tmpUserIDList.splice(idx, 1);
					}
					return idx > -1;
				});
				return [...checkedFriends];
			},
			getCheckedGroupInfo() {
				const tmpGroupIDList = [...this.checkedGroupIDList];
				const checkedGroups = this.storeConversationList.filter((item) => {
					const idx = tmpGroupIDList.findIndex(
						(groupID) => groupID === item.groupID
					);
					if (idx > -1) {
						tmpGroupIDList.splice(idx, 1);
					}
					return idx > -1;
				});
				return [...checkedGroups];
			},
			isConfirmEnable(){
				if(this.checkedUserIDList.length){
					return true;
				}
				if(this.allowGroup){
					if(this.checkedGroupIDList.length){
						return true;
					}
				}
				return false;
			}
		},
		onLoad(options) {
			const {groupID,type,checkedUserIDList,muitple,allowType} = options;
			this.type = type;
			if(allowType){
				this.allowGroup = allowType === 'All';
			}
			this.groupID = groupID;
			if(muitple){
				this.muitple = muitple;
			}
			this.checkedUserIDList = checkedUserIDList ? JSON.parse(checkedUserIDList) : [];
			if (this.type === ContactChooseTypes.Invite) {
				this.allowGroup = false;
				this.checkDisabledUser();
			}
		},
		methods: {
			checkDisabledUser() {
				const friendIDList = this.storeFriendList.map((friend) => friend.userID);
				IMSDK.asyncApi("getUsersInGroup", IMSDK.uuid(), {
					groupID: this.groupID,
					userIDList: friendIDList,
				}).then(({data}) => {
					this.disabledUserIDList = data;
				});
			},
			tabChange(idx) {
				this.keyword = "";
				this.activeTab = idx;
			},
			updateCheckedUserOrGroup(item) {
				if (item.userID) {
					this.updateCheckedUser(item);
				}
				if (item.groupID) {
					this.updateCheckedGroup(item);
				}
			},
			updateCheckedGroup({groupID}) {
				if(!this.muitple){
					this.checkedGroupIDList = [groupID];
					this.confirm();
				}else{
					if (this.checkedGroupIDList.includes(groupID)) {
						const idx = this.checkedGroupIDList.findIndex((item) => item === groupID);
						const tmpArr = [...this.checkedGroupIDList];
						tmpArr.splice(idx, 1);
						this.checkedGroupIDList = [...tmpArr];
					} else {
						this.checkedGroupIDList = [...this.checkedGroupIDList, groupID];
					}
				}
			},
			updateCheckedUser({userID}) {
				if(!this.muitple){
					this.checkedUserIDList = [userID];
					this.confirm();
				}else{
					if (this.checkedUserIDList.includes(userID)) {
						const idx = this.checkedUserIDList.findIndex((item) => item === userID);
						const tmpArr = [...this.checkedUserIDList];
						tmpArr.splice(idx, 1);
						this.checkedUserIDList = [...tmpArr];
					} else {
						this.checkedUserIDList = [...this.checkedUserIDList, userID];
					}
				}
			},
			confirm() {
				const _this = this;
				//console.log(this.checkedUserIDList,this.checkedGroupIDList);
				//return false;
				// if (this.activeTab) {
				// 	this.activeTab = 0;
				// 	return;
				// }
				this.comfirmLoading = true;
				if (this.type === ContactChooseTypes.GetList || this.type === ContactChooseTypes.ShareCard) {
					try{
						let pages = getCurrentPages();
						let prevPage = pages[pages.length - 2];
						if(prevPage.$vm.getCheckedUsers){
							prevPage.$vm.getCheckedUsers(this.getCheckedUserInfo,this.getCheckedGroupInfo);
						}else{
							const eventChannel = this.getOpenerEventChannel();
							eventChannel.emit('onSelectedConfirm', this.getCheckedUserInfo,this.getCheckedGroupInfo);
						}
					}catch(e){
						
					}
					this.comfirmLoading = false;
					uni.navigateBack({
						delta: 1,
					});
					return;
				}
				if (this.type === ContactChooseTypes.Invite) {
					console.log(_this.getCheckedUserInfo,_this.groupID);
					IMSDK.asyncApi(IMSDK.IMMethods.InviteUserToGroup, IMSDK.uuid(), {
							groupID: _this.groupID,
							reason: "",
							userIDList: _this.getCheckedUserInfo.map((user) => user.userID),
						})
						.then(() => {
							toastWithCallback("操作成功", () => uni.navigateBack());
							_this.comfirmLoading = false;
						})
						.catch((e) => {
							console.log(e);
							toastWithCallback("操作失败")
						});
					return;
				}

				this.comfirmLoading = false;
			},
		},
		onBackPress() {
			if (this.activeTab) {
				this.activeTab = 0;
				return true;
			}
			return false;
		},
	};
</script>

<style lang="scss" scoped>
	::v-deep.u-popup {
		flex: none;
	}

	.contact_choose_container {
		min-height: 100vh;
		display: flex;
		flex-direction: column;

		.search_bar_wrap {
			height: 34px;
			padding: 12px 22px;
		}

		.tab_container {
			@include colBox(false);
			flex: 1;

			.setting_item {
				padding: 32rpx 36rpx;
			}

			.title {
				height: 60rpx;
				display: flex;
				justify-content: flex-start;
				align-items: center;
				// padding: 16rpx 8rpx;
				background: #f8f9fa;
				color: #8e9ab0;
				font-size: 24rpx;
			}

			.tabs_bar {
				@include vCenterBox();
				justify-content: space-evenly;

				.tab_item {
					@include colBox(false);
					align-items: center;

					image {
						width: 50px;
						height: 50px;
					}
				}
			}

			.tab_pane {
				display: flex;
				flex-direction: column;
				flex: 1;
				overflow: hidden;
				overflow-y: scroll;

				.member_list {
					flex: 1;
					height: 80% !important;

					::v-deepuni-scroll-view {
						max-height: 100% !important;
					}
				}

				.user_list {
					height: 100% !important;
				}

				.member_anchor {
					background-color: #f8f8f8 !important;
					border: none !important;
				}
			}
		}
	}
</style>