<template>
  <view>
    <cu-custom bgImage='/static/bg.png' :isBack='true'>
      <template v-slot:content>
        {{ group.name }}
      </template>
      <template v-slot:right v-if='isMaster'>
        <text class='cuIcon cuIcon-edit' @tap='editGroup'></text>
      </template>
    </cu-custom>

    <view class='bg-white padding'>
      <view class='grid col-4'>
        <view class='group-user'
              @tap='group.prohibitFriend === DictUtils.YES ? "" : openUser(master.id)'>
          <vim-avatar :img="master.avatar" :name="master.name" />
          <view class='margin-top-xs text-sm'>
            <text class="text-cyan margin-right-xs"><text class="cuIcon-crown"></text></text>
            <text class="text-cyan">{{ master.name }}</text>
          </view>
        </view>
        <view v-for='(item,index) in userList.slice(0,endIndex)' :key='index' class='group-user'
              @tap='group.prohibitFriend === DictUtils.YES ? "" : openUser(item.id)'>
          <vim-avatar :img="item.avatar" :name="item.name" />
          <view class='margin-top-xs text-sm'>
            <text>{{ item.name }}</text>
          </view>
        </view>
        <view class='group-user' 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'>邀请</view>
        </view>
        <view class='group-user' v-if='isMaster'>
          <view class='cuIcon cuIcon-move cu-avatar group-btn radius' @tap='toDelUsers'></view>
          <view class='margin-top-xs  text-sm'>移除</view>
        </view>
        <view class='group-user' 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-grey'></text>
          <text class='text-grey'>入群审核</text>
        </view>
        <view class='action text-gray'>
          <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-grey'></text>
          <text class='text-grey'>转让群</text>
        </view>
        <view class='action text-gray'>
          <text class="cuIcon cuIcon-right"></text>
        </view>
      </view>
      <view class='cu-item text-grey' @tap='history()'>
        <view class='content'>
          <text class='cuIcon-message'></text>
          <text>聊天记录</text>
        </view>
        <view class='action'>
          <text class='cuIcon-right'></text>
        </view>
      </view>
      <view class='cu-item text-grey'>
        <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-cyan block" @tap='openChat()'>聊天</button>
      </view>
      <view class='cu-item text-red margin-top' v-if='isMaster' @tap='deleteGroup()'>
        <view class='content text-center'>
          <text>解散群组</text>
        </view>
      </view>
      <view class='cu-item text-red margin-top' @tap='exitGroup()' v-if='!isMaster'>
        <view class='content text-center'>
          <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 User from "@/mode/User";
import type UserSimple from "@/mode/UserSimple";
//@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) => {
        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) => {
    //是否是群用户
    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) => {
  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;
}

.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;;
}
</style>
