<template>
	<view class="user_card_container">
		<u-loading-page :loading="isLoading" loading-text="loading..."></u-loading-page>
		<custom-nav-bar title="" />

		<view v-if="!isLoading" style="flex: 1; display: flex; flex-direction: column">
			<view class="base_info">
				<my-avatar :desc="sourceUserInfo.remark || sourceUserInfo.nickname" :src="sourceUserInfo.faceURL" size="46" />
				<view class="user_name">
					<text class="text">{{ getShowName }}</text>
					<text class="id" @click="copy(sourceUserInfo.userID)">{{ sourceUserInfo.userID }}</text>
				</view>
				<view class="add_btn" @click="toAddFriend" v-if="trySendRequest">
					<u-button type="primary" icon="man-add" text="添加"></u-button>
				</view>
			</view>

			<view v-if="memberInfo" class="info_row">
				<user-info-row-item lable="群昵称" :content="memberInfo.nickname" />
				<user-info-row-item lable="入群时间" :content="getJoinGroupTime" />
				<user-info-row-item lable="入群方式" :content="getJoinSource" />
			</view>

			<view v-if="!isSelf && (showSetRole || showSetMuteMember)" class="info_row">
				<user-info-row-item v-if="showSetRole" lable="设为管理员" arrow>
					<u-switch :loading="switchLoading" @change="changeMemberRole" :asyncChange="true" size="20" :value="isAdmin" />
				</user-info-row-item>
				<user-info-row-item v-if="showSetMuteMember" @click="toMuteMember" arrow lable="设置禁言">
					<view class="mute_right">
						<text>{{ getMuteTime }}</text>
						<u-icon name="arrow-right" color="#999" size="20"></u-icon>
					</view>
				</user-info-row-item>
			</view>

			<view v-if="organizationData.length > 0" class="company_row info_row">
				<text class="desc_title">组织信息</text>
				<view class="company_info">
					<user-info-row-item lable="企业/组织" :content="organizationData[0].companyName" />
					<user-info-row-item lable="部门" :content="organizationData[0].departmentName" />
					<user-info-row-item lable="职位" :content="organizationData[0].position || '-'" />
					<view v-if="organizationData.length > 1" @click="toFullOrganization" class="more_dep">
						<text>查看更多</text>
						<u-icon name="arrow-right" color="#1D6BED"></u-icon>
					</view>
				</view>
			</view>

			<view class="info_row">
				<user-info-row-item v-if="!isSelf" @click="toMoreInfo" lable="个人资料" arrow />
				<user-info-row-item @click="toPublisher" lable="查看动态" arrow />
			</view>

			<view v-if="!isSelf" class="action_row">
				<view v-if="!isBlack" @click="callUser" class="action_item">
					<img src="https://bjyjb-1362704775.cos.ap-chongqing.myqcloud.com/shop/image/user_card_call.png" alt="" />
					<text>音视频通话</text>
				</view>
				<view @click="toDesignatedConversation" class="action_item">
					<img src="https://bjyjb-1362704775.cos.ap-chongqing.myqcloud.com/shop/image/user_card_message.png" alt="" />
					<text>发消息</text>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
import { mapGetters } from 'vuex';
import { CommonIsAllow } from '../../../constant';
import { getUserInDepartment } from '../../../api/orgnizaition';
import { navigateToDesignatedConversation, callingModule } from '../../../util/imCommon';
import IMSDK, { GroupJoinSource, GroupMemberRole, SessionType } from 'openim-uniapp-polyfill';
import MyAvatar from '../../../components/MyAvatar/index.vue';
import CustomNavBar from '../../../components/CustomNavBar/index.vue';
import UserInfoRowItem from './components/UserInfoRowItem.vue';
import dayjs from 'dayjs';
import { businessSearchUserInfo } from '../../../api/login';

export default {
	components: {
		CustomNavBar,
		MyAvatar,
		UserInfoRowItem
	},
	data() {
		return {
			isLoading: true,
			sourceID: '',
			sourceUserInfo: {},
			organizationData: [],
			memberInfo: null,
			switchLoading: false,
			showSetRole: false,
			showSetMuteMember: false,
			disableAdd: false
		};
	},
	computed: {
		...mapGetters(['storeFriendList', 'storeBlackList', 'storeCurrentMemberInGroup', 'storeCurrentUserID', 'storeSelfInfo', 'storeOrganizationData']),
		isFriend() {
			return this.storeFriendList.findIndex((friend) => friend.userID === this.sourceID) !== -1;
		},
		isBlack() {
			return this.storeBlackList.some((black) => black.userID === this.sourceID);
		},
		trySendRequest() {
			return !this.isFriend && !this.isSelf && !this.disableAdd && this.sourceUserInfo.allowAddFriend !== 2;
		},
		isSelf() {
			return this.sourceID === this.storeSelfInfo.userID;
		},
		isAdmin() {
			return this.memberInfo?.roleLevel === GroupMemberRole.Admin;
		},
		getJoinGroupTime() {
			return this.memberInfo ? dayjs(this.memberInfo.joinTime).format('YYYY-MM-DD') : '';
		},
		getJoinSource() {
			if (!this.memberInfo) {
				return '';
			}

			switch (this.memberInfo.joinSource) {
				case GroupJoinSource.Invitation:
					return '邀请进群';
				case GroupJoinSource.QrCode:
					return '扫码进群';
				case GroupJoinSource.Search:
					return '搜索进群';
				default:
					return '-';
			}
		},
		getShowName() {
			let suffix = '';
			if (this.sourceUserInfo.remark) {
				suffix = `(${this.sourceUserInfo.remark})`;
			}
			return this.sourceUserInfo.nickname + suffix;
		},
		getMuteTime() {
			if (!this.memberInfo.muteEndTime || this.memberInfo.muteEndTime < Date.now()) {
				return '';
			}
			return dayjs(this.memberInfo.muteEndTime).format('YYYY/MM/DD HH:mm');
		}
	},
	onLoad(options) {
		const { sourceID, sourceInfo, memberInfo, disableAdd } = options;
		this.disableAdd = disableAdd ? JSON.parse(disableAdd) : false;
		if (sourceID) {
			this.sourceID = sourceID;
		} else {
			const info = JSON.parse(sourceInfo);
			this.sourceID = info.userID;
		}
		this.getSourceUserInfo();
		if (memberInfo) {
			this.memberInfo = JSON.parse(memberInfo);
			this.checkCurrentMember();
		}
		this.getOrganizationData();
		this.setIMListener();
	},
	onUnload() {
		this.disposeIMListener();
	},
	methods: {
		copy(userID) {
			uni.setClipboardData({
				showToast: false,
				data: userID,
				success: function () {
					uni.showToast({
						icon: 'none',
						title: '复制成功'
					});
				}
			});
		},
		toPublisher() {
			uni.$u.route('/pages/moments/designatedMoments/index', {
				baseUserInfo: JSON.stringify({
					userID: this.sourceUserInfo.userID,
					nickname: this.sourceUserInfo.nickname,
					faceURL: this.sourceUserInfo.faceURL
				})
			});
		},
		async getSourceUserInfo() {
			let info = {};
			const friendInfo = this.storeFriendList.find((item) => item.userID === this.sourceID);
			if (friendInfo) {
				info = { ...friendInfo };
			} else {
				const { data } = await IMSDK.asyncApi(IMSDK.IMMethods.GetUsersInfo, IMSDK.uuid(), [this.sourceID]);
				info = { ...(data[0] ?? {}) };
			}
			this.sourceUserInfo = {
				...info
			};
			this.isLoading = false;
			try {
				const { total, users } = await businessSearchUserInfo(this.sourceID);
				if (total > 0) {
					info = {
						...info,
						...users[0]
					};
				}
			} catch (err) {
				console.log(err);
			}
			this.sourceUserInfo = {
				...info
			};
		},
		getOrganizationData() {
			getUserInDepartment(this.sourceID).then((res) => {
				this.organizationData = res.users.map((item) => ({
					companyName: this.$store.getters.storeOrganizationData.current.name,
					departmentName: item.members[0].department.name,
					position: item.members[0].position
				}));
			});
		},
		async checkCurrentMember() {
			let role;
			if (this.storeCurrentMemberInGroup.groupID === this.memberInfo.groupID) {
				role = this.storeCurrentMemberInGroup.roleLevel;
			} else {
				try {
					const { data } = await IMSDK.asyncApi(IMSDK.IMMethods.GetSpecifiedGroupMembersInfo, IMSDK.uuid(), {
						groupID: this.memberInfo.groupID,
						userIDList: [this.storeCurrentUserID]
					});
					role = data[0]?.roleLevel;
				} catch (e) {}
			}
			this.showSetRole = role === GroupMemberRole.Owner;
			this.showSetMuteMember = role === GroupMemberRole.Owner || (role === GroupMemberRole.Admin && this.memberInfo.roleLevel === GroupMemberRole.Nomal);
		},
		toAddFriend() {
			uni.$u.route('/pages/common/sendAddRequest/index', {
				isGroup: false,
				sourceID: this.sourceID,
				isScan: false,
				notNeedVerification: false
			});
		},
		callUser() {
			uni.showActionSheet({
				itemList: ['语音通话', '视频通话'],
				cancelText: '取消',
				success: ({ tapIndex }) => {
					callingModule.startLiveChat(!!tapIndex, [this.sourceID], '', this.$store.getters.storeCurrentUserID);
				}
			});
		},
		toFullOrganization() {
			uni.$u.route('/pages/common/fullOrganization/index', {
				organizationData: JSON.stringify(this.organizationData)
			});
		},
		toDesignatedConversation() {
			navigateToDesignatedConversation(this.sourceID, SessionType.Single, this.memberInfo !== null).catch(() => uni.$u.toast('获取会话信息失败'));
		},
		toMoreInfo() {
			uni.navigateTo({
				url: `/pages/common/userCardMore/index?sourceInfo=${JSON.stringify(this.sourceUserInfo)}`
			});
		},
		changeMemberRole(flag) {
			this.switchLoading = true;
			const newRole = flag ? GroupMemberRole.Admin : GroupMemberRole.Nomal;
			IMSDK.asyncApi(IMSDK.IMMethods.SetGroupMemberInfo, IMSDK.uuid(), {
				groupID: this.memberInfo.groupID,
				userID: this.sourceUserInfo.userID,
				roleLevel: newRole
			})
				.catch(() => uni.$u.toast('设置失败'))
				.finally(() => (this.switchLoading = false));
		},
		toMuteMember() {
			uni.navigateTo({
				url: `/pages/common/setMemberMute/index?sourceInfo=${JSON.stringify([this.memberInfo])}`
			});
		},
		friendInfoChangeHandler({ data }) {
			if (data.userID === this.sourceUserInfo.userID) {
				this.sourceUserInfo = {
					...this.sourceUserInfo,
					...data
				};
			}
		},
		groupMemberInfoChangeHandler({ data }) {
			if (data.userID === this.memberInfo.userID && data.groupID === this.memberInfo.groupID) {
				this.memberInfo = {
					...this.memberInfo,
					...data
				};
			}
		},
		setIMListener() {
			uni.$on(IMSDK.IMEvents.OnFriendInfoChanged, this.friendInfoChangeHandler);
			uni.$on(IMSDK.IMEvents.OnGroupMemberInfoChanged, this.groupMemberInfoChangeHandler);
		},
		disposeIMListener() {
			uni.$off(IMSDK.IMEvents.OnFriendInfoChanged, this.friendInfoChangeHandler);
			uni.$off(IMSDK.IMEvents.OnGroupMemberInfoChanged, this.groupMemberInfoChangeHandler);
		}
	}
};
</script>

<style lang="scss" scoped>
.user_card_container {
	@include colBox(false);
	height: 100vh;
	background-color: #f6f6f6;
	overflow-y: auto;
	position: relative;

	.base_info {
		@include vCenterBox();
		background-color: #fff;
		padding: 44rpx;
		margin-bottom: 18rpx;

		.add_btn {
			width: 140rpx;
			height: 60rpx;
			margin-left: auto;

			.u-button {
				width: 140rpx;
				height: 60rpx;
			}
		}

		.u-avatar {
			margin-right: 24rpx;
		}

		.user_name {
			display: flex;
			flex-direction: column;
			justify-content: space-between;
			margin-bottom: 12rpx;
			height: 46px;

			.text {
				@include nomalEllipsis();
				max-width: 300rpx;
			}
		}

		.company {
			font-size: 28rpx;
			color: $u-primary;
		}
	}

	.info_row {
		background-color: #fff;
		margin-bottom: 24rpx;
	}

	.mute_right {
		display: flex;
		align-items: center;
	}

	.company_row {
		padding: 20rpx 0;

		.desc_title {
			padding-left: 44rpx;
		}

		.company_info {
			.more_dep {
				display: flex;
				justify-content: center;
				color: #1d6bed;
			}
		}

		::v-deep .title {
			width: 200rpx;
			color: #999 !important;
		}
	}

	.action_row {
		@include vCenterBox();
		align-items: flex-end;
		justify-content: space-around;
		margin: 44rpx;
		flex: 1;

		.action_item {
			width: 100%;
			@include colBox(true);
			flex-direction: row;
			align-items: center;
			justify-content: center;
			padding: 22rpx 0;
			background: $u-primary;
			color: #fff;
			border-radius: 6px;

			&:first-child {
				background-color: #fff;
				color: $uni-text-color;
				margin-right: 24rpx;
			}

			img {
				margin-right: 16rpx;
				width: 40rpx;
				height: 40rpx;
			}
		}
	}

	.id {
		font-size: 24rpx;
		color: #999;
	}

	.online_state {
		@include vCenterBox();
		margin-left: 24rpx;
		font-size: 24rpx;
		color: #999;

		.dot {
			background-color: #10cc64;
			width: 12rpx;
			height: 12rpx;
			border-radius: 50%;
			margin-right: 12rpx;
		}

		.online_str {
			@include nomalEllipsis();
			max-width: 280rpx;
		}
	}
}
</style>
