<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({
                path: '/chat/group-add',
                query: {
                  groupId: setData?.id
                }
              })
            "
          >
            <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
              @click="
                navigateTo({
                  path: '/chat/group-member',
                  query: setData?.id
                })
              "
              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?.messageContent ? '' : '未设置'"
        ></van-cell>

        <van-cell @click="handleDescription" size="large" center>
          <template #title>
            <p class="w-full line-clamp-1">群介绍：{{ setData?.description }}</p>
          </template>
        </van-cell>
        <van-cell
          @click="getTreeType"
          size="large"
          :is-link="isRankAndFiler(userGroupData?.groupRole)"
          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"
              @click="changeIsPublic"
              active-color="#FF9300"
              inactive-color="#dcdee0"
            />
          </template>
        </van-cell>
        <van-cell size="large" center title="群聊邀请确认">
          <template #label>
            <span>
              启用后，群成员需群主或群管理员确认才能邀请朋友进群。扫描二维码进群将同时停用
            </span>
          </template>
          <template #right-icon>
            <van-switch
              v-model="isNeedConfirm"
              @click="changeIsNeedConfirm"
              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,
                objectType: 2
              }
            })
          "
          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>
          <template v-if="isRankAndFiler(userGroupData?.groupRole)">解散群聊</template>
          <template v-else>退出群聊</template>
        </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="30"
        />
      </div>
    </ChatDialog>

    <van-dialog width="90%" v-model:show="showBelongTypeId" show-cancel-button>
      <template #title>
        <div class="w-full flex justify-between items-center px-16 py-11 border-b-[1px]">
          <h1>群类型</h1>
          <div class="w-32 h-32 -mt-3 shrink-0" @click="showBelongTypeId = false">
            <img
              @click="visible = false"
              class="w-full h-full object-cover"
              src="~/assets/img/note-create/close.svg"
              alt=""
            />
          </div>
        </div>
      </template>

      <div class="w-full px-16 py-20 card-list">
        <template v-for="(subItem, subIndex) in groupTypeList" :key="subItem?.id">
          <div
            :class="` h-40 mb-4  relative ${showIndex == subItem.id ? ' border-[#FF9300] border-2  shadow-[0_4px_4px_0px_rgba(0,0,0,0.1)]' : ''}  pl-22 flex justify-start items-center shrink-0 text-xl text-black-6 font-semibold bg-[#F7F8FA] rounded-md`"
            @click="handleTypeClick(subItem)"
          >
            <div class="w-24 h-24 shrink-0 mr-6">
              <img
                class="w-full h-full object-cover"
                :src="item?.typeIcon ? item?.typeIcon : city"
                alt=""
              />
            </div>
            <span class="line-clamp-1">
              {{ subItem.typeName }}
            </span>

            <div
              v-if="showIndex == subItem.id"
              class="absolute rounded-t-md square1 -top-2 -left-2 z-1"
            ></div>
            <div v-if="showIndex == subItem.id" class="w-14 h-14 absolute top-0 left-0 z-2">
              <img class="w-full h-full object-cover" alt="" src="~/assets/img/chat/check.svg" />
            </div>
          </div>

          <div
            v-if="showIndex == subItem.id && subItem?.children.length > 0"
            class="item__child mb-4 w-full relative flex justify-start box-border flex-wrap pl-21 pt-14 bg-[#F7F7F7] rounded-md"
          >
            <div
              :class="`w-32 h-8 absolute -top-[8px] ${subIndex % 2 != 0 ? 'right-[23px]' : 'left-[23px]'} `"
            >
              <img class="w-full h-full" src="~/assets/img/chat/polygon.svg" alt="" />
            </div>
            <template v-for="el in subItem.children" :key="el?.id">
              <div
                @click="childrenHandleTypeClick(el)"
                :class="`${childrenIndex == el.id ? 'text-[#FF9300] border-[#FF9300]  border-[2px] bg-[#FF9300]/[0.08]' : 'bg-white border text-black-6'} py-5 mr-8 mb-12 rounded-[4px] text-sm  box-border px-12`"
              >
                {{ el.typeName }}
              </div>
            </template>
          </div>
        </template>
      </div>

      <template #footer>
        <div class="w-full px-40 pb-30">
          <van-button
            style="font-size: 16px"
            type="primary"
            color="#FF9300"
            round
            block
            @click="changeBelongTypeId"
          >
            确认
          </van-button>
        </div>
      </template>
    </van-dialog>
  </div>
</template>
<script setup>
import city from '~/assets/img/chat/city-one.svg'

const route = useRoute()

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

definePageMeta({
  layout: false
})

useSeoMeta({
  title: '群聊'
})

onMounted(() => {
  userInfoStore.getUserInfo()
  getGroupSetData()
})

let setData = reactive({
  userId: userInfo.value.userId,
  belongTypeIdDictMap: {}
})

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 showBelongTypeId = 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({ groupName: groupName.value })

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

  if (isRemark.value == 2)
    changeGroupName({
      groupNickname: groupName.value
    })

  // showDialog.value = false
}

// groupName 修改群名称
// belongTypeId 群聊类型
// groupAvatar 群头像
// isNeedConfirm  是否开启群验证 0 否 1 是
// isPublic 是否公开展示 0隐藏 1公开

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

    if (data) {
      userGroupData.value[Object.keys(body)[0]] = groupName.value

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

// 是否开启群验证
const changeIsNeedConfirm = async () => {
  changeGroupBelongTypeIdIsNeedConfirm({ isNeedConfirm: changeStateBoolean(isNeedConfirm.value) })
}

// 是否公开展示
const changeIsPublic = async () => {
  changeGroupBelongTypeIdIsNeedConfirm({ isPublic: changeStateBoolean(isPublic.value) })
}

const showIndex = ref(null)
const childrenIndex = ref(null)

const groupTypeList = ref([])
const subTypeList = ref([])
const groupTypeName = ref('')

// 选中群类型的方法
const handleTypeClick = (item) => {
  if (showIndex.value == item?.id) {
    showIndex.value = null
    subTypeList.value = []
  } else {
    showIndex.value = item.id
    subTypeList.value = item.children
  }
}
// 选中群类型子集的方法
const childrenHandleTypeClick = (item) => {
  childrenIndex.value = item.id
  groupTypeName.value = item.typeName
}

// 获取群类型
async function getTreeType() {
  if (isRankAndFiler(userGroupData.value?.groupRole)) {
    try {
      const { data } = await request('/website/tourGroupType/treeType')
      if (Array.isArray(data) && data.length) {
        groupTypeList.value = data

        data.map((item) => {
          item.children.map((el) => {
            if (el.id == setData?.belongTypeId) {
              showIndex.value = item.id
              childrenIndex.value = setData.belongTypeId
              subTypeList.value = item.children
            }
          })
        })

        showBelongTypeId.value = true
      } else {
        groupTypeList.value = []
      }
    } finally {
    }
  } else {
    return
  }
}

// 群聊类型
const changeBelongTypeId = async () => {
  if (childrenIndex.value != setData.belongTypeId) {
    changeGroupBelongTypeIdIsNeedConfirm({ belongTypeId: childrenIndex.value })
  }
  showBelongTypeId = false
}

// 修改 群聊类型  是否开启群验证
async function changeGroupBelongTypeIdIsNeedConfirm(body) {
  try {
    const { data } = await request('/website/tourGroup/updateGroup', {
      method: 'post',
      body: {
        groupId: setData.id,
        ...body
      }
    })
    if (data) {
      if ((userGroupData.value[Object.keys(body)[0]] = 'belongTypeId')) {
        setData.belongTypeIdDictMap.name = groupTypeName.value
      }
      // showSuccessToast('修改成功')
      return
    }
  } 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.value.groupRemark = groupName.value
      } else {
        userGroupData.value[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(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 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 = () => {
  navigateTo({
    path: '/chat/announcement',
    query: {
      groupId: setData?.id,
      userId: userInfo.value.userId,
      groupRole: userGroupData.value?.groupRole
    }
  })
}

// 修改群介绍
const handleDescription = () => {
  if (isRankAndFiler(userGroupData.value?.groupRole)) {
    showDialog({
      width: 260,
      title: '群介绍',
      message: setData.description,
      confirmButtonColor: '#FF9400'
    }).then(() => {
      // on close
    })
  } else {
    showDialog({
      width: 260,
      title: '群介绍',
      message: setData.description,
      confirmButtonColor: '#FF9400'
    }).then(() => {
      // on close
    })
  }
}

// 退出群聊
function handleExitGroupChat() {
  showConfirmDialog({
    width: 260,
    title: '提示',
    message: `是否${isRankAndFiler(userGroupData?.groupRole) ? '解散' : '退出'}当前群聊${setData?.groupName ? `"${setData?.groupName}"` : ''}`,
    confirmButtonColor: '#FF9300'
  })
    .then(async () => {
      const res = await request('/website/tourGroup/exitGroup', {
        query: {
          groupId: setData.id
        }
      })
      if (res && res?.success) {
        navigateTo({
          path: '/profile/my-news',
          replace: true
        })
      }
    })
    .catch(() => {})
}
</script>
<style lang="scss" scoped>
::v-deep .van-dialog__header {
  padding-top: 21px;
}

.card-list {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  grid-auto-flow: dense; /* 确保项目会填充所有的网格单元 */
  grid-gap: 12px;

  .item__child {
    grid-column: span 2;
  }

  .square1 {
    width: 0;
    height: 0;
    border-bottom: 28px solid transparent; /* 创建三角形 */
    border-left: 28px solid #ff9300; /* 三角形的颜色 */
  }
}
</style>
