<template><page-meta :root-font-size="fontSize+'px'"></page-meta>
    <seller-base :show="false">
    <view class="scroll-view-wrapper scroll-view  div container" :style="'height:'+contentHeight+'px'">
        <view class="div common-header-wrap">
            <view :style="'height:'+navHeight+'px'"></view>
            <view class="common-header-holder"></view>
            <view class="common-header-fixed">
            <title-header />
            <uni-nav-bar :title="t_name" class="common-header" left-icon="back" @clickLeft="goBack()">
                <view class="div common-btn btn" slot="right" @click="showPopup('historyVisible')">聊天记录</view>
            </uni-nav-bar>
        </view>
        </view>
        <scroll-view :scroll-y="true" class="scroll-view div" :scroll-into-view="'msg_'+(msg_list.length-1)">
            <view class="dstouch-chat-con">
              <view class="div" v-for="(item,index) in msg_list" :key="index" :id="'msg_'+index">
                  <chat-message :item="getMessage(item,index,0)" :t_id="t_id"></chat-message>
              </view>
            </view>
        </scroll-view>
        <view class="div dstouch-chat-bottom">
            <view class="div chat-input-layout"> <view class="span open-smile"><text class="a iconfont" @click="open_smile">&#xe6cd;</text></view>
                <view class="div input-box">
                    <input type="text" v-model="msg">
                    <view class="div common-btn ds-button-small submit" @click="submit()">发送</view>
                </view>
            </view>
            <view class="div chat-smile-layout" v-if="smile_show">
                <view class="ul">
                    <view class="li" v-for="(smile,index) in smilies_array" :key="index" @click="addSmile(index)"><image mode="aspectFit" class="img" :title="smile.text" :alt="smile.text" :src="getSmile(smile.image)"></view>
                </view>
            </view>
        </view>

        <!--聊天记录-->
        <uni-popup background-color="#fff" ref="historyVisible" type="right" >
            <view :style="'width:'+screenWidth+'px'" class="common-popup-wrapper">
            <view class="div common-header-wrap">
                <view :style="'height:'+navHeight+'px'"></view>
                <view class="common-header-holder"></view>
                <view class="common-header-fixed">
                <title-header />
                <uni-nav-bar title="聊天记录" class="common-header" left-icon="back" @clickLeft="hidePopup('historyVisible')">
                </uni-nav-bar>
            </view>
            </view>
            <view class="scroll-view div common-popup-content">
                <scroll-view style="position: absolute;top:0;right:0;left:0;bottom:0" @scrolltolower="loadMore" scroll-y="true">
                    <view class="div" v-if="historyList && historyList.length">
                        <chat-message v-for="(item,index) in historyList" :key="item.instant_message_id" :item="getMessage(item,index,1)" :t_id="t_id"></chat-message>
                    </view>
                    <empty-record v-else-if="historyList && !historyList.length"></empty-record>
                </scroll-view>
            </view>
        </view>
        </uni-popup>
    </view>
</seller-base>
</template>

<script>
import {getFontSize} from '@/util/common'
import TitleHeader from '../../TitleHeader'
import SellerBase from '../SellerBase'
import ChatMessage from './ChatMessage'
import EmptyRecord from '../../EmptyRecord'

import { mapState, mapActions } from 'vuex'
import { addInstantMessage, getChatHistory, joinChat, setMessage } from '../../../api/sellerInstantMessage'
import { env } from '../../../static/config'
export default {
  data(){
    return {
      canReconnect:true,
      navHeight: 0,
      screenWidth:0,
      contentHeight:0,
      params: { 'page': 0, 'per_page': 20 },
      loading: false, // 是否加载更多
      isMore: true, // 是否有更多
      historyList: false,
      t_id: 0,
      t_name: '',
      goods_id: 0,
      smile_show: false,
      socket_connect: 0,
      msg_list: [],
      msg: '',
      lockReconnect: false,
      timeOut: false,
      smilies_array: {
        ':smile:': { image: 'smile.gif', text: '微笑' },
        ':sad:': { image: 'sad.gif', text: '难过' },
        ':biggrin:': { image: 'biggrin.gif', text: '呲牙' },
        ':cry:': { image: 'cry.gif', text: '大哭' },
        ':huffy:': { image: 'huffy.gif', text: '发怒' },
        ':shocked:': { image: 'shocked.gif', text: '惊讶' },
        ':tongue:': { image: 'tongue.gif', text: '调皮' },
        ':shy:': { image: 'shy.gif', text: '害羞' },
        ':titter:': { image: 'titter.gif', text: '偷笑' },
        ':sweat:': { image: 'sweat.gif', text: '流汗' },
        ':mad:': { image: 'mad.gif', text: '抓狂' },
        ':lol:': { image: 'lol.gif', text: '阴险' },
        ':loveliness:': { image: 'loveliness.gif', text: '可爱' },
        ':funk:': { image: 'funk.gif', text: '惊恐' },
        ':curse:': { image: 'curse.gif', text: '咒骂' },
        ':dizzy:': { image: 'dizzy.gif', text: '晕' },
        ':shutup:': { image: 'shutup.gif', text: '闭嘴' },
        ':sleepy:': { image: 'sleepy.gif', text: '睡' },
        ':hug:': { image: 'hug.gif', text: '拥抱' },
        ':victory:': { image: 'victory.gif', text: '胜利' },
        ':sun:': { image: 'sun.gif', text: '太阳' },
        ':moon:': { image: 'moon.gif', text: '月亮' },
        ':kiss:': { image: 'kiss.gif', text: '示爱' },
        ':handshake:': { image: 'handshake.gif', text: '握手' }
      }
    }
  },
  beforeDestroy: function () {
    this.canReconnect=false
    heartCheck.stop()
    this.socket_connect = 0
  },
  components:{
    TitleHeader,
    SellerBase,
    ChatMessage: ChatMessage,
    EmptyRecord: EmptyRecord
  },
  computed:{
    fontSize(){
      return getFontSize()
    },
    ...mapState({
      config: state => state.config.config,
      user: state => state.seller.info
    })
  },
  onLoad: function (option) {
	  this.t_id = option.t_id
	  this.t_name = option.t_name
	  this.goods_id = option.goods_id
    if (!this.t_id) {
	  uni.showToast({icon:'none',title: '参数错误'})
      uni.navigateBack({delta:1})
    }
    if (this.config.instant_message_open != '1' || !this.config.instant_message_gateway_url) {
	  uni.showToast({icon:'none',title: '未设置socket host'})
      uni.navigateBack({delta:1})
    }
    this.fetchConfig({}).then(
      response => {
        this.createWebSocket()
      },
      error => {
        uni.showToast({icon:'none',title: error.message})
      }
    )
	this.loadMore()
  },
  watch: {

  },
  mounted(){
    // #ifdef  MP-WEIXIN
    this.navHeight = uni.getMenuButtonBoundingClientRect().height
    // #endif
    this.screenWidth=uni.getSystemInfoSync().screenWidth
    this.contentHeight=uni.getSystemInfoSync().screenHeight-uni.getSystemInfoSync().statusBarHeight
  },
  methods:{
    showPopup(id){
      this.$refs[id].open()
    },
    hidePopup(id){
      this.$refs[id].close()
    },
    goBack(){uni.navigateBack({delta:1})},
    ...mapActions({
      fetchConfig: 'fetchConfig'
    }),
    createWebSocket () {
      uni.connectSocket({
          url: this.config.instant_message_gateway_url,
      }).then(res=>{
        this.init()
      }).catch(error=>{
        this.reconnect()
      })
    },
    init () {
      uni.onSocketOpen(res=>{
        this.wsOpen()
      })
      uni.onSocketMessage(res=>{
        this.wsMessage(res)
      })
      uni.onSocketClose(res=>{
        this.wsClose(res)
      })
      uni.onSocketError(res=>{
        this.wsError(res)
      })
    },
    reconnect () {
      if (this.lockReconnect) {
        return
      };
      this.lockReconnect = true
      // 没连接上会一直重连，设置延迟避免请求过多
      this.timeOut && clearTimeout(this.timeOut)
      var _this = this
      this.timeOut = setTimeout(function () {
        _this.createWebSocket()
        _this.lockReconnect = false
      }, 4000)
    },
    wsOpen () {
      this.socket_connect = 1
      // 心跳检测重置
      heartCheck.start()
    },
    wsMessage (res) {
      var message = JSON.parse(res.data)
      if (!message) {
		uni.showToast({icon:'none',title: '消息转换失败：' + res.data})
        return
      }
      var type = message.type || ''
      switch (type) {
        // Events.php中返回的init类型的消息，将client_id发给后台进行uid绑定
        case 'init':
          this.clientId = message.client_id

          joinChat(this.clientId).then(res => {

          }).catch(error => {
            uni.showToast({icon:'none',title: error.message})
          })
          break
        case 'leave':
          break
        case 'get_msg':// 未读消息
          this.filterMsg(message.msg_list)
          break
        default:
          this.filterMsg([message])
      }
      heartCheck.start()
    },
    wsClose (res) {
      this.socket_connect = 0
      if (res.reason) {
        console.log('聊天系统连接断开：' + res.reason)
      }
      if(this.canReconnect){
        this.reconnect()
      }
    },
    wsError (res) {
	  uni.showToast({icon:'none',title: res.errMsg})
      this.reconnect()
    },
    loadMore () {
      this.loading = true
      this.params.page = ++this.params.page
      if (this.isMore) {
        this.loading = false
        this.getHistoryList(true)
      }
    },

    getHistoryList () {
      uni.showLoading({ title: '加载中' })

      getChatHistory(this.params, this.t_id).then(res => {
        uni.hideLoading()
        if (res.result.hasmore) {
          this.isMore = true
        } else {
          this.isMore = false
        }

        let temp = res.result.list
        if (temp) {
          if (!this.historyList) {
            this.historyList = temp
          } else {
            this.historyList = this.historyList.concat(temp)
          }
        }
      }).catch(function (error) {
        uni.hideLoading()
        uni.showToast({icon:'none',title: error.message})
      })
    },
    getMessage (item, index, type) {
      this.getTime(item, index, type)
      if (type) {
        return this.historyList[index]
      } else {
        return this.msg_list[index]
      }
    },

    getTime (item, index, type) {
      let time = item.instant_message_add_time
      if (type) {
        this.historyList[index]['if_show_time'] = false
        if (index) {
          if (Math.abs(this.historyList[index - 1]['show_time'] - time) > 10) {
            this.historyList[index]['show_time'] = time
            this.historyList[index]['if_show_time'] = true
          } else {
            this.historyList[index]['show_time'] = this.historyList[index - 1]['show_time']
          }
        } else {
          this.historyList[index]['show_time'] = time
          this.historyList[index]['if_show_time'] = true
        }
      } else {
        this.msg_list[index]['if_show_time'] = false
        if (index) {
          if (Math.abs(this.msg_list[index - 1]['show_time'] - time) > 10) {
            this.msg_list[index]['show_time'] = time
            this.msg_list[index]['if_show_time'] = true
          } else {
            this.msg_list[index]['show_time'] = this.msg_list[index - 1]['show_time']
          }
        } else {
          this.msg_list[index]['show_time'] = time
          this.msg_list[index]['if_show_time'] = true
        }
      }
    },
    open_smile () {
      this.smile_show = !this.smile_show
    },
    addSmile (code) {
      this.msg += code
      this.smile_show = false
    },
    submit (type = 0) {
      let msg
      if (this.msg == '') {
		uni.showToast({icon:'none',title: '请填写内容'})
        return
      }
      msg = this.msg
      addInstantMessage({ to_id: this.t_id, message: msg, message_type: type }).then(res => {
        this.msg = ''
        let msg = res.result.instant_message_data
        this.msg_list.push(msg)
      }).catch(function (error) {
        uni.showToast({icon:'none',title: error.message})
      })
    },
    getSmile (smile) {
      return env.SITE_URL + '/static/plugins/js/smilies/images/' + smile
    },
    filterMsg (msg_list) {
      let msg_id = false
      for (var k in msg_list) {
        let msg = msg_list[k]
        if (msg.instant_message_to_id != this.user.member_id || msg.instant_message_from_id != this.t_id) {
          continue
        }
        msg_id = msg.instant_message_id
        this.msg_list.push(msg)
      }
      if (msg_id) {
        if (this.socket_connect) {
          setMessage({ max_id: msg_id, f_id: this.t_id })
        }
      }
    }

  }

}
// 心跳检测
var heartCheck = {
  timeout: 3000,
  timeoutObj: null,
  start: function () {
    var self = this
    this.timeoutObj && clearInterval(this.timeoutObj)
    this.timeoutObj = setInterval(function () {
      // 这里发送一个心跳，后端收到后，返回一个心跳消息，
      uni.sendSocketMessage({
        data: '123456789'
      })
    }, this.timeout)
  },
        stop:function(){
            this.timeoutObj && clearInterval(this.timeoutObj)
        }
}
</script>

<style scoped lang="scss">
.scroll-view-wrapper{display: flex;flex-direction: column;}
.scroll-view{flex:1}
.common-header{
        .btn{background: #000;color: #fff;box-shadow: 0px 2px 4px #d2d2d2;}
    }
    .common-header-wrap .common-header{box-shadow: unset}
    .dstouch-chat-con {height: 100%;display: flex;flex-direction: column;justify-content: flex-end;}

    .dstouch-chat-bottom {}
    .chat-input-layout { position: relative; z-index: 1; display: block; height: 2rem; background-color: rgba(255,255,255,0.90)}
    .chat-input-layout .open-smile { display: block; width: 1.5rem; height: 1.5rem; padding: 0.25rem;}
    .chat-input-layout .open-smile .a { display: block; width: 1.5rem; height: 1.5rem; font-size:1.5rem;color:#6eb6eb}
    .chat-input-layout .input-box { position: absolute; z-index: 1; top: 0.24rem; right: 0.4rem; bottom: 0.24rem; left: 2rem; background: #F5F5F5; border: solid 0.05rem #EEE; border-radius: 0.2rem;}
    .chat-input-layout .input-box input[type="text"] { background-color: transparent; border: none; width: 100%; height: 100%; padding:.1rem 3rem .1rem .1rem; font-size:$fontSize;box-sizing:border-box;display: block;}
    .chat-input-layout .input-box .submit { position: absolute; z-index: 1; top: 0; right:0; display: block; height: 1.4rem; }
    .chat-smile-layout { display: block; width: 100%; height: 4.2rem; background-color: #FAFAFA; border-top: solid 0.05rem #DDD;}
    .chat-smile-layout .ul { font-size: 0;}
    .chat-smile-layout .ul .li { display: inline-block; width: 12.5%; height: 1rem; padding: 0.3rem 0 0 0; text-align: center;  vertical-align: middle;}
    .chat-smile-layout .ul .li .img { display: inline-block; height: 100%; vertical-align: middle;}
    .common-popup-content{background:#f7f7f7;overflow-x:hidden}

</style>
