<template>
  <HeaderNav :title="title" :is-back="true"></HeaderNav>
  <view class="body-background" :style="{
		backgroundImage:'url('+staticImage.wallpaperBgImage+')'
		}"></view>
  <view class="app-wallpaper">
    <view  class="detail-container">
      <view class="detail-content-container">
        <scroll-view class="detail-content"   :scroll-y="true" :scroll-top="scrollTop"
              style="padding-bottom: 90px;box-sizing: border-box;" :style="{height:windowHeihgt-40+'px'}">
          <view id="scroll-view-content">
            <view :class="item.send_user_id === user_id && type === item.type ? 'chat-item my-chat row' : 'chat-item other-chat row'"
                  v-for="(item, index) in messageList">
              <view class="chat-item-content  row">
							<view class="chat-avator " v-if="item.send_user_id !== user_id || type !== item.type">
                  <image mode="aspectFill" class="img" :src="item.avatar ? item.avatar : user.avatar"/>
                </view>
                <view class="chat-content-container " style="max-width: calc(100% - 50px);">
								<view class="chat-time">{{item.user_name}} {{ item.create_time }}</view>
                  <view class="chat-content" style="word-break: break-all;">{{ item.info }}</view>
                </view>
							<view class="chat-avator " v-if="item.send_user_id === user_id && type === item.type">
                  <image mode="aspectFill" class="img" :src="item.avatar ? item.avatar : user.avatar"/>
                </view>
              </view>
            </view>
          </view>

        <view class="detail-input-group-container">
          <view class="detail-input-group row">

            <view class="col">
              <input class="detail-input" v-model="message" type="text"/>
            </view>
            <MzButton
                title="发送"
                font-color="#fff"
                button-color="#4DC3B8"
                button-width="auto"
                class="detail-input-button"
                @click.stop="sendMessage"
            >
            </MzButton>
          </view>
        </view>
        </scroll-view>
      </view>

    </view>
    <view class="detail-background-container">
      <view class="detail-background"></view>
    </view>
  </view>

</template>

<script>
import {
  imghost
} from '@/config/host'
import api from '../../utils/functions.js';
import HeaderNav from '../../components/HeaderNav/Index.vue';
import MzButton from '../../components/MzButton/Index.vue';
import {getToken} from "@/api/chat";
import log from "@/utils/log";

export default {
  components: {
    HeaderNav,
    MzButton
  },
  data: {
    scrollTop:0,
    windowHeihgt: 1000,
    staticImage: {
      wallpaperBgImage: imghost + '/static/image/background.png',
    },
    user: {
      avatar: imghost + '/static/image/banner.png',
      nickname: '清晨的风',
      background: imghost + '/static/image/banner.png',
      sex: '女',
      phone: '15012345678',
      coupons: 221,
      id: 88685,
      birthday: '2002-05-11',
    },
    ableChat: false,
    message: '',
    chat_id: 0,
    type: 0,
    user_id: 0,
    messageList: [],
      title:"在线咨询"
  },
  onLoad(options) {
    this.getToken(options.id, options.type ?? 1);


  },
  onReady() {

  },
  methods: {
    scrollToBottom() {
      this.$nextTick(() => {
        uni.createSelectorQuery().in(this).select('#scroll-view-content').boundingClientRect((res) => {
          let top = res.height - this.windowHeihgt + 500;
          console.log(res)
          console.log(top)
          if (top > 0) {
            this.scrollTop = top;
          }
        }).exec()
      })
    },
    getToken(order_id, type) {
      getToken(order_id, type).then(data => {
        this.chat_id = data.data.chat_id;
        this.type = data.data.type;
        this.user_id = data.data.user_id;
        uni.connectSocket({
          url: data.data.chat_url
        });

        uni.onSocketOpen((res) => {
          this.ableChat = true;
          console.log('WebSocket连接已打开！');
        });

        uni.onSocketClose((res) => {
          this.ableChat = false;
          console.log('WebSocket 已关闭！');
        });

        uni.onSocketMessage((res) => {
          this.newMessage(res);
        })
      })
    },
    newMessage(messages) {
      log(messages);
      messages = JSON.parse(messages.data);
      log(messages);
      if (messages.do_type === 'init') {
        this.messageList = messages.data;
        uni.$u.sleep(200).then(()=>{
          this.scrollToBottom();
        })

        return;
      }

      this.messageList.push(messages);
      log(this.messageList);
      this.scrollToBottom();
    },
    sendMessage() {
      if (!this.message) {
        return uni.showToast({
          title: "消息不能为空",
          icon: 'error'
        })
      }
      uni.showLoading({
        title: '消息发送中...',
        mask: true,
      });
      if (!this.ableChat) {
        setInterval((t) => {
          if (!this.ableChat) {
            return;
          }
          clearInterval(t);
          uni.sendSocketMessage({
            data: this.message
          });
          uni.hideLoading();
        }, 50);
      } else {
        uni.sendSocketMessage({
          data: JSON.stringify({
            do_type: 'add',
            info: this.message,
            msg_type: 1,
            send_user_id: this.user_id,
            type: this.type,
            chat_id: this.chat_id,
          })
        });
        uni.hideLoading();
        this.message = '';
      }
      this.scrollToBottom();
    }
  },
  onPageScroll(res) {

  },
  onUnload() {
    try {
      uni.closeSocket();
    } catch {
    }
  },
  created() {
    this.windowHeihgt = api.navHeight().windowHeihgt;
  }
}
</script>

<style lang="scss">
@import './components/index.scss';
</style>