<template>
  <div>
    <!--pages/socks/socks.wxml-->
    <div class="news" @click="outbtn">
      <!-- <div class="chat-notice" v-if="userInfo">系统消息: 欢迎 {{ userInfo.name }} 加入聊天室</div> -->

      <div class="historycon">
        <scroll-view scroll-y="true" class="history" :scroll-top="scrollTop">
          <div v-for="(item,i) in newslist" :key="i" :id="'scroll'-index">
            <!-- 历史消息 -->

            <!-- <div class="chat-news">
                <div style="text-align: left;padding-left: 20rpx;">
                <img class='new_img' src="{{item.avatarUrl? item.avatarUrl:'images/avator.png'}}"></img>
                <text class="name">{{ item.name }}{{item.date}}</text>
                </div>
                <div class='you_left'>
                <block v-if="{{item.type=='text'}}">
                <div class='new_txt'>{{item.content}}</div>
                </block>
                <block v-if="{{item.type=='img'}}">
                <img class="selectImg" src="{{item.images}}"></img>
                </block>
                </div>
            </div>-->

            <!-- <div>{{item.date}}</div> -->

            <!--自己的消息 -->
            <div class="chat-news chat-news-my" v-if="item.name == userInfo.name">
              <div class="my_right">
                <div class="new_txt">{{item.content}}</div>
                <!-- <img
                  class="selectImg"
                  :src="item.images"
                  :data-src="item.images"
                  lazy-load="true"
                  @bindtap="previewImg"
                />-->
              </div>
              <div style="text-align: right;">
                <text class="name">{{ item.name }}</text>
              </div>
              <!--  v-if="item.type=='text'"  v-if="item.type=='img'"-->
            </div>

            <!-- 别人的消息 -->

            <div class="chat-news" v-else>
              <div style="text-align: left; ">
                <!-- <img class="new_img" :src="item.avatarUrl? item.avatarUrl:''" /> -->
                <text class="name">{{ item.name }}</text>
              </div>
              <!-- v-if="item.type=='text'"  v-if="item.type=='img'" -->
              <div class="you_left">
                <div>
                  <div class="new_txt">{{item.content}}</div>
                </div>

                <!-- <div>
                  <img
                    class="selectImg"
                    :src="item.images"
                    :data-src="item.images"
                    lazy-load="true"
                    bindtap="previewImg"
                  />
                </div>-->
              </div>
            </div>
          </div>
        </scroll-view>
      </div>
    </div>

    <div id="flag"></div>

    <!-- 聊天输入 -->

    <div class="message">
      <div bindreset="cleanInput" class="sendMessage">
        <!-- style="width:62%" 快手 -->
        <input type="text" placeholder="请输入聊天内容.." v-model="message"/>

        <div class="add" @click="inCrease">+</div>
        <!-- style="background:#1aad19" 快手 -->
        <button type="primary" @click="send" formType="reset" size="small" button-hover="blue" >发送</button>
      </div>

      <div :class=" aniStyle?' increased slideup':'increased slidedown'" v-if="increase">
        <div class="img" bindtap="chooseImage">相册</div>
      </div>
    </div>
  </div>
</template>

<script>
import websocket from "@/utils/websocket";
import { formatDate } from "@/utils/assist.js";
import { mapGetters } from "vuex";
import loginApi from '@/apis/login'
export default {
  data() {
    return {
      newslist: [],
      userInfo: {},
      localImg: "@/assets/images/head.png",
      scrollTop: 0,
      increase: false, //图片添加区域隐藏
      aniStyle: true, //动画效果
      message: "",
      previewImgList: [],
      vendorID: 0,
      vendorOrderID: "",
      receiveID: "",
    };
  },
  computed: {
    ...mapGetters({
      selfInfo: "login/selfInfo",
      storeID:"indexPage/storeID",
      storeInfo: "indexPage/storeInfo",
    }),
  },
  async onLoad(query) {
    // console.log("页面参数", query);
    // console.log("storeInfo", this.storeInfo);
    this.vendorID = Number(query.vendorID);
    this.vendorOrderID = query.vendorOrderID;
    let res = await loginApi.getUsers(this.storeInfo.tel1);
	if(res.data){
		this.receiveID = res.data[0].userID;
		// console.log("res1111111111", res.data[0]);
	}
    if (this.selfInfo) {
      this.userInfo = this.selfInfo;
      console.log(this.userInfo);
    }
    
    let chatInfo = await loginApi.getImMessageRecord(this.vendorOrderID)

    console.log("聊天记录", chatInfo);
    if (chatInfo) {
      this.newslist = chatInfo
    }
    //调通接口
    let token = uni.getStorageSync("token") ? uni.getStorageSync("token") : store.getters['login/tmpData'].token;
    //let url = `ws://111.231.218.230:8080/v2/event/TestWebsocket?token=${token}&vendorOrderID=${this.vendorOrderID}`// beta 地址
    let url = `wss://www.jxc4.com:443/v2/event/TestWebsocket?token=${token}&vendorOrderID=${this.vendorOrderID}`; //服务器地址
    websocket.connect(this.userInfo, url, (res) => {
      // console.log(JSON.parse(res.data))
      let list = [];
      list = this.newslist;
      console.log(JSON.parse(res.data));
      // console.log('返回的聊天数据', JSON.parse(res.data));
      // console.log('------------------------------分隔符-----------------------');
      if (res.data && res.data.length > 0) {
        list.push(JSON.parse(res.data));
      }
      this.newslist = list;
    });
  },
  // 页面卸载
  onUnload() {
    uni.closeSocket();
    // wx.showToast({
    //   title: "连接已断开~",
    //   icon: "none",
    //   duration: 2000,
    // });
  },
  methods: {
    //事件处理函数
    send() {
      console.log("this.message", this.message);
      var flag = this;
      if (this.message.trim() == "") {
        uni.showToast({
          title: "消息不能为空哦~",
          icon: "none",
          duration: 2000,
        });
      } else {
        setTimeout(() => {
          this.increase = false;
        }, 500);
        console.log(this.storeID);

        websocket.send(
          JSON.stringify(
            {
              content: this.message,
              messageType: 1,
              name: this.userInfo.name,
              //avatarUrl: this.userInfo.avatarUrl,
              userID: this.userInfo.userID,
              receiveID: this.receiveID,
              storeID: this.storeID[0],
              vendorID: this.vendorID,
              vendorOrderID: this.vendorOrderID,
            },
          )
        );
        console.log("发送完后的 list", this.newslist);
        this.cleanInput();
        this.bottom();
      }
    },

    //监听input值的改变
    // bindChange(res) {
    //   this.message = res.detail.value;
    // },

    cleanInput() {
      //button会自动清空，所以不能再次清空而是应该给他设置目前的input值
      this.message = "";
    },

    inCrease() {
      this.increase = true;
      this.aniStyle = true;
    },

    //点击空白隐藏message下选框
    outbtn() {
      this.increase = false;
      this.aniStyle = true;
    },

    //发送图片
    chooseImage() {
      console.log('发送图片-------------')
      var that = this;
      uni.chooseImage({
        count: 1, // 默认9
        sizeType: ["original", "compressed"], // 可以指定是原图还是压缩图，默认二者都有
        sourceType: ["album", "camera"], // 可以指定来源是相册还是相机，默认二者都有
        success: function (res) {
          // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
          var tempFilePaths = res.tempFilePaths;
          // console.log(tempFilePaths)
          uni.uploadFile({
            url: "wss://www.xxx.cn", //服务器地址
            filePath: tempFilePaths[0],
            name: "file",
            headers: {
              "Content-Type": "form-data",
            },
            success: function (res) {
              if (res.data) {
                that.setData({
                  increase: false,
                });
                websocket.send(
                  '{"images":"' +
                  res.data +
                  '","date":"' +
                  formatDate(new Date()) +
                  '","messageType":"2","name":"' +
                  this.userInfo.name +
                  '","avatarUrl":"' +
                  this.userInfo.avatarUrl +
                  '"}'
                );
                this.bottom();
              }
            },
          });
        },
      });
    },

    //图片预览
    previewImg(e) {
      var that = this;
      //必须给对应的wxml的image标签设置data-set=“图片路径”，否则接收不到
      var res = e.target.dataset.src;
      var list = this.previewImgList; //页面的图片集合数组
      //判断res在数组中是否存在，不存在则push到数组中, -1表示res不存在
      if (list.indexOf(res) == -1) {
        this.previewImgList.push(res);
      }

      uni.previewImage({
        current: res, // 当前显示图片的http链接
        urls: that.previewImgList, // 需要预览的图片http链接列表
      });
    },
    bottom() {
      uni.createSelectorQuery()
        .select("#flag")
        .boundingClientRect(function (rect) {
          // 使页面滚动到底部\
          console.log("rect", rect);
          uni.pageScrollTo({
            scrollTop: rect.bottom,
          });
        })
        .exec();
    },
    //聊天消息始终显示最底端
    // bottom() {
    //   var query = wx.createSelectorQuery();
    //   query.select("#flag").boundingClientRect();
    //   query.selectViewport().scrollOffset();
    //   query.exec(function (res) {
    //     wx.pageScrollTo({
    //       scrollTop: res[0].bottom, // #the-id节点的下边界坐标
    //     });
    //     //res[1].scrollTop; // 显示区域的竖直滚动位置
    //   });
    // },
  },
};
</script>

<style lang="scss" scoped>
@import "./online-contact.scss";
</style>