<template>
  <Theme>
    <view class="wrap">
      <Navbar title="网购助手" fixed border leftShow id="navbar" />
      <ConsultCard
        class="topcard"
        id="top_card"
        :style="{ '--navbarHeight': navbarHeight + 'px' }"
      ></ConsultCard>
      <view
        class="content"
        :style="{
          '--topHeight': topHeight + 'px',
          '--height': bottomHeight + 'px',
          '--keyboardHeight': keyboardHeight + 'px',
          '--contHeight': contHeight + 'px',
          '--navbarHeight': navbarHeight + 'px',
          '--tabbarHeight': tabbarHeight + 'px',
        }"
      >
        <scroll-view
          class="chat_content"
          scroll-anchoring
          :scroll-y="true"
          :scroll-top="scrollTop"
          :lower-threshold="lowerThreshold"
          :refresher-triggered="refresherTriggered"
          :refresher-enabled="refresherEnabled"
          @refresherrefresh="refresherrefresh"
          refresher-default-style="none"
          refresher-background="var(--bg)"
          @scroll="onScroll"
          @scrolltolower="onScrollLower"
        >
          <view class="refresher" v-if="refresherTriggered">
            <up-loadmore :status="'loading'" :loadingText="$t('正在加载')" />
          </view>
          <view class="scroll" id="scroll_items">
            <Message :list="msgList" />
          </view>
        </scroll-view>
      </view>
      <view
        class="new_count"
        :style="{ bottom: bottomHeight + tabbarHeight + 5 + 'px' }"
        v-show="newMessageCount > 0"
        @click="getContHeight"
      >
        <text>{{ newMessageCount }} {{ $t("条新消息") }}</text>
      </view>
      <footer-input
        v-model="message"
        :bottomHeight="tabbarHeight"
        @heights="getFooterHeight"
        @submit="send"
        @linechange="inputHeightChange"
        @imageUp="imageUp"
        ref="footerInputRef"
      />

      <Tabbar page="chat" @getTabbarHeight="getTabbarHeight" />
    </view>
  </Theme>
</template>
<script setup>
import { onUnload, onLoad, onShow } from "@dcloudio/uni-app";
import { ref, nextTick, onMounted, reactive, watch, provide } from "vue";
import Navbar from "@/components/navbar";
import footerInput from "@/components/footer_input";
import Message from "@/components/message";
import Tabbar from "@/components/tabbar";
import ConsultCard from "@/components/message/components/consultCard.vue";
import { query, systemInfo, useGlobal } from "@/utils";
import { RONGIMCALL_HISTORY } from "@/api";
import { useSocketStore, useMessageStore } from "@/store";
import { storeToRefs } from "pinia";

const useSocket = useSocketStore();
const useMessage = useMessageStore();
const { messageMap } = storeToRefs(useMessage);
const bottomHeight = ref(0);
const scrollTop = ref(0);
const keyboardHeight = ref(0);
const contHeight = ref(0);
const newHeight = ref(0);
const message = ref("");
const footerInputRef = ref(null);

const refresherTriggered = ref(false);
const refresherEnabled = ref(true);
const msgList = ref([]);
const page = ref(1);
const pagesize = ref(10);
const total = ref(0);

const channel = ref("");
const firstMsg = ref({});
const lowerThreshold = ref(0);
const distanceFromBottom = ref(0);
const newMessageCount = ref(0);
const bottomSafeDistanceHeight = ref(0);
const tabbarHeight = ref(0);
const topHeight = ref(0);
const navbarHeight = ref(0);

watch(
  () => messageMap.value,
  (newVal, oldVal) => {
    const info = newVal[channel.value];
    if (channel.value && info) {
      msgList.value = info.messageList;
      newMessageCount.value =
        distanceFromBottom.value > lowerThreshold.value ? info.unreadCount : 0;
    }
  },
  { deep: true, immediate: true }
);

provide("onQuestionSend", send);

function onScroll(e) {
  const { detail } = e;
  const distanceForBottom =
    detail.scrollHeight - detail.scrollTop - contHeight.value;
  distanceFromBottom.value = distanceForBottom > 0 ? distanceForBottom : 0;
  if (distanceFromBottom.value <= lowerThreshold.value) {
    useMessage.updateUnreadCount(channel.value, -1);
  }
}
function onScrollLower() {
  useMessage.updateUnreadCount(channel.value, -1);
}
const refresherrefresh = () => {
  refresherTriggered.value = true;
  if (total.value <= page.value * pagesize.value) {
    nextTick(() => {
      refresherTriggered.value = false;
    });
    return;
  }
  page.value += 1;
  nextTick(() => {
    getHistory(true);
  });
};

const getCont = () => {
  nextTick(() => {
    const { windowHeight, statusBarHeight } = systemInfo();
    contHeight.value = windowHeight - statusBarHeight - navbarHeight.value;
  });
};

const getContHeight = (isLoading) => {
  try {
    nextTick(async () => {
      const res = await query("#scroll_items");
      let info = uni.getSystemInfoSync();
      if (isLoading) {
        scrollTop.value = res.height - newHeight.value - navbarHeight.value;
      } else {
        if (info.platform === "ios") {
          scrollTop.value =
            res.height +
            bottomHeight.value -
            keyboardHeight.value +
            tabbarHeight.value;
        } else {
          scrollTop.value =
            res.height -
            bottomHeight.value -
            keyboardHeight.value -
            tabbarHeight.value;
        }
      }
      newHeight.value = res.height;
    });
  } catch (error) {}
};
const getFooterHeight = (res) => {
  nextTick(() => {
    bottomHeight.value = res.height || 0;
    keyboardHeight.value = res.keyboardHeight || 0;
    bottomSafeDistanceHeight.value = res.bottomSafeDistance || 0;
    getContHeight();
  });
};

function send(text) {
  sendMessage({ type: "text", text: text || message.value });
}

const imageUp = (url) => {
  sendMessage({ type: "image", url: url });
};

const sendMessage = (msgObject) => {
  let messageData = reactive({
    type: "service",
    msg: JSON.stringify(msgObject),
    send: 1,
    loading: true,
    status: -1,
  });
  useMessage.updateMessageList(channel.value, messageData, "push");
  getContHeight();
  useMessage
    .sendMessage(msgObject, "service")
    .then((data) => {
      messageData.loading = false;
      messageData.status = 1;
      for (let key in data) {
        if (key != "msg") {
          messageData[key] = data[key];
        }
      }
      useMessage.updateGlobalMapLasttime(`serviceChannel`, data.indate);
    })
    .catch(() => {
      messageData.loading = false;
      messageData.status = 0;
    });
  nextTick(() => {
    footerInputRef.value && footerInputRef.value.clear();
  });
};

const getTabbarHeight = (height) => {
  tabbarHeight.value = height;
};

const inputHeightChange = () => {
  // console.log("输入框高度发送变化");
};
const open = () => {
  useMessage
    .openChannel({
      type: "service",
      socket_id: useSocket.socketId,
    })
    .then(async (res) => {
      firstMsg.value = res.data;
      channel.value = res.data.auth.channel;
      await getHistory();
      await clearCount();
    });
};

const getHistory = async (isLoading = false) => {
  try {
    let para = {
      page: page.value,
      pagesize: pagesize.value,
      type: "service",
    };
    const res = await RONGIMCALL_HISTORY(para);
    const lists = res.data.lists;
    for (let i = 0; i < lists.length; i++) {
      const msgInfo = {
        ...lists[i],
        msg: JSON.parse(lists[i].msg),
      };
      useMessage.updateMessageList(channel.value, msgInfo, "unshift");
    }
    if (lists.length > 0 && page.value == 1) {
      let result = lists[0];
      let lastTime = result
        ? result.indate
        : (Date.now() / 1000).toFixed(0) - 0;
      useMessage.updateGlobalMapLasttime(`serviceChannel`, lastTime);
    }
    total.value = res.data.total;
    !total.value &&
      useMessage.updateMessageList(channel.value, firstMsg.value, "unshift");
    if (total.value <= page.value * pagesize.value) {
      nextTick(() => {
        refresherEnabled.value = false;
      });
    }
    nextTick(() => {
      getContHeight(isLoading);
      refresherTriggered.value = false;
    });
  } catch (error) {}
};

const clearCount = () => {
  useMessage.updateUnreadCount(channel.value, -1);
  useMessage.updateGlobalMapUnreadCount("serviceChannel", -1);
};

const getHeight = async () => {
  try {
    const res = await query("#top_card");
    topHeight.value = res.height;
    const resNav = await query("#navbar");
    navbarHeight.value = resNav.height;
  } catch (error) {}
};

const openAndGetHistory = async () => {
  try {
    await getHeight();
    await open();
    await getCont();
    await getContHeight();
  } catch (error) {
    console.error(error);
  }
};
onMounted(() => {
  nextTick(() => {
    openAndGetHistory();
  });
});
uni.hideTabBar();
onUnload(() => {
  useSocket.send({
    event: "pusher:unsubscribe",
    data: { channel: channel.value },
  });
  clearCount();
});
</script>
<style lang="less" scoped>
@import url("@/style.less");

.wrap {
  background: var(--bg);
  height: 100vh;
  padding-bottom: constant(safe-area-inset-bottom);
  padding-bottom: env(safe-area-inset-bottom);
  .topcard {
    position: sticky;
    top: var(--navbarHeight);
    padding: 0 30rpx;
    background: var(--bg);
    z-index: 10;
  }
  .content {
    width: 100%;
    // padding: 0 30rpx;

    .chat_content {
      height: calc(
        var(--contHeight) - var(--keyboardHeight) - var(--height) -
          var(--tabbarHeight)
      );
      /*  #ifdef  APP-PLUS  */
      padding-bottom: constant(safe-area-inset-bottom);
      padding-bottom: env(safe-area-inset-bottom);
      /*  #endif  */
      /*  #ifdef  H5  */
      padding-bottom: calc(
        var(--tabbarHeight) + var(--height) + constant(safe-area-inset-bottom)
      );
      padding-bottom: calc(
        var(--tabbarHeight) + var(--height) + env(safe-area-inset-bottom)
      );
      // padding-bottom: calc(var(--tabbarHeight) + var(--height));
      /*  #endif  */

      .scroll {
        overflow: hidden;
      }
    }
  }

  .new_count {
    position: fixed;
    bottom: 0;
    right: 16rpx;
    z-index: 20;
    height: 52rpx;
    padding: 0 20rpx;
    border-radius: 26rpx;
    background-color: rgba(0, 0, 0, 1);
    color: #fff;
    font-size: 24rpx;
    line-height: 52rpx;
  }
}
</style>