<template>
	<page-meta :page-font-size="fontValue+'px'" :root-font-size="fontValue+'px'"></page-meta>
  <view>
    <cu-custom bgImage='/static/bg.png' :isBack='true'>
      <template v-slot:content>
        <text class="text-black">{{ group.name }}</text>
      </template>
      <template v-slot:right v-if='isMaster'>
        <text class='cuIcon cuIcon-edit text-black' @tap='editGroup'></text>
      </template>
    </cu-custom>

    <view class='bg-white padding'>
      <view class='item_list'>
		  <view class='item_content' @tap='group.prohibitFriend === DictUtils.YES ? "" : openUser(group.master)'>
           <image class="logoImg" :src="master.avatar" mode="scaleToFill"></image>
           <!-- <vim-avatar :img="master.avatar" :name="master.name" /> -->
           <view class='margin-top-xs text-sm' style="display: flex;flex-direction:row;justify-content: center;">
             <text class="text-zblue  margin-right-xs"><text class="cuIcon-crown"></text></text>
             <text class="text-zblue text-bold user_name">{{ master.name }}</text>
           </view>
        </view>
        <view v-for='(item,index) in userList.slice(0,endIndex)' :key='index' class='item_content'
              @tap='group.prohibitFriend === DictUtils.YES ? "" : openUser(item.id)'>
          <vim-avatar :img="item.avatar" :name="item.name" />
          <view class='margin-top-xs text-sm'>
            <text class="text-black text-bold user_name">{{ item.name }}</text>
          </view>
        </view>
        <view class='item_content' v-if="group.openInvite === DictUtils.YES || isMaster">
          <view class='cuIcon cuIcon-add cu-avatar group-btn radius' @tap='toAddUsers'></view>
          <view class='margin-top-xs  text-sm text-black text-bold'>邀请</view>
        </view>
        <view class='item_content' v-if='isMaster'>
          <view class='cuIcon cuIcon-move cu-avatar group-btn radius' @tap='toDelUsers'></view>
          <view class='margin-top-xs  text-sm text-black text-bold'>移除</view>
        </view>
        <view class='item_content' v-if='userList.length>endIndex'>
          <view class='cuIcon cuIcon-more cu-avatar group-btn radius' @tap='moreUser'></view>
          <view class='margin-top-xs  text-sm '>更多</view>
        </view>
      </view>
    </view>
    <chat-setting :chat-id='group.id'></chat-setting>
    <view class='cu-list menu margin-top text-sm'>
      <view class='cu-item card-menu' v-if='isMaster' @tap='handleCheck()'>
        <view class='content'>
          <text class='cuIcon-check text-black text-bold'></text>
          <text class='text-black text-bold'>入群审核</text>
        </view>
        <view class='action text-black text-bold'>
          <text class="cuIcon cuIcon-right"></text>
        </view>
      </view>
      <view class='cu-item card-menu' v-if='isMaster' @tap='handleTransference()'>
        <view class='content'>
          <text class='cuIcon-share text-black text-bold'></text>
          <text class='text-black text-bold'>转让群</text>
        </view>
        <view class='action text-black text-bold'>
          <text class="cuIcon cuIcon-right"></text>
        </view>
      </view>
      <view class='cu-item text-black text-bold' @tap='history()'>
        <view class='content'>
          <text class='cuIcon-message'></text>
          <text class="text-black text-bold">聊天记录</text>
        </view>
        <view class='action'>
          <text class='cuIcon-right'></text>
        </view>
      </view>
      <view class='cu-item text-black text-bold'>
        <view class='content'>
          <text class='cuIcon-notice'></text>
          <text>公告</text>
        </view>
        <view class='action'  v-if='isMaster' @tap="handleAnnouncement">
          <text class='cuIcon-right'></text>
        </view>
      </view>
      <view v-if="group.announcement " class='cu-item text-gray announcement'>{{ group.announcement }}</view>
    </view>
    <view class='cu-list menu margin-top text-sm'>
      <view class='text-cyan margin-top padding' >
        <button class="cu-btn lg bg-zblue block border" @tap='openChat()'>聊天</button>
      </view>
      <view class='cu-item text-red margin-top' v-if='isMaster' @tap='deleteGroup()'>
        <view class='content text-center text-bold'>
          <text>解散群组</text>
        </view>
      </view>
      <view class='cu-item text-red margin-top' @tap='exitGroup()' v-if='!isMaster'>
        <view class='content text-center text-bold'>
          <text>退出群聊</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang='ts'>
import {getCurrentInstance, reactive, ref} from 'vue'
import {onLoad} from '@dcloudio/uni-app'
import {useUserStore} from '@/store/userStore'
import {useChatStore} from '@/store/chatStore'
import CuCustom from '@/colorui/components/cu-custom.vue'
import GroupApi from '@/api/GroupApi'
import {useGroupStore} from '@/store/groupStore'

import ChatType from '@/utils/ChatType'
import type Group from '@/mode/Group'
import type Message from '@/mode/Message'
import UserApi from '@/api/UserApi'
import MessageUtils from '@/utils/MessageUtils'
import MessageType from '@/utils/MessageType'
import type ChatSimple from '@/mode/ChatSimple'
import {storeToRefs} from 'pinia'
import {useWsStore} from '@/store/WsStore'
import ChatSetting from '@/components/ChatSetting.vue'
import DictUtils from "@/utils/DictUtils";
import VimAvatar from "@/components/VimAvatar.vue";
import type UserSimple from "@/mode/UserSimple";
import Auth from "@/api/Auth";
const fontValue=ref(Auth.getfontSize());
//@ts-ignore
const {proxy} = getCurrentInstance()

const groupStore = useGroupStore()

const store = useUserStore()
const chatStore = useChatStore()
const userStore = useUserStore()
//显示的群用户条数
const endIndex = ref(8)
//是否是群主
const isMaster = ref(false)
const master = ref({} as UserSimple)


//群用户
const userList = ref<ChatSimple[]>([])

const group = reactive<Group>({
  id: '',
  master: '',
  name: '',
  avatar: '',
  openInvite: '0',
  inviteCheck: '0',
  prohibition: '0',
  prohibitFriend: '0',
  announcement: ''
})

const handleAnnouncement = () => {
  uni.navigateTo({
    url: '/pages/group/announcement?id=' + group.id
  })
}

onLoad((opt) => {
  group.id = opt?.id
  uni.showLoading()
  GroupApi.get(group.id)
      .then((res) => {
		//console.log('group',res)
        group.id = res.data.id
        group.name = res.data.name
        group.avatar = res.data.avatar
        group.master = res.data.master
        group.openInvite = res.data.openInvite
        group.inviteCheck = res.data.inviteCheck
        group.prohibition = res.data.prohibition
        group.prohibitFriend = res.data.prohibitFriend
        group.announcement = res.data.announcement
        isMaster.value = res.data.master === store.user?.id

        loadUser(group.id)
      })
  groupStore.loadWaitCheckList()
})

const toAddUsers = () => {
  uni.navigateTo({
    url: '/pages/group/add-users?id=' + group.id
  })
}

const toDelUsers = () => {
  uni.navigateTo({
    url: '/pages/group/del-users?id=' + group.id
  })
}

const moreUser = () => {
  endIndex.value = userList.value.length + 1
}

const history = () => {
  uni.navigateTo({
    url: '/pages/chat/history?chatId=' + group.id + '&type=' + ChatType.GROUP
  })
}


//加载群用户
const loadUser = (gId: string) => {
  userList.value = []
  GroupApi.users(gId).then((res) => {
    //是否是群用户
	//console.log('GroupApi',res)
    if (!res.data.some((item: any) => {
      return item.id === useUserStore().getUser()!.id
    })) {
      MessageUtils.message('无权限')
    }
    res.data.forEach((item: any) => {

      if(group.master === item.id){
        master.value = {
          name: item.name,
          avatar: item.avatar
        }
      }else {
        userList.value.push({
          id: item.id,
          name: item.name,
          avatar: item.avatar
        })
      }
    })
  })
      .finally(() => {
        uni.hideLoading()
      })
}

const editGroup = () => {
  uni.navigateTo({
    url: '/pages/group/edit?id=' + group.id
  })
}

const handleCheck = () => {
  uni.navigateTo({
    url: '/pages/group/invite?id=' + group.id
  })
}

/**
 * 转让群
 */
const handleTransference = () => {
  uni.navigateTo({
    url: '/pages/group/transference?id=' + group.id
  })
}

const openUser = (id: string | undefined) => {
//console.log('openUser',id);
  uni.navigateTo({
    url: '/pages/pub/user?id=' + id
  })
}

const deleteGroup = () => {
  uni.showModal({
    title: '提示',
    content: '是否解散此群?？',
    cancelText: '取消',
    confirmText: '确定',
    success: res => {
      if (res.confirm) {
        notify(group.master, group.id)
        GroupApi.delete(group.id).then((res) => {
          if (res) {
            groupStore.loadGroupList()
            MessageUtils.message('群已经解散')
            uni.reLaunch({
              url: '/pages/index/index'
            })
          }
        })
      }
    }
  })
}

//离开群
const exitGroup = () => {
  uni.showModal({
    title: '提示',
    content: '是否退出此群?？',
    cancelText: '取消',
    confirmText: '确定',
    success: res => {
      if (res.confirm) {
        GroupApi.exit(group.id).then((res) => {
          if (res) {
            chatStore.delChat(group.id)
            groupStore.loadGroupList()
            notify(group.master, group.id, store.getUser()?.name + ' 已退群')
            MessageUtils.message('已退群')
            uni.reLaunch({
              url: '/pages/index/index'
            })
          }
        })
      }
    }
  })
}

/**
 * 通知用户群已经被删除
 * @param master 群主id
 * @param groupId 群id
 * @param content 通知内容
 */
const notify = (master: string, groupId: string, content: string = '群已被解散') => {
  if (master) {
    UserApi.getUser(master).then((res) => {
      let user = res.data
      let msg: Message = {
        chatId: groupId,
        messageType: MessageType.text,
        fromId: master,
        mine: true,
        content: content,
        timestamp: new Date().getTime(),
        type: ChatType.GROUP
      }
      useWsStore().sendMessage(msg)
    })
  }
}

/**
 * 打开聊天室
 */
const openChat = () => {
  chatStore.openChat({
    id: group.id,
    name: group.name,
    avatar: group.avatar,
    type: ChatType.GROUP,
    unreadCount: 0,
    isLoading: false,
    loaded: true
  })
  uni.navigateTo({
    url: '/pages/chat/chat?id=' + group.id + '&type=' + ChatType.GROUP
  })
}

const {waitCheckMap} = storeToRefs(groupStore)
</script>

<style scoped>
.grid > view {
  height: 140upx;
  margin-top: 10px;
}

.group-btn {
  font-size: 2rem;
  border: 1px solid #ccc;
  width: 100upx;
  height: 100upx;
}

.grid > .grid-btn {
  display: flex;
  align-items: center;
  justify-content: center;
}

.logoImg{
  width: 100upx;
  height: 100upx;
  border-radius: 8upx;
}

.group-user {
  padding: 5px;
  text-align: center;
}

.group-user .text {
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
  text-align: center;
  margin-top: 10upx;
}

.announcement{
  text-indent: 2rem;
  word-break: break-all;
  line-height: 1.5;
  padding: 20px !important;
  background: #eee !important;;
}

.item_list{
	display: flex;
	flex-wrap: wrap;
	justify-content: flex-start;
}
.item_content{
	display: flex;
	flex-direction: column;
	align-items: center;
	width: 154upx;
	height: 154upx;
	margin: 5px;
	box-sizing: border-box;
}
.user_name{
	max-width: 154upx;
	text-align: center;
	overflow: hidden;
	text-overflow: ellipsis;
	display: -webkit-box;
	-webkit-line-clamp: 1;
	-webkit-box-orient: vertical;
}
</style>
