<template>
  <div>
    <li class="chat-item media" :class='{reversed:reversed}' v-if="type == 'text'">
      <p class="defriend" v-if="status === 'defriend'">您和对方不是好友关系，不能聊天。</p>
      <p class="media-left" v-if="!reversed">
        <a>
          <img :src="targetHeadImg" alt="" ref="chatList" @click="targetInfo">
        </a>
      </p>
      <p class="media-right" v-if="!!reversed">
        <a>
          <img :src="selfHeadImg" alt="">
        </a>
      </p>
      <p class="media-body">
        <span class="media-content" v-html="msgInfo.text" style="max-width:64%;"></span>
      </p>
    </li>

    <li class="chat-item media" :class='{reversed:reversed}' v-if="type == 'custom'">
      <p class="defriend" v-if="status === 'defriend'">您和对方不是好友关系，不能聊天。</p>
      <p class="media-left" v-if="!reversed">
        <a>
          <img :src="targetHeadImg" alt="" ref="chatList" @click="targetInfo">
        </a>
      </p>
      <p class="media-right" v-if="!!reversed">
        <a>
          <img :src="selfHeadImg" alt="">
        </a>
      </p>
      <p class="media-body">
        <span class="media-content" v-html="msgInfo.content.data.text"></span>
      </p>
    </li>

    <li class="chat-item media" v-if="type === 'timeTag'">
      <p class="media-time">{{msgInfo.text}}</p>
    </li>
    <li class="chat-item media" :class='{reversed:reversed}' v-if="type === 'image'">
      <p class="defriend" v-if="status === 'defriend'">您和对方不是好友关系，不能聊天。</p>
      <p class="media-left" v-if="!reversed">
        <a >
          <img :src="targetHeadImg" alt="" ref="chatList" @click="targetInfo">
        </a>
      </p>
      <p class="media-right" v-if="!!reversed">
        <a>
          <img :src="selfHeadImg" alt="">
        </a>
      </p>
      <p class="media-body">
        <span class="media-content media-right-file" v-if="!!reversed">
          <img class="imgMessage fileMessage" :src="msgInfo.file.url"  @click="previwBigPic(msgInfo.file.url)">
        </span>
        <span class="media-content media-left-file" v-if="!reversed">
          <img class="imgMessage fileMessage" :src="msgInfo.file.url" @click="previwBigPic(msgInfo.file.url)">
        </span>
      </p>
    </li>
    <li class="chat-item media" :class='{reversed:reversed}' v-if="type === 'geo'">
      <p class="defriend" v-if="status === 'defriend'">您和对方不是好友关系，不能聊天。</p>
      <p class="media-left" v-if="!reversed">
        <a>
          <img :src="targetHeadImg" alt="" ref="chatList" @click="targetInfo">
        </a>
      </p>
      <p class="media-right" v-if="!!reversed">
        <a>
          <img :src="selfHeadImg" alt="">
        </a>
      </p>
      <p class="media-body">
        <span class="media-content media-right-geo" v-if="!!reversed">
          <p class="weizhi">{{msgInfo.geo.title}}</p>
          <img class="imgMessage geoMessage"
               :src="`//restapi.amap.com/v3/staticmap?location=${msgInfo.geo.lng},${msgInfo.geo.lat}&zoom=14&size=400*200&markers=mid,,:${msgInfo.geo.lng},${msgInfo.geo.lat}&key=ecfdddadcd2c011b96aa9463f5ff7c77`"
               @click="viewGeo()" ref="chatList">
        </span>
        <span class="media-content media-left-geo" v-if="!reversed">
          <p class="weizhi">{{msgInfo.geo.title}}</p>
          <img class="imgMessage geoMessage"
               :src="`//restapi.amap.com/v3/staticmap?location=${msgInfo.geo.lng},${msgInfo.geo.lat}&zoom=14&size=400*200&markers=mid,,:${msgInfo.geo.lng},${msgInfo.geo.lat}&key=ecfdddadcd2c011b96aa9463f5ff7c77`"
               @click="viewGeo()" ref="chatList">
        </span>
      </p>
    </li>
    <div id='container'></div>
    
    <popup :reverse="isReverse" :height="height" :history-model="true" v-model="isViewGeo"  id="chat-geo-popup" @on-hide="onPopupHide" @on-show="onPopupShow" >
        <iframe width="100%" height="100%" frameborder=0 style="display:block;position:absolute;z-index:999999;top:0;left:0" :src="iframeSrc"></iframe>
    </popup>
  </div>
</template>
<script>
import {
  mapKey,
  mapService,
  mapGeoServiceView
} from './config'

import emojiObj from './emoji.js'

let Utils = Object.create(null)

Utils.encode = function(_map, _content) {
  _content = '' + _content
  if (!_map || !_content) {
    return _content || ''
  }
  return _content.replace(_map.r, function($1) {
    var _result = _map[!_map.i ? $1.toLowerCase() : $1]
    return _result != null ? _result : $1
  });
};
Utils.escape = (function() {
  let _reg = /<br\/?>$/
  let _map = {
    r: /\<|\>|\&|\r|\n|\s|\'|\"/g,
    '<': '&lt;',
    '>': '&gt;',
    '&': '&amp;',
    ' ': '&nbsp;',
    '"': '&quot;',
    "'": '&#39;',
    '\n': '<br/>',
    '\r': ''
  }
  return function(_content) {
    _content = Utils.encode(_map, _content)
    return _content.replace(_reg, '<br/>');
  };
})();

export default {
  props: {
    info: {
      type: Object,
      default () {
        return {}
      }
    },
    mapService: {
      type: String,
      default: mapService
    },
    mapKey: {
      type: String,
      default: mapKey
    },
    big: String
  },
  data(){
    return{
        positionLng:0,
        positionLat:0,
        isReverse: false,
        mask: false,
        height: '100%',
        iframeSrc:'',
        isViewGeo: false
    }
  },
  methods: {
    onPopupShow() {},
    onPopupHide() {

    },
    //预览图片
    previwBigPic(big) {
      let _imgs=[]
      _imgs.push(big)
      this.$wechat.previewImage(window.location.href,_imgs)
    },
    //预览地图
    viewGeo() {
      let that = this;
      /***************************************
       由于Chrome、IOS10等已不再支持非安全域的浏览器定位请求，为保证定位成功率和精度，请尽快升级您的站点到HTTPS。
       ***************************************/
      var map, geolocation;
      //加载地图，调用浏览器定位服务
      map = new AMap.Map('container', {
          resizeEnable: true
      });
      map.plugin('AMap.Geolocation', function() {
          geolocation = new AMap.Geolocation({
              enableHighAccuracy: true,//是否使用高精度定位，默认:true
              timeout: 10000,          //超过10秒后停止定位，默认：无穷大
              buttonOffset: new AMap.Pixel(10, 20),//定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
              zoomToAccuracy: true,      //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
              buttonPosition:'RB'
          });
          map.addControl(geolocation);
          geolocation.getCurrentPosition();
          AMap.event.addListener(geolocation, 'complete', onComplete);//返回定位信息
          AMap.event.addListener(geolocation, 'error', onError);      //返回定位出错信息
      });
      //解析定位结果
      function onComplete(data) {
          // console.log(data);
          var positionLng = data.position.getLng();
          var positionLat = data.position.getLat();
          
          that.isViewGeo = true
          that.iframeSrc = '//m.amap.com/navi/?start='+positionLng+','+positionLat+'&dest='+that.msgInfo.geo.lng+','+that.msgInfo.geo.lat+'&destName=去这里&key=d3f5d8b3b05231fa6a11375492310e3a'
          that.$store.state.IMStore.EditPopState = new Date().getTime();
      }
      //解析定位错误信息
      function onError(data) {
          // console.log('定位失败');
      }
      // window.location.href = viewgeo
    },
    // closeIframe() {
    //   this.isViewGeo = false
    // },
    targetInfo() {
      this.$emit('on-click-targetinfo')
    }
  },
  mounted(){
      

  },
  computed: {
    reversed() {
      return this.info.flow === "out" ? true : false
    },
    type() {
      return this.info.type
    },
    status(){
      return this.info.status
    },
    targetHeadImg() {
      return this.$store.state.IMStore.target.headImg
    },
    selfHeadImg() {
      return this.$store.state.IMStore.imUserInfo.headImg
    },
    msgInfo() {
      let rawMsg = Object.assign({}, this.info)
      
      if (rawMsg.type === 'text') {
        rawMsg.showText = Utils.escape(rawMsg.text)

        if (/\[[^\]]+\]/.test(rawMsg.showText)) {
          let emojiItems = rawMsg.showText.match(/\[[^\]]+\]/g)
          emojiItems.forEach(text => {
            let emojiCnt = emojiObj.emojiList.emoji
            if (emojiCnt[text]) {
              rawMsg.showText = rawMsg.showText.replace(text, `<img class="emoji-small" src="${emojiCnt[text].img}">`)
            }
          })
        }
        rawMsg.text = rawMsg.showText
      } else if(rawMsg.type === 'custom'){
        rawMsg.content = JSON.parse(rawMsg.content)

        if(rawMsg.content.type == 8 || rawMsg.content.type == 9){
          rawMsg.content.data = rawMsg.content.msg
        }
        
        rawMsg.showText = Utils.escape(rawMsg.content.data.text)

        if (/\[[^\]]+\]/.test(rawMsg.showText)) {
          let emojiItems = rawMsg.showText.match(/\[[^\]]+\]/g)
          emojiItems.forEach(text => {
            let emojiCnt = emojiObj.emojiList.emoji
            if (emojiCnt[text]) {
              rawMsg.showText = rawMsg.showText.replace(text, `<img class="emoji-small" src="${emojiCnt[text].img}">`)
            }
          })
        }
        rawMsg.content.data.text = rawMsg.showText
      }

      return rawMsg
    }
  }
}
</script>
