<template>
  <div>
    <ChatHeaderBar title="聊天设置" />

    <div class="w-full min-h-300 pt-60 box-border bg-[#F7F8FA]">
      <van-cell-group
        style="margin-bottom: 12px; padding-top: 12px; padding-left: 16px"
        class="box-border"
        inset
      >
        <van-row>
          <van-col
            style="width: 54px"
            v-for="(item, index) in setData?.memberList"
            :key="index"
            span="4"
            class="mb-12 mr-10"
          >
            <div class="w-40 h-40 rounded-full border mx-auto overflow-hidden mb-4">
              <img
                v-if="item.headImageUrl"
                class="w-full h-full object-cover"
                :src="item.headImageUrl"
                alt=""
              />
              <img
                v-else
                class="w-full h-full object-cover"
                src="~/assets/img/default_avatar.png"
                alt=""
              />
            </div>
            <p class="w-full line-clamp-1 lin text-sm text-center text-black-6">
              {{ item.groupNickname ? item.groupNickname : userInfo.showName }}
            </p>
          </van-col>
          <van-col span="4" class="mb-12 mr-10" @click="navigateTo('/chat/group-add')">
            <div
              class="w-40 h-40 rounded-full flex justify-center items-center bg-[#F3F3F3] border mx-auto overflow-hidden mb-4"
            >
              <span class="iconfont icon-plus text-black-6" style="font-size: 24px"></span>
            </div>
            <p class="w-full line-clamp-1 lin text-sm text-center text-black-6">添加成员</p>
          </van-col>
          <van-col v-if="isRankAndFiler(userGroupData?.groupRole)" span="4 mb-12 mr-10">
            <div
              class="w-40 h-40 rounded-full flex justify-center items-center bg-[#F3F3F3] border mx-auto overflow-hidden mb-4"
            >
              <van-icon name="minus" size="24" color="#666666" />
            </div>
            <p class="w-full line-clamp-1 lin text-sm text-center text-black-6">删除成员</p>
          </van-col>
        </van-row>

        <div
          v-if="changeState(userGroupData?.groupRole) && setData?.memberList?.lenght == 13"
          @click="navigateTo('/chat/group-member')"
          class="w-full flex pb-5 box-border justify-center items-center leading-3xl text-sm text-black"
        >
          查看更多群成员
          <van-icon name="arrow" class="-mt-2" size="16" />
        </div>
      </van-cell-group>

      <van-cell-group style="margin-bottom: 12px" inset>
        <van-cell
          size="large"
          @click="
            changeState(userGroupData?.groupRole)
              ? openDialog({
                  title: '修改群名称',
                  value: setData?.groupName,
                  isRemark: 0,
                  placeholder: '未命名',
                  subTitle: '最多不能超过12个字'
                })
              : showDialog({
                  title: '群名称',
                  message: setData.groupName,
                  confirmButtonColor: '#FF9300',
                  showCancelButton: false
                })
                  .then(() => {
                    // on close
                  })
                  .catch(() => {
                    // on cancel
                  })
          "
          center
          is-link
          title="群名称"
        >
          <template #value>
            <p class="w-full line-clamp-2 text-xl text-black/[0.4] leading-5xl">
              {{ setData?.groupName ? setData?.groupName : '未命名' }}
            </p>
          </template>
        </van-cell>
        <van-cell
          @click="
            navigateTo({
              path: '/chat/qr-code',
              query: {
                groupName: setData.groupName,
                groupAvatar: setData.groupAvatar,
                groupId: setData?.id
              }
            })
          "
          size="large"
          center
          is-link
          title="群二维码"
        >
          <template #value>
            <div class="w-full flex justify-end items-center">
              <img class="w-16 h-16 shrink-0" src="~/assets/img/chat/chat-code.svg" alt="" />
            </div>
          </template>
        </van-cell>

        <van-cell
          :clickable="isRankAndFiler(userGroupData?.groupRole)"
          @click="handleAnnouncement"
          size="large"
          center
          is-link
          title="群公告"
          :value="setData?.groupNotice ? '' : '未设置'"
        ></van-cell>

        <van-cell size="large" center>
          <template #title>
            <p class="w-full line-clamp-1">群介绍：{{ setData?.description }}</p>
          </template>
        </van-cell>
        <van-cell size="large" center title="群聊类型">
          <template #value>
            <p class="w-full line-clamp-1">{{ setData?.belongTypeIdDictMap?.name }}</p>
          </template>
        </van-cell>
        <van-cell
          @click="
            openDialog({
              title: '群备注',
              value: userGroupData?.groupRemark, //groupRemark
              isRemark: 1,
              placeholder: '备注',
              subTitle: '群备注仅自己可见'
            })
          "
          size="large"
          is-link
          center
          title="群备注"
        >
          <template #value>
            <p class="w-full line-clamp-1">
              {{ userGroupData?.groupRemark ? userGroupData?.groupRemark : '未设置' }}
            </p>
          </template>
        </van-cell>
      </van-cell-group>

      <van-cell-group
        v-if="isRankAndFiler(userGroupData?.groupRole)"
        style="margin-bottom: 12px"
        inset
      >
        <van-cell size="large" center title="个人主页展示">
          <template #label>
            <!-- class="text-base text-black/[0.4]" -->
            <span>开启后，在群聊广场和个人主页</span>
          </template>
          <template #right-icon>
            <van-switch v-model="isPublic" active-color="#FF9300" inactive-color="#dcdee0" />
          </template>
        </van-cell>
        <van-cell size="large" center title="群聊邀请确认">
          <template #label>
            <!-- class="text-base text-black/[0.4]" -->
            <span>
              启用后，群成员需群主或群管理员确认才能邀请朋友进群。扫描二维码进群将同时停用
            </span>
          </template>
          <template #right-icon>
            <van-switch v-model="isNeedConfirm" active-color="#FF9300" inactive-color="#dcdee0" />
          </template>
        </van-cell>

        <van-cell
          @click="
            navigateTo({
              path: '/chat/examine',
              query: {
                groupId: setData?.id
              }
            })
          "
          size="large"
          is-link
          center
          title="收到的进群申请"
        ></van-cell>
      </van-cell-group>

      <van-cell-group style="margin-bottom: 12px" inset>
        <van-cell
          @click="
            openDialog({
              title: '我在群里的昵称',
              value: userGroupData?.groupNickname,
              placeholder: '昵称',
              isRemark: 2,
              subTitle: '昵称修改之后，只会在此群内显示，群内成员都可以看见'
            })
          "
          size="large"
          is-link
          center
          title="我在群里的昵称"
        >
          <template #value>
            <p class="w-full line-clamp-1">
              {{ userGroupData?.groupNickname }}
            </p>
          </template>
        </van-cell>
      </van-cell-group>
      <van-cell-group style="margin-bottom: 12px" inset>
        <van-cell
          @click="
            navigateTo({
              path: '/chat/set-sub',
              query: {
                tab: 'records',
                groupId: setData?.id
              }
            })
          "
          size="large"
          is-link
          center
          title="查找聊天记录"
        ></van-cell>
      </van-cell-group>
      <van-cell-group style="margin-bottom: 12px" inset>
        <van-cell size="large" is-link center title="消息免打扰">
          <template #right-icon>
            <van-switch
              v-model="isNotDisturb"
              @click="handleIsNotDisturb"
              active-color="#FF9300"
              inactive-color="#dcdee0"
            />
            <!-- @change="
                (val) => {
                  isNotDisturb = val
                }
              " -->
          </template>
        </van-cell>
        <van-cell size="large" is-link center title="置顶聊天">
          <template #right-icon>
            <van-switch
              v-model="isTop"
              @click="handleIsTop"
              active-color="#FF9300"
              inactive-color="#dcdee0"
            />
          </template>
        </van-cell>
        <van-cell
          @click="
            navigateTo({
              path: '/chat/background',
              query: {
                groupId: setData?.id
              }
            })
          "
          size="large"
          is-link
          center
          title="设置当前聊天背景"
        ></van-cell>
      </van-cell-group>

      <van-cell-group style="margin-bottom: 12px" inset>
        <van-cell
          @click="
            navigateTo({
              path: '/chat/report',
              query: {
                groupId: setData?.id,
                objectType: 2
              }
            })
          "
          size="large"
          is-link
          center
          title="举报"
        ></van-cell>
        <van-cell
          @click="clearChatHistory"
          size="large"
          is-link
          center
          title="清空聊天记录"
        ></van-cell>
      </van-cell-group>

      <div class="w-full pt-10 pb-40 px-16 box-border">
        <van-button @click="handleExitGroupChat" color="#FF9300" round block>退出群聊</van-button>
      </div>
    </div>

    <ChatDialog
      v-model:show="showDialog"
      v-model:title="dialogTitle"
      @confirm="confirm"
      @cancel="cancel"
    >
      <div class="w-full px-12 text-center mt-4">
        <p class="mx-auto w-[80%] text-sm text-black-9 mb-16">{{ dialogSubTitle }}</p>

        <van-field
          class=""
          style="height: 40px; background: #f5f5f5; border-radius: 8px; margin-bottom: 30px"
          clearable
          :placeholder="dialogPlaceholder"
          v-model="groupName"
          maxlength="12"
        />
      </div>
    </ChatDialog>
  </div>
</template>
<script setup>
const route = useRoute()
const router = useRouter()

const userInfoStore = useUserInfoStore()
const { userInfo } = storeToRefs(userInfoStore)

definePageMeta({
  layout: false
})

useSeoMeta({
  title: '我的消息'
})

onMounted(() => {
  userInfoStore.getUserInfo()
  getGroupSetData()
})
// computed(() => route.query.userId ?? '')

let setData = reactive({
  // groupId: computed(() => route.query.groupId ?? ''),
  userId: userInfo.value.userId
  // groupRole: 1
  // groupNotice:
  //   '群公告模版 1.本群提倡友好理性交流，鼓励群友多发言，多互动 2.禁止无意义刷屏、发送广告信息以及谩骂等不良消息 3.为了保证群活跃不经常发言的群友，可能会被定时清理出群'
})

watch([() => route.query.groupId, () => route.query.userId], () => {}, {
  immediate: true
})

const userGroupData = ref(null)

const groupName = ref('')

// isPublic 是否公开展示 0隐藏 1公开。
// isNeedConfirm 是否开启群聊邀请确认 0不开启 1开启。
// 是否显示到个人主页
const isPublic = ref(false)
const isNeedConfirm = ref(false)
const isNotDisturb = ref(false)
const isTop = ref(false)

// 弹出窗
const showDialog = ref(false)
const isRemark = ref(0) //0 群名称 1备注 2 我在群里的昵称
const dialogTitle = ref('')
const dialogPlaceholder = ref('')
const dialogSubTitle = ref('')

// 弹窗的方法
const openDialog = (item) => {
  showDialog.value = true
  dialogTitle.value = item?.title
  isRemark.value = item.isRemark
  groupName.value = item?.value
  dialogPlaceholder.value = item?.placeholder
  dialogSubTitle.value = item?.subTitle
}
// 弹窗确认的事件
const confirm = () => {
  if (userGroupData.value?.groupRole == 1 && isRemark.value == 0) {
    changeGroupName()
  } else {
  }

  if (isRemark.value == 1) changeTourMember({ groupId: setData.id, remark: groupName.value })

  if (isRemark.value == 2)
    changeGroupName({
      groupId: setData.id,
      groupNickname: groupName.value
    })

  // showDialog.value = false
}

// 修改群名称
const changeGroupName = async () => {
  try {
    const { data } = await request('/website/tourGroup/updateGroup', {
      method: 'post',
      body: {
        groupId: setData.id,
        groupName: groupName.value
      }
    })

    if (data) {
      showSuccessToast('修改成功')
    } else {
      showFailToast('修改失败')
    }
  } catch (error) {}
}

// 修改备注名 和修改自己在群里的备注
const changeTourMember = async (body) => {
  try {
    const { data } = await request('/website/tourMember/updateTourMember', {
      method: 'post',
      body
    })
    console.log(data, '修改自己在群里的备注')

    if (data) {
      //修改成功
      if ((Object.keys(body)[1] = 'remark')) {
        userGroupData.groupRemark = groupName.value
      } else {
        userGroupData[Object.keys(body)[1]] = groupName.value
      }
      showSuccessToast('操作成功')
    } else {
      // showSuccessToast('操作失败')
    }
  } catch (error) {}
}

const cancel = () => {
  showDialog.value = false
}

// 改变状态的公用方法
const changeState = (state) => {
  if (state == 1) return true
  if (state == 0) return false
}

const changeStateBoolean = (state) => {
  if (state) {
    return 1
  } else {
    return 0
  }
}

// 是否置顶
const handleIsTop = () => {
  handleBoolean({ isTop: changeStateBoolean(isTop.value) })
}

// 是否免打扰
const handleIsNotDisturb = () => {
  handleBoolean({ isNotDisturb: changeStateBoolean(isNotDisturb.value) })
}

const handleBoolean = async (params) => {
  try {
    let { data } = await request('/website/tourMember/updateSingleTourMember', {
      method: 'post',
      body: {
        groupId: userGroupData.value.groupId,
        ...params
      }
    })
    if (data) {
      if (Object.keys(params)[0] == 'isTop') {
        isTop.value ? showToast('已置顶') : showToast('置顶取消')
      }
      if (Object.keys(params)[0] == 'isNotDisturb') {
        isNotDisturb.value ? showToast('已开启面打扰') : showToast('已关闭面打扰')
      }
    }
  } catch (error) {}
}
// 获取群设置的配置信息
const getGroupSetData = async () => {
  const { data } = await request('/website/tourGroup/getGroupInfoAndMemberByGroupId', {
    query: {
      groupId: route.query.groupId
    }
  })
  if (typeof data == 'object') {
    setData = data
    console.log(setData.id, 'setDataid')
    console.log(setData, 'setData')

    console.log(data.memberList, '555')
    console.log(userInfo.value.userId, 'userInfo')

    userGroupData.value = data.memberList.find((item) => item.userId == userInfo.value.userId)
    console.log()

    console.log(userGroupData.value, '4444')
    console.log(userGroupData.value.groupRole, 'userGroupData groupRole')

    isPublic.value = changeState(setData.isPublic)
    isNeedConfirm.value = changeState(setData.isNeedConfirm)

    isNotDisturb.value = changeState(userGroupData.value?.isNotDisturb)
    isTop.value = changeState(userGroupData.value.isTop)
  }
}

// 返回上一页
const onClickLeft = () => {
  router.back()
}

// 是否是普通成员
const isRankAndFiler = (role) => {
  return role == 1 || role == 2 ? true : false
}

// 清空聊天记录
const clearChatHistory = () => {
  showConfirmDialog({
    width: 260,
    title: '提示',
    message: '清空聊天记录',
    confirmButtonColor: '#FF9300'
  })
    .then(async () => {
      try {
        const res = await request('/website/tourMessage/clearGroupMessage', {
          query: {
            groupId: setData?.id
          }
        })
        if (res && res?.success) return
      } catch (error) {}
    })
    .catch(() => {})
}

// 点击公告
const handleAnnouncement = () => {
  console.log(userGroupData.value?.groupRole, 'userGroupData?.groupRole')
  console.log(!isRankAndFiler(3))
  //  && !setData?.groupNotice
  if (isRankAndFiler(userGroupData.value?.groupRole)) {
    // navigateTo({
    //   path: '/chat/announcement',
    //   query: {
    //     groupId: setData?.id,
    //     userId: userInfo.value.userId,
    //     groupRole: userGroupData.value?.groupRole
    //   }
    // })
  }

  if (!isRankAndFiler(userGroupData.value?.groupRole)) {
    showConfirmDialog({
      width: 260,
      message: `只有群主${setData?.groupName ? setData?.groupName : ''}或群管理员才能修改公告`,
      showCancelButton: false,
      confirmButtonColor: '#FF9300',
      confirmButtonText: '我知道了'
    }).then(() => {})
    return
  }
}

// 退出群聊
async function handleExitGroupChat() {
  let { data } = await request('/website/tourGroup/exitGroup', {
    query: {
      groupId: setData.groupId,
      userId: user
    }
  })
  navigateTo({
    path: '/profile/my-news',
    replace: true
  })
}
</script>
<style lang="scss" scoped>
::v-deep .van-dialog__header {
  padding-top: 21px;
}
</style>
