<template>
  <!-- style="padding:14px 0 4px;" -->
  <Theme>
    <view
      class="message-list__wrap"
      :style="{ height: props.height ? props.height : 'auto' }"
    >
      <scroll-view
        :style="{ height: '100%' }"
        scroll-y
        :scroll-top="
          scrollTopAfterListUpdated
            ? scrollTopAfterListUpdated
            : listNodeInfo
            ? listNodeInfo.height - props.tabbarHeight
            : 0
        "
        :scroll-with-animation="scrollTopAfterListUpdated <= 0 && true"
        :upper-threshold="1"
        :lower-threshold="props.lowerThreshold"
        class="message-list__scroll"
        @scroll="onScroll"
        @scrolltoupper="onScrolltoupper"
        @scrolltolower="onScrollLower"
      >
        <view class="list_box">
          <!-- 咨询卡片 -->
          <view
            style="
              padding: 4px 30rpx 0;
              position: sticky;
              top: -2px;
              left: 0;
              z-index: 10;
              background-color: #fafafa;
            "
          >
            <ConsultCard></ConsultCard>
            <!-- <view class="list_head" v-else>
              <view class="list_head-left">
                <image class="list_head-avatar" :src="avatar"></image>
                <view>
                  <view class="list_head-nickname">{{ nickname }}</view>
                  <view class="list_head-online">
                    <text class="list_head-online-status"></text>
                    <text>{{ $t("在线") }}</text>
                  </view>
                </view>
              </view>
              <view class="list_head-right">
                <view
                  class="list_head-right-btn"
                  style="margin-right: 5px"
                  @click="handleOpenModal(1)"
                  >{{ $t("结束会话") }}
                </view>
                <view class="list_head-right-btn" @click="handleOpenModal(2)">{{
                  $t("申请退款")
                }}</view>
              </view>
            </view> -->
          </view>
          <!-- loading start -->
          <view v-if="props.loading">
            <up-loadmore :status="'loading'" :loadingText="$t('正在加载')" />
          </view>
          <!-- loading end -->

          <!-- 消息列表 -->
          <view class="message_list">
            <template v-for="(item, i) in dataList" :key="i">
              <!-- 时间 -->
              <view
                class="message__item message_item__tips"
                v-if="handleTime(i, dataList)"
              >
                <view class="message__item-time">
                  <text>{{ handleTime(i, dataList) }}</text>
                </view>
              </view>
              <!-- 系统关闭提示信息 -->
              <view
                class="message__item message_item__tips"
                v-if="item.msg.type == 'service_close'"
              >
                <view class="message__item-time">
                  <text>{{ $t("会话已关闭") }}</text>
                </view>
              </view>
              <view
                class="message__item message_item__tips"
                v-else-if="item.msg.type == 'service_start'"
              >
                <TipsListCard :datas="item.msg.data"></TipsListCard>
              </view>
              <view
                class="message__item"
                :class="[item.send > 0 ? 'message__item-self' : '']"
                v-else
              >
                <!-- 头像 -->
                <view class="message__item-left">
                  <image
                    v-if="item.send > 0"
                    class="message__item-avatar"
                    :src="item.uimg || getuserInfo.userimg"
                    mode=""
                  ></image>
                  <image
                    v-else
                    class="message__item-avatar"
                    :src="item.simg"
                    mode=""
                  ></image>
                </view>
                <!-- 内容 -->
                <view class="message__item-right">
                  <!-- 图片 -->
                  <view v-if="item.msg.type == 'image'">
                    <up-image
                      :show-loading="true"
                      :src="item.msg.url"
                      width="240rpx"
                      height="240rpx"
                      :fade="false"
                      @click="previewImage(1, [item.msg.url])"
                    ></up-image>
                  </view>
                  <!-- 欢迎信息 -->
                  <view
                    style="padding: 20rpx 30rpx"
                    v-else-if="item.msg.type == 'service_welcome'"
                  >
                    <text>{{ item.msg.body }}</text>
                  </view>
                  <!-- 文本 -->
                  <view style="padding: 20rpx 30rpx" v-else>
                    <text>{{ item.msg.text || "" }}</text>
                  </view>
                </view>
                <view class="message__item-status">
                  <up-loading-icon
                    mode="circle"
                    size="40rpx"
                    v-if="item.loading"
                  ></up-loading-icon>
                </view>
              </view>
            </template>
          </view>
        </view>
      </scroll-view>
    </view>

    <Popup
      ref="tipPopupRef"
      mode="center"
      class="message_list_tip_popup"
      title="提示"
    >
      <template #content>
        <view class="popup_content">
          <text>{{ $t(tipPopupContent) }}</text>
        </view>
      </template>
      <template #footer>
        <view class="popup__footer">
          <view class="popup__footer-btn" @click="onClose">{{
            $t("取消")
          }}</view>
          <view
            class="popup__footer-btn popup__footer-btn__confirm"
            @click="onConfirm"
          >
            <up-loading-icon
              size="30rpx"
              style="margin-right: 12rpx"
              v-if="isSubmitting"
            ></up-loading-icon>
            <text>{{ $t("确认") }}</text>
          </view>
        </view>
      </template>
    </Popup>
  </Theme>
</template>

<script setup>
import {
  ref,
  getCurrentInstance,
  nextTick,
  onMounted,
  watch,
  computed,
  inject,
} from "vue";
import { t } from "@/locale";
import { storeToRefs } from "pinia";
import { onReady } from "@dcloudio/uni-app";
import { query, TimeOut, format, Toast } from "@/utils";
import Popup from "@/components/popup.vue";
import ConsultCard from "./consultCard.vue";
import QuestionCard from "./questionCard.vue";
import TipsListCard from "./tipsListCard.vue";
import { useUserStore, useMessageStore } from "@/store";
import useTools from "../hooks/useTools";
import { RONGIMCALL_PAY_RETURN } from "@/api";

const props = defineProps({
  lowerThreshold: {
    type: Number,
    default: 50,
  },
  height: {
    type: String,
    default: "",
  },
  listHeight: {
    type: Number,
    default: 0,
  },
  tabbarHeight: {
    type: Number,
    default: 0,
  },
  dataList: {
    type: Array,
    default() {
      return [];
    },
  },
  loading: {
    type: Boolean,
    default: false,
  },
});

const emits = defineEmits(["on-scroll", "on-scroll-top", "on-scroll-bottom"]);

const tipPopupRef = ref(null);
const tipPopupContent = ref("");
const popupFlag = ref(0);
const isSubmitting = ref(false);

const channelData = inject("channelData");
const channelID = inject("channel");
const payStatus = ref(0);
const avatar = ref("");
const nickname = ref("");
const useUser = useUserStore();
const { getuserInfo } = storeToRefs(useUser);
const useMessage = useMessageStore();
const { handleTime } = useTools();

const scrollTopAfterListUpdated = ref(0);
const _this = getCurrentInstance();
const currentScrollTop = ref(0);
const oldListNodeInfo = ref(null);
const listNodeInfo = ref(null);
const isInit = ref(true);

const scrollTop = computed(() => {
  const listHeight = listNodeInfo.value ? listNodeInfo.value.height : 0;
  const boxHeight = props.listHeight;

  let scrollHeight = listHeight - boxHeight - props.tabbarHeight;

  return scrollHeight > 50 ? scrollHeight : 0;
});

watch(
  () => channelData.value,
  (newData) => {
    payStatus.value = newData ? newData.openInfo.status : 0;
    avatar.value = newData ? newData.openInfo.simg : "";
    nickname.value = newData ? newData.openInfo.sname : "";
  },
  {
    deep: true,
  }
);

watch(
  () => props.height,
  (newHeight) => {
    computeScrollHeight();
  }
);

watch(
  () => props.dataList.length,
  (newLen, oldLen) => {
    if (newLen - oldLen > 0 && isInit.value) {
      computeScrollHeight().then(() => {
        isInit.value = false;
      });
    }
  },
  { immediate: true }
);

watch(
  () => props.loading,
  (newState, oldState) => {
    nextTick(async () => {
      if (newState == false && oldState == true && oldListNodeInfo.value) {
        oldListNodeInfo.value = listNodeInfo.value;
        listNodeInfo.value = await query(".list_box", _this);
        const value =
          listNodeInfo.value.height -
          oldListNodeInfo.value?.height -
          props.tabbarHeight +
          currentScrollTop.value;
        scrollTopAfterListUpdated.value = value > 0 ? value : 1;
        console.log(
          "scrollTopAfterListUpdated.value",
          scrollTopAfterListUpdated.value
        );
      }
    });
  }
);

function updateInitState(state) {
  isInit.value = state == true ? state : false;
}

function handleOpenModal(flag) {
  popupFlag.value = flag;
  if (flag == 1) {
    tipPopupContent.value = "page.user_chat.tipPopupContentForCloseChat";
  } else if (flag == 2) {
    tipPopupContent.value = "page.user_chat.tipPopupContentForRefund";
  }
  tipPopupRef.value && tipPopupRef.value.open();
}

function onClose() {
  tipPopupRef.value && tipPopupRef.value.close();
}

function onConfirm() {
  if (isSubmitting.value) return;
  isSubmitting.value = true;
  if (popupFlag.value == 1) {
    useMessage.closeChannel().then((result) => {
      Toast(result.msg);
      useMessage.updateStatus(channelID.value, 0);
      isSubmitting.value = false;
      tipPopupRef.value && tipPopupRef.value.close();
    });
  } else if (popupFlag.value == 2) {
    RONGIMCALL_PAY_RETURN()
      .then((result) => {
        Toast(result.msg);
        isSubmitting.value = false;
        tipPopupRef.value && tipPopupRef.value.close();
      })
      .catch((err) => {
        Toast(err.msg);
      });
  }
}

function previewImage(index, urls) {
  uni.previewImage({
    current: index,
    urls: urls,
    success() {},
  });
}

function computeScrollHeight() {
  return new Promise((resolve, reject) => {
    nextTick(() => {
      let timer = TimeOut(async () => {
        oldListNodeInfo.value = listNodeInfo.value;
        listNodeInfo.value = null;
        listNodeInfo.value = await query(".list_box", _this);
        scrollTopAfterListUpdated.value = 0;
        resolve(listNodeInfo.value);
      }, 50);
    });
  });
}

// 滚动到顶部
function onScrolltoupper() {
  emits("on-scroll-top");
}

function onScrollLower() {
  emits("on-scroll-bottom");
}

function onScroll(e) {
  currentScrollTop.value = e.detail.scrollTop;
  emits("on-scroll", e);
}

defineExpose({
  computeScrollHeight,
  updateInitState,
});
</script>

<style scoped lang="less">
.message-list__wrap {
  width: 100%;
  height: 100%;
  overflow: hidden;
}

.message-list__scroll {
  padding: 0 0rpx 0rpx;
  box-sizing: border-box;
}

.list_box {
  position: relative;
}

.list_head {
  width: 100%;
  padding: 20rpx 0;
  display: flex;
  justify-content: space-between;
  align-items: center;

  .list_head-left {
    display: flex;
    align-items: center;
  }

  .list_head-avatar {
    overflow: hidden;
    width: 80rpx;
    height: 80rpx;
    margin-right: 16rpx;
    border-radius: 50%;
  }

  .list_head-nickname {
    font-weight: 600;
    font-size: 30rpx;
  }

  .list_head-online {
    display: flex;
    align-items: center;
    font-size: 24rpx;
    margin-top: 3px;
  }

  .list_head-online-status {
    width: 20rpx;
    height: 20rpx;
    margin-right: 4px;
    background-color: #39b54a;
    border-radius: 50%;
  }

  .list_head-right {
    display: flex;
  }

  .list_head-right-btn {
    padding: 0 20rpx;
    height: 52rpx;
    background-color: var(--black);
    border-radius: 26rpx;
    color: var(--light);
    font-size: 24rpx;
    line-height: 52rpx;
  }
}

.message_list {
  margin-top: 30rpx;
  padding: 20rpx 30rpx 30rpx;

  .message__item {
    width: 100%;
    display: flex;
    align-items: flex-start;
    margin-bottom: 30rpx;
  }

  .message__item-self {
    display: flex;
    flex-direction: row-reverse;

    .message__item-right {
      margin-left: 0;
      margin-right: 16rpx;
      background-color: var(--black);
      color: #fff;
    }

    .message__item-status {
      margin-left: 0;
      margin-right: 12rpx;
    }
  }

  .message_item__tips {
    justify-content: center;
    margin-bottom: 24rpx;
    font-size: 24rpx;
    color: #767676;
  }

  .message__item-avatar {
    width: 80rpx;
    height: 80rpx;
    border-radius: 50%;
  }

  .message__item-right {
    overflow: hidden;
    max-width: calc(100% - (80rpx * 2) - 16rpx - 20rpx - 40rpx - 12rpx);
    margin-left: 16rpx;
    border-radius: 20rpx;
    background: #fafafa;
    // text-align: justify;
    // word-break: break-all;
    word-wrap: break-word;
    color: #3d3d3d;
    font-size: 28rpx;
  }

  .message__item-status {
    width: 40rpx;
    height: 40rpx;
    margin-left: 12rpx;
  }
}
</style>


<style lang="less" scoped>
.popup_content {
  text-align: center;
  line-height: 1.5;
}

.popup__footer {
  display: flex;
  justify-content: space-around;

  .popup__footer-btn {
    padding: 12rpx 30rpx;
    border: 1rpx solid #333;
    border-radius: 12rpx;
  }

  .popup__footer-btn__confirm {
    display: flex;
    align-items: center;
    background-color: var(--black);
    color: var(--light);
  }
}

.message_list_tip_popup :deep(.u-popup__content) {
  width: 85%;
}

.message_list_tip_popup :deep(.pop .conts),
.message_list_tip_popup :deep(.pop .top) {
  justify-content: center;
}
</style>