<template>
	<view class="group_settings_container">
		<u-navbar :autoBack="true" bgColor="#ECECEC" :title="'群聊设置('+storeCurrentGroup.memberCount+')'" safeAreaInsetTop placeholder fixed></u-navbar>

		<view class="group_settings_content">
			<view class="setting_row info_row" v-if="1==2">
				<view class="group_avatar" @click="updateGroupAvatar">
					<my-avatar :src="storeCurrentConversation.faceURL" :isGroup="true" size="46" />
					<image v-if="isOwner" class="edit_icon" src="@/static/images/group_setting_edit.png" alt="" />
				</view>
				<view class="group_info">
					<view class="group_info_name">
						<text class="group_name">{{ storeCurrentConversation.showName }}({{storeCurrentGroup.memberCount}})</text>
						<image v-if="isOwner || isAdmin" @click="toUpdateGroupName" style="width: 24rpx; height: 24rpx" src="@/static/images/group_edit.png" alt="" />
					</view>

					<text @click="copyGroupID" class="sub_title">{{storeCurrentConversation.groupID}}</text>
				</view>
			</view>

			<group-member-row v-if="isJoinGroup" :isNomal="!isAdmin && !isOwner"
				:groupID="storeCurrentConversation.groupID" :memberCount="storeCurrentGroup.memberCount"
				:groupMemberList="groupMemberList" />
			
			<uni-list>
				<uni-list-item title="群聊名称" :rightText="storeCurrentConversation.showName" @click="editGroupName" :clickable="isOwner || isAdmin" :showArrow="isOwner || isAdmin"></uni-list-item>
				<uni-list-item title="群公告" to="/pages/conversation/groupSettings/announcement" clickable showArrow></uni-list-item>
				<uni-list-item title="群二维码" :to="'/pages/common/userOrGroupQrCode?groupID='+storeCurrentConversation.groupID" clickable showArrow></uni-list-item>
				<uni-list-item v-if="isOwner || isAdmin" title="群管理" to="/pages/conversation/groupManage/index" clickable showArrow></uni-list-item>
				<uni-list-item v-if="1==2" title="备注" :rightText="storeCurrentConversation.showName" @click="editGroupName" :clickable="isOwner || isAdmin" :showArrow="isOwner || isAdmin"></uni-list-item>
			</uni-list>
			<u-gap></u-gap>
			<uni-list>
				<uni-list-item title="查找聊天内容" to=""></uni-list-item>
			</uni-list>
			<u-gap></u-gap>
			<uni-list>
				<uni-list-item title="消息免打扰" @switchChange="updateCoversation('recvMsgOpt',storeCurrentConversation.recvMsgOpt==0 ? 2: 0)" showSwitch :switchChecked="storeCurrentConversation.recvMsgOpt !== 0"></uni-list-item>
				<uni-list-item title="置顶聊天" @switchChange="updateCoversation('isPinned',!storeCurrentConversation.isPinned)" showSwitch :switchChecked="storeCurrentConversation.isPinned"></uni-list-item>
			</uni-list>
			<u-gap></u-gap>
			<uni-list>
				<uni-list-item v-if="1==2" title="我在本群的昵称"></uni-list-item>
				<uni-list-item title="删除聊天记录" @click="clearMsg" clickable></uni-list-item>
			</uni-list>
			<u-gap></u-gap>
			<uni-list v-if="isJoinGroup">
				<uni-list-item :border="false">
					<view slot="body" class="uni-list-item__content" @click="confirm">
						<text class="uni-list-item__content-title" style="color: red;">{{isOwner ? '解散群聊' : '退出群聊'}}</text>
					</view>
				</uni-list-item>
			</uni-list>
			<u-gap></u-gap>
			<u-gap></u-gap>
		</view>

		<u-toast ref="uToast"></u-toast>
	</view>
</template>

<script>
	import {mapGetters} from "vuex";
	import {GroupMemberListTypes} from "@/constant";
	import IMSDK, {
		GroupMemberRole,
		GroupStatus,
		GroupVerificationType,
		IMMethods,
		MessageReceiveOptType,
	} from "openim-uniapp-polyfill";
	import CustomNavBar from "@/components/CustomNavBar/index.vue";
	import MyAvatar from "@/components/MyAvatar/index.vue";
	import SettingItem from "@/components/SettingItem/index.vue";
	import GroupMemberRow from "./components/GroupMemberRow.vue";
	import {getPurePath} from "@/util/common";

	const ConfirmTypes = {
		Dismiss: "Dismiss",
		Quit: "Quit",
	};

	export default {
		components: {
			CustomNavBar,
			MyAvatar,
			SettingItem,
			GroupMemberRow
		},
		props: {},
		data() {
			return {
				switchLoading: {
					pin: false,
					opt: false,
					mute: false,
				},
				groupMemberList: [],
				isJoinGroup: true
			};
		},
		onShow() {
			console.log(this.storeCurrentConversation);
			/*
			this.$store.commit("conversation/SET_CURRENT_CONVERSATION", {
				"conversationID": "sg_1793688611",
				"conversationType": 3,
				"userID": "",
				"groupID": "1793688611",
				"showName": "5676uy",
				"faceURL": "",
				"recvMsgOpt": 0,
				"unreadCount": 0,
				"groupAtType": 0,
				"latestMsg": "{\"clientMsgID\":\"e6274af29366f9097615cc373bc9139d\",\"serverMsgID\":\"ba783d50f2853d5588c913529c08b790\",\"createTime\":1764803528981,\"sendTime\":1764803525434,\"sessionType\":3,\"sendID\":\"100004\",\"recvID\":\"100003\",\"msgFrom\":100,\"contentType\":101,\"senderPlatformID\":2,\"senderNickname\":\"131****1111\",\"senderFaceUrl\":\"/static/img/avatar.png\",\"groupID\":\"1793688611\",\"seq\":10,\"isRead\":false,\"status\":2,\"textElem\":{\"content\":\"2222222222222222222222222222222222\"},\"attachedInfoElem\":{\"groupHasReadInfo\":{\"hasReadCount\":0,\"groupMemberCount\":3},\"isPrivateChat\":false,\"burnDuration\":0,\"hasReadTime\":0,\"isEncryption\":false,\"inEncryptStatus\":false}}",
				"latestMsgSendTime": 1764803525434,
				"draftText": "",
				"draftTextTime": 0,
				"isPinned": false,
				"isPrivateChat": false,
				"burnDuration": 0,
				"isNotInGroup": false,
				"updateUnreadCountTime": 0,
				"attachedInfo": "",
				"ex": "",
				"maxSeq": 0,
				"minSeq": 0,
				"msgDestructTime": 0,
				"isMsgDestruct": false
			});
			this.$store.commit("conversation/SET_CURRENT_MEMBER_IN_GROUP", {
				"groupID": "1793688611",
				"userID": "100004",
				"nickname": "131****1111",
				"faceURL": "/static/img/avatar.png",
				"roleLevel": 20,
				"joinTime": 1764103081761,
				"joinSource": 2,
				"inviterUserID": "100003",
				"muteEndTime": 0,
				"operatorUserID": "100003",
				"ex": "",
				"attachedInfo": ""
			});
			this.$store.commit("conversation/SET_CURRENT_GROUP", {
				"groupID": "1793688611",
				"groupName": "5676uy",
				"notification": "",
				"introduction": "",
				"faceURL": "",
				"createTime": 1764103081757,
				"status": 0,
				"creatorUserID": "100003",
				"groupType": 2,
				"ownerUserID": "100003",
				"memberCount": 3,
				"ex": "",
				"attachedInfo": "",
				"needVerification": 0,
				"lookMemberInfo": 0,
				"applyMemberFriend": 0,
				"notificationUpdateTime": 0,
				"notificationUserID": ""
			});
			*/
			//console.log(this.storeCurrentGroup,this.storeCurrentConversation,this.storeCurrentMemberInGroup)
			this.getGroupMemberList();
			if (this.storeCurrentConversation.groupID) {
				IMSDK.asyncApi(
					IMMethods.IsJoinGroup,
					IMSDK.uuid(),
					this.storeCurrentConversation.groupID
				).then((res) => {
					this.isJoinGroup = res.data
				});
			}
		},
		watch: {
			"storeCurrentGroup.memberCount"() {
				this.getGroupMemberList();
			},
		},
		computed: {
			...mapGetters([
				"storeCurrentConversation",
				"storeCurrentMemberInGroup",
				"storeCurrentGroup",
			]),
			isOwner() {
				return this.storeCurrentMemberInGroup.roleLevel === GroupMemberRole.Owner;
			},
			isAdmin() {
				return this.storeCurrentMemberInGroup.roleLevel === GroupMemberRole.Admin;
			},
			getGroupVerStr() {
				if (
					this.storeCurrentGroup.needVerification ===
					GroupVerificationType.ApplyNeedInviteNot
				) {
					return "群成员邀请无需验证";
				}
				if (
					this.storeCurrentGroup.needVerification === GroupVerificationType.AllNot
				) {
					return "允许所有人加群";
				}
				return "需要发送验证消息";
			},
			isAllMuted() {
				return this.storeCurrentGroup.status === GroupStatus.Muted;
			},
		},
		methods: {
			editGroupName(){
				if(this.isOwner || this.isAdmin){
					this.toUpdateGroupName();
				}
			},
			getGroupMemberList() {
				IMSDK.asyncApi(IMSDK.IMMethods.GetGroupMemberList, IMSDK.uuid(), {
						groupID: this.storeCurrentConversation.groupID,
						filter: 0,
						offset: 0,
						count: !this.isAdmin && !this.isOwner ? 9 : 8,
					})
					.then(({
						data
					}) => {
						//console.log(data);
						this.groupMemberList = [...data];
					})
					.catch((err) => {
						console.log(err);
					});
			},
			toGroupManage() {
				uni.navigateTo({
					url: "/pages/conversation/groupManage/index",
				});
			},
			toUpdateGroupName() {
				if (!this.isAdmin && !this.isOwner) {
					return;
				}

				uni.navigateTo({
					url: `/pages/conversation/updateGroupOrNickname/index?sourceInfo=${JSON.stringify(this.storeCurrentGroup,)}`,
				});
			},
			copyGroupID() {
				uni.setClipboardData({
					data: this.storeCurrentGroup.groupID,
					success: () => {
						uni.hideToast();
						this.$nextTick(() => {
							uni.$u.toast("复制成功");
						});
					},
				});
			},
			updateGroupInfo(field,value1){
				const data = {groupID:this.storeCurrentGroup.groupID};
				data[field] = value1;
				IMSDK.asyncApi('setGroupInfo', IMSDK.uuid(),data).then(res=>{
					console.log(res);
				}).catch(e=>{
					console.log(e);
				})
			},
			updateCoversation(field,value1){
				const data = {conversationID:this.storeCurrentConversation.conversationID};
				data[field] = value1;
				IMSDK.asyncApi('setConversation', IMSDK.uuid(),data).then(res=>{
					console.log(res);
				}).catch(e=>{
					console.log(e);
				})
			},
			updateGroupAvatar() {
				if (!this.isAdmin && !this.isOwner) {
					return;
				}

				uni.chooseImage({
					count: 1,
					sizeType: ["compressed"],
					success: async ({
						tempFilePaths
					}) => {
						const path = tempFilePaths[0];
						const nameIdx = path.lastIndexOf("/") + 1;
						const typeIdx = path.lastIndexOf(".") + 1;
						const fileName = path.slice(nameIdx);
						const fileType = path.slice(typeIdx);
						try {
							const {
								data: {
									url
								},
							} = await IMSDK.asyncApi(IMMethods.UploadFile, IMSDK.uuid(), {
								filepath: getPurePath(tempFilePaths[0]),
								name: fileName,
								contentType: fileType,
								uuid: IMSDK.uuid(),
							});
							await IMSDK.asyncApi(IMSDK.IMMethods.SetGroupInfo, IMSDK.uuid(), {
								groupID: this.storeCurrentConversation.groupID,
								faceURL: url,
							});
							uni.$u.toast("修改成功");
						} catch (error) {
							uni.$u.toast("修改失败");
						}
					},
				});
			},
			confirm() {
				const _this = this;
				uni.showModal({
					content:this.isOwner ? '确定要解散当前群聊吗?' : '确定要退出当前群聊吗?',
					success(res){
						if (res.confirm) {
							let funcName = "";
							let sourceID = _this.storeCurrentConversation.groupID;
							if (this.isOwner) {
								funcName = IMSDK.IMMethods.DismissGroup;
							}else{
								funcName = IMSDK.IMMethods.QuitGroup;
							}
							IMSDK.asyncApi(funcName, IMSDK.uuid(), sourceID)
								.then(() => {
									uni.$u.toast("操作成功");
									setTimeout(
										() =>
										uni.switchTab({
											url: "/pages/conversation/conversationList/index",
										}),
										250,
									);
								})
								.catch(() => uni.$u.toast("操作失败"));
						}
					}
				})
			},
			clearMsg(){
				IMSDK.asyncApi('clearConversationAndDeleteAllMsg',IMSDK.uuid(), this.storeCurrentConversation.conversationID).then(res=>{
					uni.navigateBack();
				}).catch(e=>{
					console.log(e);
				})
			}
		},
	};
</script>

<style lang="scss" scoped>
	.group_settings_container {
		@include colBox(false);
		height: 100vh;
		background-color: #f6f6f6;

		.group_settings_content {
			overflow-y: auto;
		}

		.setting_row {
			background-color: #fff;
			margin: 24rpx;
			border-radius: 6px;
			overflow: hidden;
		}

		.info_row {
			@include vCenterBox();
			padding: 36rpx 44rpx;

			.group_avatar {
				margin-right: 16rpx;
				position: relative;

				.edit_icon {
					position: absolute;
					right: -6rpx;
					bottom: -6rpx;
					width: 11px;
					height: 11px;
				}
			}

			.group_info {
				min-height: 46px;
				display: flex;
				flex: 1;
				flex-direction: column;
				align-items: flex-start;
				justify-content: space-between;

				&_name {
					display: flex;
					flex-direction: row;
					align-items: center;
					justify-content: center;

					.group_name {
						// @include nomalEllipsis();
						font-size: 34rpx;
						max-width: 380rpx;
						margin-right: 24rpx;
					}
				}

				.sub_title {
					@include nomalEllipsis();
					margin-bottom: 0;
					font-size: 28rpx;
					color: #999;
				}
			}
		}
	}
</style>