<template>
  <view class='cu-list menu margin-top'>
    <!--只有在聊天列表的chat 才有置顶功能-->
    <view class='cu-item' v-if='chat'>
      <view class='content'>
        <text class='cuIcon-messagefill text-grey'></text>
        <text class='text-grey'>聊天置顶</text>
      </view>
      <view class='action'>
        <switch @change='chatTopChange' :class="isTop?'checked':''" :checked='isTop?true:false'></switch>
      </view>
    </view>
    <view class='cu-item'>
      <view class='content'>
        <text class='cuIcon-settings text-grey'></text>
        <text class='text-grey'>消息免打扰</text>
      </view>
      <view class='action'>
        <switch @change='messageTipsChange' :class="isTips?'checked':''" :checked='isTips?true:false'></switch>
      </view>
    </view>
  </view>
</template>
<script lang='ts' setup>
import {computed, ref} from 'vue'
import {storeToRefs} from 'pinia'
import {useImmunityStore} from '@/store/immunityStore'
import {useChatStore} from '@/store/chatStore'
import {useUserStore} from '@/store/userStore'
import ImmunityApi from '@/api/ImmunityApi'


interface IProps{
  chatId:string
}
const props = defineProps<IProps>();
const isTop = ref(false)
const chatStore = useChatStore()
const immunityStore = useImmunityStore()
const { immunityList } = storeToRefs(immunityStore)
const isTips = computed(() => {
  return immunityList.value.indexOf(props.chatId) > -1
})

const chat = chatStore.getChat(props.chatId)
if (chat) {
  isTop.value = chat.top ?? false
}

const chatTopChange = () => {
  if(chat){
    isTop.value = !isTop.value
    if (isTop.value) {
      chatStore.topChat(props.chatId)
    } else {
      chatStore.cancelTop(props.chatId)
    }
  }
}

const messageTipsChange = (e: TouchEvent) => {
  const userId = useUserStore().getUser()?.id
  if (userId) {
    // @ts-ignore
    if (e.detail.value) {
      ImmunityApi.save(userId, props.chatId).then(() => {
        immunityStore.loadData()
      })
    } else {
      ImmunityApi.delete(userId, props.chatId).then(() => {
        immunityStore.loadData()
      })
    }
  }
}
</script>
<style scoped>

</style>