<template>
<view>
  <!-- #ifdef H5 -->
  <scroll-view
    ref="conversation-list"
    class="conversation-list"
    :style="{'background-color': conversationList.length?'#FFF':''}"
    :scroll-top="listScrollTop"
    scroll-y="true"
    @scrolltolower="loadMore()"
    @scroll="onScroll"
  >
    <!-- #endif -->
    <!-- #ifndef H5 -->
    <uni-list
      ref="conversation-list"
      class="conversation-list"
      :style="{'height':wHeight,'width':'750rpx'}"
      :border="false"
    >
    <!-- #endif -->

      <!-- 注意：nvue下 list 内必须是 cell，所以元素都需要在uni-list-chat内 -->
      <uni-im-conversation v-for="(item,index) in conversationList" :key="item.id" :id="item.id"
        :conversation="item"
        class="conversation-list-item" :class="{'activeConversation':activeConversationId == item.id,'focus':item.focus}"
        @click="clickItem(item)"
        @contextmenu.prevent.native="openConversationMenu($event,index)"
      >
        <template v-if="canCheck" #left>
          <view style="justify-content: center;">
            <view class="check-box" :class="{checked:isCheck(item)}">
              <uni-icons
                v-if="isCheck(item)"
                color="#FFF"
                type="checkmarkempty"
              />
            </view>
          </view>
        </template>
      </uni-im-conversation>

      <!-- #ifdef APP-NVUE -->
      <!-- nvue端appear（元素一旦显示在可视窗口中）就触发加载更多。-->
      <cell v-if="conversationList.length" @appear="loadMore()" />
      <!-- #endif -->
      <uni-list-item :custom-style="{backgroundColor:'#f5f5f5',padding:0}" style="margin-top: 5px;" :border="false">
        <template #body>
          <template v-if="!keyword">
            <uni-im-load-state
              class="tip"
              :content-text="loadMoreContentText"
              :status="conversationHasMore?'loading':'noMore'"
            />
          </template>
          <template v-else>
            <text v-if="conversationList.length === 0" style="text-align: center;flex: 1;margin: 8px;color: #aaa;">
              没有相关数据
            </text>
          </template>
        </template>
      </uni-list-item>

      <!-- #ifndef H5 -->
    </uni-list>
    <!-- #endif -->
    <!-- #ifdef H5 -->
  </scroll-view>
  <!-- #endif -->


  <!-- #ifdef H5 -->
  <uni-im-contextmenu ref="uni-im-contextmenu" />
  <!-- #endif -->
</view>
</template>

<script>
import uniIm from '@/uni_modules/uni-im/sdk/index.js';
const db = uniCloud.database();
let currentScrollTop = 0;
export default {
  props: {
    keyword: {
      type: String,
      default: ''
    },
    activeConversationId: {
      type: [String, Boolean],
      default: ''
    },
    canCheck: {
      type: Boolean,
      default: false
    },
    checkedList: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      listScrollTop: 0,
    }
  },
  computed: {
    conversationHasMore() {
      return uniIm.conversation.hasMore
    },
    // #ifdef APP-NVUE
    wHeight() {
      return uni.getSystemInfoSync().windowHeight + 'px'
    },
    // #endif
    loadMoreContentText() {
      return {
        contentrefresh: "正在加载...",
        contentnomore: (this.conversationList.length ? "没有更多数据了" : "没有会话数据")
      }
    },
    conversationList() {
      return uniIm.conversation.dataList
        // #ifdef H5
        .filter(i => i.title.toLowerCase().includes(this.keyword.toLowerCase()))
        // #endif
        .filter(i => !i.hidden)
    }
  },
  watch: {
    conversationList: {
      handler() {
        // console.log('更新会话列表',this.conversationList)
        this.$emit('change', this.conversationList)
      },
      deep: true
    },
    activeConversationId(activeConversationId) {
      // #ifdef H5
      // 重试次数
      let tryIndex = 0
      const scrollToCurrentConversation = () => {
        if (tryIndex > 5) {
          return
        }
        const query = uni.createSelectorQuery().in(this);
        query.select('#' + activeConversationId).boundingClientRect(data => {
          if (!data) {
            // console.log('找不到 showMsgByIndex #'+activeConversationId,'tryIndex:'+tryIndex);
            tryIndex++
            setTimeout(() => scrollToCurrentConversation(), 300)
            return
          } else {
            // console.log(data);
          }
          let listHeight = document.querySelector('.conversation-list')?.clientHeight
          if (data.top - 70 < listHeight) {
            return
          }
          this.listScrollTop = ''
          this.$nextTick(() => {
            this.listScrollTop = currentScrollTop - listHeight + data.top + data.height
            // console.log('this.listScrollTop',this.listScrollTop);
          })
        }).exec()
      }
      scrollToCurrentConversation()
      // #endif
    }
  },
  mounted() {},
  methods: {
    onScroll(e) {
      currentScrollTop = e.detail.scrollTop
      this.$emit('onScroll', e)
    },
    isCheck(item) {
      return this.checkedList.some(i => i.id === item.id)
    },
    clickItem(item) {
      if (this.canCheck) {
        // 判断是否选中
        let checkedList = this.checkedList;
        if (this.isCheck(item)) {
          checkedList.splice(checkedList.findIndex(i => i.id === item.id), 1)
        } else {
          checkedList.push(item)
        }
        this.$emit('update:checkedList', checkedList)
      }
      this.$emit('clickItem', item)
    },
    openConversationMenu(e, index) {
      // #ifdef H5
      let conversation = this.conversationList[index]
      conversation.focus = true
      const myContextmenu = this.$refs['uni-im-contextmenu']
      const position = {
        "top": e.clientY + 35,
        "left": e.clientX
      }
      let menuList = [{
                        "title": "置顶",
                        "action": () => {
                          conversation.pinned = !conversation.pinned
                          db.collection('uni-im-conversation')
                            .doc(conversation._id)
                            .update({
                              "pinned": conversation.pinned
                            })
                            .then((e) => {
                              console.log('updated 置顶', e.result.updated, conversation._id)
                            })
                            .catch(() => {
                              uni.showToast({
                                title: '服务端错误，置顶失败，请稍后重试',
                                icon: 'none'
                              });
                              conversation.pinned = !conversation.pinned
                            })
                        }
                      },
                      {
                        "title": conversation.mute ? "允许消息通知" : "消息免打扰",
                        "action": () => {
                          console.log('mute 允许消息通知 / 消息免打扰')
                          conversation.changeMute()
                        }
                      },
                      // {
                      //   "title":"复制会话id",
                      //   "action":()=>{
                      //      uni.setClipboardData({
                      //        data:conversation.id,
                      //        showToast:false
                      //      })
                      //   }
                      // },
                      {
                        "title": "移除会话",
                        "action": () => conversation.hide()
                      }
      ]
      if (conversation.pinned) {
        menuList[0].title = "取消置顶"
      }
      myContextmenu.show(position, menuList)
      myContextmenu.onClose(() => {
        conversation.focus = false
      })
      // #endif
    },
    async loadMore() {
      let data = await uniIm.conversation.loadMore()
      // console.log('加载到新的会话数据',data);
      return data
    }
  }
}
</script>

<style lang="scss" scoped>
  .conversation-list,
  .tip {
    flex: 1;
  }

  .conversation-list .conversation-list-item.focus {
    border: 2px solid #1ab94e;
  }

  .conversation-list .conversation-list-item {
    /* #ifdef H5 */
    cursor: pointer;
    /* #endif */
    border: 2px solid transparent;
    border-radius: 5px;
    margin: 0 5px;
  }

  /* #ifdef H5 */
  .conversation-list .conversation-list-item ::v-deep .uni-list-chat__content-title {
    font-size: 14px;
  }

  .conversation-list ::v-deep .conversation-list-item .uni-list--border {
    display: none;
  }
  .conversation-list ::v-deep .conversation-list-item .uni-list-chat__container {
    padding: 8px 8px 8px 6px;
  }
  /* #endif */

  .conversation-list .conversation-list-item.activeConversation {
    background-color: #f1f1f1;
  }

  .check-box {
    border: 1px solid #ccc;
    width: 20px;
    height: 20px;
    border-radius: 2px;
    margin-right: 10px;
  }

  .check-box.checked {
    background-color: #00a953;
    border-color: #00a953;
  }
</style>