<script setup>
  import TUIChatEngine, {
    TUIStore,
    StoreName,
    TUIChatService
  } from '@tencentcloud/chat-uikit-engine-lite'
  import { ref, watch, onMounted, onUnmounted } from 'vue'
  import { useUI } from '../../utils/use-ui'
  import { CHAT_MSG_CUSTOM_TYPE } from '../../TUIKit/constant'
  import { isEnabledMessageReadReceiptGlobal } from '../../TUIKit/components/TUIChat/utils/utils'
  import { getFriendList, getGroupList } from '../../utils/storage'

  const { showLoading, hideLoading, showToast, showDialog } = useUI()

  const isShow = defineModel('show', {
    type: Boolean,
    default: false
  })

  const props = defineProps({
    /** 分享类型: 1 直播 2 商品详情*/
    type: {
      type: String,
      default: '2'
    },
    id: {
      type: String,
      default: ''
    },
    /** 分享文本 */
    text: {
      type: String,
      default: ''
    },
    /** 封面图 */
    cover: {
      type: String,
      default: ''
    },
    /** 多少钱 */
    price: {
      type: [String, Number],
      default: ''
    },
    /** 直播用户数据 */
    userLiveData: {
      type: Object,
      default: () => ({})
    }
  })

  const refPopup = ref(null)
  /** 多选状态 */
  const isMultiple = ref(false)
  /** 群列表 */
  const groupList = ref([])
  /** 好友列表 */
  const friendList = ref([])
  /** 选中数据 */
  const selectedList = ref([])

  watch(
    () => isShow.value,
    v => {
      if (v) {
        refPopup.value.open()
      } else {
        refPopup.value.close()
        selectedList.value = []
        isMultiple.value = false
      }
    }
  )

  const onShow = v => {
    isShow.value = v.show
  }

  /** 获取好友列表 */
  const onFriendListUpdated = list => {
    console.log('好友列表=======:', list)
    // #ifdef APP-PLUS
    friendList.value = getFriendList()
    // #endif

    // #ifdef H5
    friendList.value = list
    // #endif

    friendList.value = friendList.value.map(v => {
      return {
        ...v,
        ...(v?.profile || {})
      }
    })

    console.log('好友列表：', friendList.value)
  }

  /** 获取群列表 */
  const onGroupListUpdated = list => {
    console.log('群列表=======:', list)
    // #ifdef APP-PLUS
    groupList.value = getGroupList()

    // #endif

    // #ifdef H5
    groupList.value = list
    // #endif

    console.log('群列表：', groupList.value)
  }

  /** 判断多选状态 */
  const multipleShow = id => {
    return selectedList.value.some(item => item.id === id)
  }

  /**
   * 选项
   * @param item
   * @param state 1 群聊 0 好友
   */
  const onSelect = (item, state) => {
    let data = {}
    if (state) {
      data = {
        id: `GROUP${item.groupID}`,
        name: item.name,
        avatar: item.avatar
      }
    } else {
      data = {
        id: `C2C${item.profile.userID}`,
        name: item.profile.nick || item.profile.userID,
        avatar: item.profile.avatar
      }
    }
    if (isMultiple.value) {
      if (multipleShow(data.id)) {
        selectedList.value = selectedList.value.filter(
          item => item.id !== data.id
        )
      } else {
        if (selectedList.value.length >= 9) {
          showDialog('提示', '最多选择9个', false)
          return
        }
        selectedList.value.push(data)
      }
    } else {
      onConfirm(0, data)
    }
  }

  /** 发送自定义信息数据 */
  const sendCustomData = async item => {
    let to = ''
    let isGroup = false
    if (item.id.includes('GROUP')) {
      // 分割 GROUP
      to = item.id.split('GROUP')[1]
      isGroup = true
    } else {
      to = item.id.split('C2C')[1]
      isGroup = false
    }
    const payload = {
      data: JSON.stringify(
        props.type == 1
          ? {
              id: props.id,
              businessID: CHAT_MSG_CUSTOM_TYPE.LIVE,
              title: props.text,
              cover: props.cover,
              userLiveData: props.userLiveData
            }
          : {
              id: props.id,
              businessID: CHAT_MSG_CUSTOM_TYPE.GOODS,
              title: props.text,
              cover: props.cover,
              price: props.price
            }
      ),
      description: props.text,
      extension: props.text
    }
    const options = {
      to,
      payload,
      conversationType: isGroup
        ? TUIChatEngine.TYPES.CONV_GROUP
        : TUIChatEngine.TYPES.CONV_C2C,
      needReadReceipt: isEnabledMessageReadReceiptGlobal()
    }
    await TUIChatService.sendCustomMessage(options)
  }

  /** 多选分享 */
  const multiSelectShare = async () => {
    showLoading()
    const requests = selectedList.value.map(v => sendCustomData(v))
    await Promise.all(requests)
    hideLoading()
    await showToast('分享成功', 'success')
    isShow.value = false
  }

  /**
   * 确定分享
   * @param state 1 多选 0 单选
   * @param data
   */
  const onConfirm = async (state, item) => {
    if (state == 1 && selectedList.value.length == 0) {
      return
    }
    const show = await showDialog(
      '提示',
      `确定分享${props.type == 1 ? '直播间' : '商品'}吗？`
    )
    if (!show) {
      return
    }
    if (state) {
      multiSelectShare()
    } else {
      showLoading()
      await sendCustomData(item)
      hideLoading()
      await showToast('分享成功', 'success')
      isShow.value = false
    }
  }

  onMounted(() => {
    TUIStore.watch(StoreName.GRP, {
      groupList: onGroupListUpdated
    })

    TUIStore.watch(StoreName.FRIEND, {
      friendList: onFriendListUpdated
    })
  })

  onUnmounted(() => {
    TUIStore.unwatch(StoreName.GRP, {
      groupList: onGroupListUpdated
    })

    TUIStore.unwatch(StoreName.FRIEND, {
      friendList: onFriendListUpdated
    })
  })
</script>

<template>
  <uni-popup
    ref="refPopup"
    safeArea
    type="bottom"
    background-color="#ffffff"
    borderRadius="16rpx 16rpx 0 0"
    @change="onShow"
  >
    <!-- 顶部标题 -->
    <view class="top-box">
      <text
        class="close"
        @click="
          () => {
            if (!isMultiple) {
              isShow = false
            } else {
              selectedList = []
              isMultiple = false
            }
          }
        "
      >
        {{ isMultiple ? '关闭' : '取消' }}
      </text>
      <text class="text">选择聊天</text>
      <view>
        <text
          v-if="isMultiple"
          :class="{ 'on-btn': !selectedList.length > 0 }"
          class="multiple-btn"
          @click="onConfirm(1)"
        >
          {{
            `下一步 ${selectedList.length > 0 ? selectedList.length : ''}`
          }}
        </text>
        <view v-else class="multiple" @click="isMultiple = true">
          多选
        </view>
      </view>
    </view>
    <!-- 选项数据 -->
    <view v-if="selectedList.length > 0" class="option-box">
      <view
        v-for="(item, index) in selectedList"
        :key="index"
        class="option-card"
      >
        <image
          v-if="item?.avatar"
          :src="item?.avatar"
          mode="aspectFill"
          class="avatar"
        ></image>
        <view v-else class="avatar">
          <uni-icons type="contact-filled" size="98rpx"></uni-icons>
        </view>
      </view>
    </view>

    <!-- 列表 -->
    <view scroll-y="true" class="list-box">
      <view
        v-for="(item, index) in groupList"
        :key="index"
        class="item-box"
        @click="onSelect(item, 1)"
      >
        <view v-if="isMultiple" class="box">
          <uni-icons
            v-if="!multipleShow(`GROUP${item?.groupID}`)"
            type="circle"
            color="#b7b7b7"
            size="30"
          ></uni-icons>
          <uni-icons
            v-else
            type="checkbox-filled"
            color="#00d993"
            size="30"
          ></uni-icons>
        </view>
        <view class="card-box">
          <image
            v-if="item?.avatar"
            :src="item?.avatar"
            mode="aspectFill"
            class="head-img"
          ></image>
          <view v-else class="head-img">
            <uni-icons type="contact-filled" size="108rpx"></uni-icons>
          </view>
          <view class="right-box">
            <text class="name">
              {{ item?.name }}
            </text>
            <text class="num">({{ item?.memberCount }}人)</text>
          </view>
        </view>
      </view>
      <!-- 好友列表================== -->
      <view
        v-for="(item, index) in friendList"
        :key="index"
        class="item-box"
        @click="onSelect(item, 0)"
      >
        <view v-if="isMultiple" class="box">
          <uni-icons
            v-if="!multipleShow(`C2C${item?.userID}`)"
            type="circle"
            color="#b7b7b7"
            size="30"
          ></uni-icons>
          <uni-icons
            v-else
            type="checkbox-filled"
            color="#00d993"
            size="30"
          ></uni-icons>
        </view>
        <view class="card-box">
          <image
            v-if="item?.avatar"
            :src="item?.avatar"
            mode="aspectFill"
            class="head-img"
          ></image>
          <view v-else class="head-img">
            <uni-icons type="contact-filled" size="108rpx"></uni-icons>
          </view>
          <view class="right-box">
            <text class="name">
              {{ item?.nick || item?.userID }}
            </text>
          </view>
        </view>
      </view>
    </view>
  </uni-popup>
</template>

<style lang="scss" scoped>
  .top-box {
    padding: 32rpx 24rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
    color: #333333;
    font-weight: 400;
    border-bottom: 2rpx solid #f2f2f2;
    box-sizing: border-box;
    position: relative;
    .close {
      font-size: 28rpx;
    }
    .text {
      position: absolute;
      left: 50%;
      transform: translateX(-50%);
      font-size: 32rpx;
      font-weight: 500;
    }
    .multiple {
      font-size: 28rpx;
    }
    .multiple-btn {
      position: absolute;
      right: 24rpx;
      font-size: 28rpx;
      color: #ffffff;
      background: #00d993;
      border-radius: 8rpx;
      padding: 4rpx 12rpx;
    }
    .on-btn {
      background: #b7b7b7;
    }
  }

  .list-box {
    padding: 22rpx 24rpx;
    height: 46vh;
    overflow-y: auto;
    .item-box + .item-box {
      margin-top: 12rpx;
      padding-top: 12rpx;
      border-top: 2rpx solid #f2f2f2;
    }

    .item-box {
      display: flex;
      align-items: center;
      .box {
        margin-right: 10rpx;
      }
      .card-box {
        display: flex;
        align-items: center;
        .head-img {
          width: 80rpx;
          height: 80rpx;
          border-radius: 80rpx;
          display: flex;
          justify-content: center;
          align-items: center;
          margin-right: 16rpx;
        }
        .right-box {
          display: flex;
          .name {
            flex-shrink: 0;
            max-width: 340rpx;
            font-size: 28rpx;
            font-weight: 500;
            // 显示省略号
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }
          .num {
            margin-left: 8rpx;
            font-size: 24rpx;
            color: #999999;
          }
        }
      }
    }
  }

  .option-box {
    padding: 20rpx 24rpx;
    border-bottom: 2rpx solid #f2f2f2;
    // 超过宽度左右滑动
    overflow-x: auto;
    display: flex;
    align-items: center;
    .option-card + .option-card {
      margin-left: 14rpx;
    }
    .option-card {
      .avatar {
        flex-shrink: 0;
        width: 70rpx;
        height: 70rpx;
        border-radius: 70rpx;
        display: flex;
        justify-content: center;
        align-items: center;
        background: rgb(194, 194, 194);
      }
    }
  }
</style>
