<!-- 店铺客服聊天 -->
<template>
  <view class="wanl-chat">
    <view class="edgeInsetTop"></view>
    <view @touchstart="hideDrawer">
      <scroll-view class="cu-chat" scroll-y="true" :scroll-with-animation="scrollAnimation" :scroll-top="scrollTop"
        :scroll-into-view="scrollToView" @scrolltoupper="loadHistory" upper-threshold="50">
        <view class="loading" v-show="isHistoryLoading">
          <view class="spinner">
            <view class="rect1"></view>
            <view class="rect2"></view>
            <view class="rect3"></view>
            <view class="rect4"></view>
            <view class="rect5"></view>
          </view>
        </view>
        <view v-for="(row, index) in msgList" :key="index" :id="'msg' + row.id">
          <view v-if="row.type == 'chat'">
            <view class="cu-item self" v-if="parseInt(row.form.id) === user_id">
              <view class="main" v-if="row.message.type == 'text'">
                <view class="content bg-green">
                  <rich-text :nodes="row.message.content.text"></rich-text>
                </view>
              </view>
              <view class="main" v-if="row.message.type == 'img'">
                <image :src="row.message.content.url" @tap="showPic(row.message)"
                  :style="{ width: row.message.content.w + 'px', height: row.message.content.h + 'px' }"></image>
              </view>
              <view class="main" v-if="row.message.type == 'voice'" @tap="playVoice(row.message)"
                :class="playMsgid == row.message.id ? 'play' : ''">
                <view class="action text-bold text-grey" style="padding-right: 2rpx;">
                  {{ row.message.content.length }}
                  <text class="wlIcon-miao"></text>
                </view>
                <view class="content bg-green">
                  <text :style="{ width: row.message.content.length * 6 + 'rpx' }"></text>
                  <text class="wlIcon-yuyinyou text-xxl padding-left-xl"></text>
                </view>
              </view>
              <view class="main goods" v-if="row.message.type == 'goods'">
                <view class="content" @tap="onGoods(row.message.content.id)">
                  <image :src="$appKit.oss(row.message.content.image, 100, 0)" mode="widthFix"></image>
                  <view class="text-price text-orange text-lg margin-tb-xs">
                    {{ row.message.content.price }}
                  </view>
                  <view>
                    {{ row.message.content.title }}
                  </view>
                </view>
              </view>
              <view class="main order" v-if="row.message.type == 'order'">
                <view class="content" @tap="orderDetails(row.message.content.id)">
                  <view>
                    <text>{{ $t('chat.order-details') }}</text>
                  </view>
                  <view class="margin-tb-bj radius product padding-sm">
                    <view class="item" v-for="(item, idx) in row.message.content.goods" :key="idx">
                      <view class="image">
                        <image :src="$appKit.oss(item.image, 50, 50)" mode="aspectFill"></image>
                      </view>
                      <view class="details text-sm">
                        <view class="text-cut wanl-gray-dark">
                          <text>{{ item.title }}</text>
                        </view>
                        <view class="wanl-gray-light flex justify-between" style="width: 100%;">
                          <view class="text-price text-orange">
                            {{ item.price * item.number }}
                          </view>
                          <view>
                            <text>{{ item.difference }} x {{ item.number }}</text>
                            <text v-if="item.refund_status != 0">({{ refundStatusText[item.refund_status] }})</text>
                          </view>
                        </view>
                      </view>
                    </view>
                  </view>
                  <view class="text-sm flex justify-between">
                    <view>
                      <text>{{ stateText[row.message.content.state - 1] }}</text>
                    </view>
                    <view>
                      <text>{{ $t('chat.order-number') }}：</text>
                      <text>{{ row.message.content.order_no }}</text>
                    </view>
                  </view>
                </view>
              </view>
              <view class="cu-avatar radius"
                :style="{ backgroundImage: 'url(' + $appKit.oss(row.form.avatar, 100, 100) + ')' }"></view>
              <view class="date">{{ $appKit.timeToChat(row.createtime) }}</view>
            </view>
            <view class="cu-item" v-else>
              <view class="cu-avatar radius"
                :style="{ backgroundImage: 'url(' + $appKit.oss(row.form.avatar, 100, 100) + ')' }"></view>
              <view class="main" v-if="row.message.type == 'text'">
                <view class="content">
                  <rich-text :nodes="row.message.content.text"></rich-text>
                </view>
              </view>
              <view class="main" v-if="row.message.type == 'img'">
                <image :src="row.message.content.url" @tap="showPic(row.message)"
                  :style="{ width: row.message.content.w + 'px', height: row.message.content.h + 'px' }"></image>
              </view>
              <view class="main" v-if="row.message.type == 'voice'" @tap="playVoice(row.message)"
                :class="playMsgid == row.message.id ? 'play' : ''">
                <view class="content">
                  <text class="wlIcon-yuyinzuo text-xxl padding-right-xl"></text>
                  <text :style="{ width: row.message.content.length * 6 + 'rpx' }"></text>
                </view>
                <view class="action text-bold text-grey">
                  {{ row.message.content.length }}
                  <text class="wlIcon-miao"></text>
                </view>
              </view>
              <view class="date">{{ $appKit.timeToChat(row.createtime) }}</view>
            </view>
          </view>
          <view v-if="row.type == 'sys'">
            <view class="cu-info round">{{ $t('chat.system-message-withdrawn') }}</view>
          </view>
        </view>
      </scroll-view>
    </view>
    <view class="popup-layer" :class="{ showLayer: popupLayerClass }" @touchmove.stop.prevent="discard">
      <view :class="{ hidden: hideEmoji }">
        <view class="emoji">
          <scroll-view class="emojinav" scroll-x scroll-with-animation>
            <view class="item">
              <view :class="item == TabCur ? 'emojibg' : ''" v-for="(item, index) in emojiList.categories" :key="index"
                @tap="tabSelect" :data-id="item"
                :style="{ backgroundImage: 'url(' + emojiList.groups[item][0].url + ')' }"></view>
            </view>
          </scroll-view>
          <scroll-view v-for="(emoji, groups) in emojiList.groups" :key="groups" v-if="TabCur == groups" class="subject"
            scroll-y scroll-with-animation>
            <view class="item grid margin-bottom text-center col-5">
              <view v-for="(item, index) in emoji" :key="index" @tap="addEmoji(item.value)"
                :style="{ backgroundImage: 'url(' + item.url + ')' }"></view>
            </view>
          </scroll-view>
        </view>
      </view>
      <view class="solid-top" :class="{ hidden: hideMore }">
        <view class="opmenu solid-top">
          <view class="box" @tap="browsing">
            <view class="icon wanl-gray"><text class="wlIcon-shangpin"></text></view>
            <text class="text-sm">{{ $t('chat.button.goods') }}</text>
          </view>
          <view class="box" @tap="order">
            <view class="icon wanl-gray"><text class="wlIcon-dingdan1"></text></view>
            <text class="text-sm">{{ $t('chat.button.order') }}</text>
          </view>
          <!-- #ifndef H5 -->
          <view class="box" @tap="camera">
            <view class="icon wanl-gray"><text class="wlIcon-31paishexuanzhong"></text></view>
            <text class="text-sm">{{ $t('chat.button.camera') }}</text>
          </view>
          <!-- #endif -->
          <view class="box" @tap="chooseImage">
            <view class="icon wanl-gray"><text class="wlIcon-tupian1"></text></view>
            <text class="text-sm">{{ $t('chat.button.photo') }}</text>
          </view>
          <view class="box" @tap="complaint">
            <view class="icon wanl-gray"><text class="wlIcon-zhuyidapx"></text></view>
            <text class="text-sm">{{ $t('chat.button.complaint') }}</text>
          </view>
        </view>
      </view>
    </view>
    <view class="input-box" :class="{ emptybottom: emptybottom, showLayer: popupLayerClass }"
      @touchmove.stop.prevent="discard">
      <!-- #ifndef H5 -->
      <view class="voice">
        <view :class="isVoice ? 'wlIcon-jianpanqiehuan' : 'wlIcon-yuyin'" @tap="switchVoice"></view>
      </view>
      <!-- #endif -->
      <!-- #ifdef H5 -->
      <view class="more" @tap="showMore">
        <view class="wlIcon-yuanquanjiahao"></view>
      </view>
      <!-- #endif -->
      <view class="textbox">
        <view class="voice-mode" :class="[isVoice ? '' : 'hidden', recording ? 'recording' : '']"
          @touchstart="voiceBegin" @touchmove.stop.prevent="voiceIng" @touchend="voiceEnd" @touchcancel="voiceCancel">
          {{ voiceTis }}
        </view>
        <view class="text-mode" :class="isVoice ? 'hidden' : ''">
          <view class="box">
            <textarea auto-height="true" maxlength="300" :show-confirm-bar="false" cursor-spacing="90" v-model="textMsg"
              @focus="textareaFocus" @blur="textareaBlur" @confirm="sendText" />
          </view>
          <view class="em" @tap="chooseEmoji">
            <view class="wlIcon-biaoqing2"></view>
          </view>
        </view>
      </view>
      <!-- #ifndef H5 -->
      <view class="more" @tap="showMore" style="margin-right: -12rpx;">
        <view class="wlIcon-yuanquanjiahao"></view>
      </view>
      <!-- #endif -->
      <view class="send" :class="isVoice ? 'hidden' : ''" @tap="sendText">
        <text class="wlIcon-zhifeiji" v-if="textMsg"></text>
        <text class="wlIcon-fasong" v-else></text>
      </view>
    </view>
    <view class="chatTips bg-white radius-bock margin-lr-bj padding-sm" v-if="goods && isGoods">
      <image class="radius" :src="$appKit.oss(goods.image, 100, 100)" mode="aspectFill"></image>
      <view class="details">
        <view class="flex justify-between margin-bottom-sm">
          <view class="text-cut title">
            <text>{{ goods.title }}</text>
          </view>
          <view @tap="closeTips()">
            <text class="wlIcon-31guanbi"></text>
          </view>
        </view>
        <view class="flex justify-between">
          <view class="text-lg text-orange">
            <text class="text-price">{{ goods.price }}</text>
          </view>
          <view>
            <button class="cu-btn round bg-orange sm" @tap="sendGoods(goods)">{{ $t('chat.send-merchant') }}</button>
          </view>
        </view>
      </view>
    </view>
    <view class="record" :class="recording ? '' : 'hidden'">
      <view class="ing" :class="willStop ? 'hidden' : ''">
        <view class="wlIcon-huatong01"></view>
      </view>
      <view class="cancel" :class="willStop ? '' : 'hidden'">
        <view class="wlIcon-shanchu2"></view>
      </view>
      <view class="tis" :class="willStop ? 'change' : ''">{{ recordTis }}</view>
    </view>
    <view class="WANL-MODAL">
      <view class="cu-modal bottom-modal" :class="modalName == 'goods' ? 'show' : ''" @tap="hideModal">
        <view class="cu-dialog bg-white" @tap.stop="">
          <view class="wanl-modal">
            <view class="head padding-bj">
              <view class="content">
                <view class="text-lg">{{ $t('chat.modal.browsed-goods') }}</view>
              </view>
              <view class="close wlIcon-31guanbi" @tap="hideModal"></view>
            </view>
            <scroll-view class="scroll-y" scroll-y="true">
              <view class="item goods" v-for="(item, index) in goodsData" :key="index">
                <block v-if="item.goods !== null">
                  <image class="radius" :src="$appKit.oss(item.goods.image, 100, 100)" mode="aspectFill"></image>
                  <view class="details">
                    <view class="text-cut-2 title">
                      <text>{{ item.goods.title }}</text>
                    </view>
                    <view class="flex justify-between info">
                      <view class="text-lg text-orange">
                        <text class="text-price">{{ item.goods.price }}</text>
                      </view>
                      <button class="cu-btn round line-orange sm" @tap="sendGoods(item.goods)">{{ $t('chat.send-goods')
                      }}</button>
                    </view>
                  </view>
                </block>
              </view>
            </scroll-view>
            <view class="foot padding-lr-bj"><button class="cu-btn bg-gradual-orange round text-bold complete"
                @tap="hideModal">Complete</button></view>
          </view>
        </view>
      </view>
      <view class="cu-modal bottom-modal" :class="modalName == 'order' ? 'show' : ''" @tap="hideModal">
        <view class="cu-dialog bg-bgcolor" @tap.stop="">
          <view class="wanl-modal">
            <view class="head padding-bj">
              <view class="content">
                <view class="text-lg">{{ $t('chat.modal.purchased-orders') }}</view>
              </view>
              <view class="close wlIcon-31guanbi" @tap="hideModal"></view>
            </view>
            <scroll-view class="scroll-y" scroll-y="true">
              <view class="item order-list-item bg-white radius-bock margin-tb-sm padding-bj"
                v-for="(item, index) in orderData" :key="item.id" @tap="sendOrder(item)">
                <view class="order-list-item-head">
                  <view><text>{{ $t('chat.order-number') }}：{{ item.order_no }}</text></view>
                  <view><text class="wanl-gray-dark text-sm">{{ stateText[item.state - 1] }}</text></view>
                </view>
                <view class="order-list-item-goods" v-for="(gd, key) in item.goods" :key="key">
                  <image class="radius" :src="$appKit.oss(gd.image, 100, 100)" mode="aspectFill"></image>
                  <view class="order-list-item-details">
                    <view class="text-cut-2 title wanl-gray-dark">{{ gd.title }}</view>
                    <view class="flex justify-between info">
                      <view class="text-lg text-orange">
                        <text class="text-price">{{ gd.price }}</text>
                      </view>
                    </view>
                  </view>
                </view>
                <view class="order-list-item-foot">
                  <button class="cu-btn round sm line-orange">{{ $t('chat.send-order') }}</button>
                </view>
              </view>
            </scroll-view>
            <view class="foot padding-lr-bj"><button class="cu-btn bg-gradual-orange round text-bold complete"
                @tap="hideModal">{{ $t('chat.complete') }}</button></view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
const emotions = require('@/static/json/emotions.json')
import { mapMutations } from 'vuex'
import { getShopChat, getChatHistory, getBrowsingToShop, getOrderListToShop, getUploadConfig } from '@/features/mall/gateway/im'
import { setChat } from '@/common/chat-utils.js'
import { STORAGE } from '@/core/constants/storage-keys'
export default {
  data() {
    return {
      user_id: parseInt(this.$store.state.user.id) || 0,
      avatar: this.$store.state.user.avatar,
      username: this.$store.state.user.username,
      nickname: this.$store.state.user.nickname,
      to_id: 0,
      shop_id: 0,
      shop_name: null,
      shop_avatar: null,
      textMsg: '',
      isHistoryLoading: false,
      reload: false,
      current_page: 1,
      scrollAnimation: false,
      scrollTop: 0,
      scrollToView: '',
      msgList: [],
      msgImgList: [],
      goods: null,
      isGoods: true,
      goodsData: [],
      orderData: [],
      emptybottom: false,
      // #ifndef H5
      RECORDER: uni.getRecorderManager(),
      // #endif
      isVoice: false,
      voiceTis: this.$t('chat.voice.hold-to-speak'),
      recordTis: this.$t('chat.voice.slide-up-to-cancel'),
      recording: false,
      willStop: false,
      initPoint: { identifier: 0, Y: 0 },
      recordTimer: null,
      recordLength: 0,
      AUDIO: uni.createInnerAudioContext(),
      playMsgid: null,
      VoiceTimer: null,
      popupLayerClass: false,
      hideMore: true,
      modalName: null,
      stateText: [this.$t('chat.state.waiting-payment'), this.$t('chat.state.payment-successful'), this.$t('chat.state.waiting-receipt'), this.$t('chat.state.waiting-review'), this.$t('chat.state.refund-order'), this.$t('chat.state.order-completed'), this.$t('chat.state.transaction-closed')],
      refundStatusText: [this.$t('chat.refund-status.not-refunded'), this.$t('chat.refund-status.refunding'), this.$t('chat.refund-status.to-be-returned'), this.$t('chat.refund-status.refund-completed'), this.$t('chat.refund-status.refund-closed'), this.$t('chat.refund-status.refund-rejected')],
      TabCur: this.$t('chat.emoji.default'),
      hideEmoji: true,
      emojiList: this.emojiData(),
      QnUrl: '',
      Sysmodel: ''
    }
  },
  created() {
    this.Sysmodel = (this.$wanlshop && this.$wanlshop.wanlsys) ? this.$wanlshop.wanlsys().model : ''
  },
  async onLoad(option) {
    if (option.hasOwnProperty('goods')) {
      this.goods = JSON.parse(option.goods)
      setTimeout(() => {
        this.isGoods = false
      }, 5000)
    }
    try {
      const res = await getShopChat({ id: option.shop_id, type: 'chat' })
      this.to_id = res.data.user_id
      this.shop_id = res.data.id
      this.shop_name = res.data.shopname
      this.shop_avatar = res.data.avatar
      uni.setNavigationBarTitle({ title: res.data.shopname + (res.data.isOnline == 1 ? '-' + this.$t('chat.online') : '-' + this.$t('chat.offline')) })
      this.getMsgList(res.data.user_id)
      // 進入聊天頁：暫停全局角标提示，並清零該會話未讀
      this.setIschat({ notice: false })
      this.$store.dispatch('chat/update', { type: 'del', id: res.data.user_id }).catch(() => {})
      setTimeout(() => {
        this.loadHistory({ bootstrap: true })
      }, 500)
    } catch (e) {
      console.error('[chat] getShopChat failed:', e)
    }
    this.AUDIO.onEnded(() => {
      this.playMsgid = null
    })
    // #ifndef H5
    this.RECORDER.onStart(e => {
      this.recordBegin(e)
    })
    this.RECORDER.onStop(e => {
      this.recordEnd(e)
    })
    // #endif
    uni.$on('onMessage', this.onSend)
  },
  onNavigationBarButtonTap() {
    uni.navigateTo({ url: '/pages/shop/index?id=' + this.shop_id })
  },
  onUnload() {
    uni.$off('onMessage', this.onSend)
    if (this.to_id) {
      this.$store.dispatch('chat/update', { type: 'del', id: this.to_id }).catch(() => {})
    }
    this.setIschat({ notice: true, number: 0 })
  },
  onShow() {
    if (this.msgList.length) {
      this.scrollToLatest()
    }
  },
  methods: {
    ...mapMutations({
      setIschat: 'chat/setIschat'
    }),
    /** 滚到最新消息（强制变更 scrollTop，避免同值不生效） */
    scrollToLatest() {
      if (!this.msgList.length) return
      const last = this.msgList[this.msgList.length - 1]
      this.scrollAnimation = false
      this.scrollToView = ''
      this.scrollTop = 0
      this.$nextTick(() => {
        this.scrollTop = 9999999 + (Date.now() % 1000)
        this.scrollToView = 'msg' + last.id
        this.$nextTick(() => {
          this.scrollAnimation = true
        })
      })
    },
    getMsgList(id) {
      const primary = STORAGE.chatMsgPrefix + id
      const legacy = 'wanlchat:message_' + id
      let list = uni.getStorageSync(primary)
      if (!Array.isArray(list) || !list.length) {
        list = uni.getStorageSync(legacy)
        // 旧 key 有数据时迁移到统一前缀
        if (Array.isArray(list) && list.length) {
          uni.setStorageSync(primary, list)
        }
      }
      if (!Array.isArray(list) || !list.length) return
      for (let i = 0; i < list.length; i++) {
        if (list[i].type == 'chat' && list[i].message && list[i].message.type == 'img') {
          list[i].message.content = this.setPicSize(list[i].message.content)
          this.msgImgList.push(list[i].message.content.url)
        }
        if (list[i].type == 'chat' && list[i].message && list[i].message.type == 'text') {
          list[i].message.content.text = this.replaceEmoji(list[i].message.content.text)
        }
      }
      this.msgList = list
      this.$nextTick(() => {
        this.scrollToLatest()
      })
    },
    async loadHistory(options) {
      // scrolltoupper 传入事件对象；进页引导传 { bootstrap: true }
      const bootstrap = !!(options && options.bootstrap)
      if (this.isHistoryLoading || this.reload || !this.to_id) return
      this.isHistoryLoading = true
      this.scrollAnimation = false
      const hadLocal = this.msgList.length > 0
      // 上拉加载更多时锚定原第一条；首次进页要滚到最新，不能锚到顶部
      const view_id = (!bootstrap && hadLocal) ? this.msgList[0].id : null
      try {
        const res = await getChatHistory({ to_id: this.to_id, page: this.current_page })
        const page = res && res.data
        let list = []
        let currentPage = 1
        let lastPage = 1
        if (Array.isArray(page)) {
          list = page
        } else if (page && typeof page === 'object') {
          list = page.data || page.rows || page.list || []
          currentPage = Number(page.current_page) || 1
          lastPage = Number(page.last_page) || currentPage
        }
        if (!Array.isArray(list)) list = []

        // 先拷贝一份用于本地缓存（避免把表情 HTML 写回）
        const forStore = currentPage == 1 ? JSON.parse(JSON.stringify(list)) : null

        for (let i = 0; i < list.length; i++) {
          if (list[i].type == 'chat' && list[i].message && list[i].message.type == 'img') {
            list[i].message.content = this.setPicSize(list[i].message.content)
            this.msgImgList.unshift(list[i].message.content.url)
          }
          if (list[i].type == 'chat' && list[i].message && list[i].message.type == 'text') {
            list[i].message.content.text = this.replaceEmoji(list[i].message.content.text)
          }
        }
        list.sort(function (a, b) {
          return (a.updatetime || a.createtime || 0) - (b.updatetime || b.createtime || 0)
        })

        if (currentPage == 1) {
          // 本地已有且服务端本页为空时，保留本地，避免被清空
          if (list.length || !hadLocal) {
            this.msgList = list
          }
          if (forStore && forStore.length && this.to_id) {
            uni.setStorageSync(STORAGE.chatMsgPrefix + this.to_id, forStore)
          }
        } else {
          this.msgList = list.concat(this.msgList)
        }

        this.$nextTick(() => {
          if (bootstrap || !view_id) {
            this.scrollToLatest()
          } else {
            this.scrollToView = 'msg' + view_id
            this.$nextTick(() => {
              this.scrollAnimation = true
            })
          }
        })

        if (currentPage >= lastPage || list.length === 0) {
          this.reload = true
        } else {
          this.current_page = currentPage + 1
        }
      } catch (e) {
        console.error('[chat] loadHistory failed:', e)
      }
      this.isHistoryLoading = false
    },
    onChat(msg) {
      if (msg.type == 'system') {
        if (msg.msg.type == 'text') this.addSystemTextMsg(msg)
      } else if (msg.type == 'chat') {
        if (msg.message.type == 'text') this.addTextMsg(msg)
        if (msg.message.type == 'voice') this.addVoiceMsg(msg)
        if (msg.message.type == 'img') this.addImgMsg(msg)
        if (msg.message.type == 'goods') this.addGoodsMsg(msg)
        if (msg.message.type == 'order') this.addOrderMsg(msg)
      }
      this.$nextTick(() => {
        this.scrollToView = 'msg' + msg.id
      })
    },
    onSend(msg) {
      if (msg.form.id == this.to_id) {
        setChat(msg, 'receive')
        if (msg.type == 'system') {
          if (msg.msg.type == 'text') this.addSystemTextMsg(msg)
        } else if (msg.type == 'chat') {
          if (msg.message.type == 'text') this.addTextMsg(msg)
          if (msg.message.type == 'voice') this.addVoiceMsg(msg)
          if (msg.message.type == 'img') this.addImgMsg(msg)
          if (msg.message.type == 'goods') this.addGoodsMsg(msg)
          if (msg.message.type == 'order') this.addOrderMsg(msg)
        }
        this.$nextTick(() => {
          this.scrollToView = 'msg' + msg.id
        })
      }
    },
    sendMsg(content, type) {
      let lastid = 1
      if (this.msgList.length) {
        lastid = this.msgList[this.msgList.length - 1].id
        lastid++
      }
      let data = {
        id: lastid,
        type: 'chat',
        to_id: this.to_id,
        form: {
          id: this.user_id,
          avatar: this.avatar,
          name: this.nickname
        },
        message: {
          type: type,
          content: content
        },
        createtime: parseInt(new Date().getTime() / 1000)
      }
      this.onChat(JSON.parse(JSON.stringify(data)))
      setChat(data, 'send')
      this.$store.dispatch('chat/update', {
        type: 'send',
        data,
        shop: {
          id: this.shop_id,
          user_id: this.to_id,
          name: this.shop_name,
          avatar: this.shop_avatar
        }
      }).catch(() => {})
      this.$appKit.send(data)
    },
    addTextMsg(msg) {
      msg.message.content.text = this.replaceEmoji(msg.message.content.text)
      this.msgList.push(msg)
    },
    addVoiceMsg(msg) {
      this.msgList.push(msg)
    },
    addImgMsg(msg) {
      msg.message.content = this.setPicSize(msg.message.content)
      this.msgImgList.push(msg.message.content.url)
      this.msgList.push(msg)
    },
    addGoodsMsg(msg) {
      this.msgList.push(msg)
    },
    addOrderMsg(msg) {
      this.msgList.push(msg)
    },
    addSystemTextMsg(msg) {
      this.msgList.push(msg)
    },
    emojiData() {
      var groups = {},
        categories = [],
        map = {}
      emotions.forEach(emotion => {
        var cate = emotion.category.length > 0 ? emotion.category : this.$t('chat.emoji.default')
        if (!groups[cate]) {
          groups[cate] = []
          categories.push(cate)
        }
        groups[cate].push(emotion)
        map[emotion.phrase] = emotion.icon
      })
      return { groups, categories, map }
    },
    replaceEmoji(str) {
      if (!str) return ''
      let replacedStr = str
      Object.keys(this.emojiList.map).forEach(key => {
        if (str.indexOf(key) !== -1) {
          const url = this.emojiList.map[key]
          if (url) {
            replacedStr = replacedStr.split(key).join('<img src="' + url + '" style="width:18px;vertical-align:middle;">')
          }
        }
      })
      return replacedStr.replace(/(\r\n)|(\n)/g, '<br>')
    },
    tabSelect(e) {
      this.TabCur = e.currentTarget.dataset.id
    },
    setPicSize(content) {
      let maxW = uni.upx2px(350)
      let maxH = uni.upx2px(350)
      if (content.w > maxW || content.h > maxH) {
        let scale = content.w / content.h
        content.w = scale > 1 ? maxW : maxH * scale
        content.h = scale > 1 ? maxW / scale : maxH
      }
      return content
    },
    showMore() {
      this.isVoice = false
      this.hideEmoji = true
      if (this.hideMore) {
        this.hideMore = false
        this.openDrawer()
      } else {
        this.hideDrawer()
      }
    },
    openDrawer() {
      this.emptybottom = true
      this.popupLayerClass = true
    },
    hideDrawer() {
      this.emptybottom = false
      this.popupLayerClass = false
      setTimeout(() => {
        this.hideMore = true
        this.hideEmoji = true
      }, 150)
    },
    chooseImage() {
      this.getImage('album')
    },
    camera() {
      this.getImage('camera')
    },
    getImage(type) {
      this.hideDrawer()
      uni.chooseImage({
        sourceType: [type],
        sizeType: ['original', 'compressed'],
        success: res => {
          uni.showLoading({ title: this.$t('chat.voice.sending-voice'), mask: true })
          const total = res.tempFilePaths.length
          let done = 0
          const tryHide = () => {
            done++
            if (done >= total) uni.hideLoading()
          }
          getUploadConfig().then(updata => {
            for (let i = 0; i < total; i++) {
              uni.getImageInfo({
                src: res.tempFilePaths[i],
                success: image => {
                  uni.uploadFile({
                    url: updata.uploadurl,
                    filePath: image.path,
                    name: 'file',
                    formData: updata.storage == 'local' ? null : updata.multipart,
                    success: data => {
                      this.sendMsg({ url: JSON.parse(data.data).data.fullurl, w: image.width, h: image.height }, 'img')
                      tryHide()
                    },
                    fail: error => {
                      uni.showToast({ title: JSON.parse(error.data).msg, icon: 'error', position: true })
                      tryHide()
                    }
                  })
                },
                fail: () => tryHide()
              })
            }
          }).catch(() => {
            uni.hideLoading()
          })
        }
      })
    },
    showPic(message) {
      uni.previewImage({
        indicator: 'none',
        current: message.content.url,
        urls: this.msgImgList
      })
    },
    chooseEmoji() {
      this.hideMore = true
      if (this.hideEmoji) {
        this.hideEmoji = false
        this.openDrawer()
      } else {
        this.hideDrawer()
      }
    },
    addEmoji(em) {
      this.textMsg += em
    },
    textareaFocus() {
      this.emptybottom = true
      this.closeTips()
      if (this.popupLayerClass && this.hideMore == false) {
        this.hideDrawer()
      }
    },
    textareaBlur() {
      this.emptybottom = false
    },
    sendText() {
      this.hideDrawer()
      if (!this.textMsg) return
      let msg = { text: this.textMsg }
      this.sendMsg(msg, 'text')
      this.textMsg = ''
    },
    sendGoods(data) {
      this.sendMsg(data, 'goods')
      this.closeTips()
      this.hideModal()
    },
    sendOrder(data) {
      this.sendMsg({ id: data.id, order_no: data.order_no, goods: data.goods, state: data.state }, 'order')
      this.closeTips()
      this.hideModal()
    },
    closeTips() {
      this.isGoods = false
    },
    complaint() {
      this.$appKit.to(`/pages/account/complaint?id=${this.shop_id}&type=2`)
      this.hideDrawer()
    },
    async browsing() {
      this.hideDrawer()
      try {
        const res = await getBrowsingToShop({ shop_id: this.shop_id })
        this.goodsData = res.data
        this.modalName = 'goods'
      } catch (e) {
        console.error('[chat] browsing failed:', e)
      }
    },
    async order() {
      this.hideDrawer()
      try {
        const res = await getOrderListToShop({ shop_id: this.shop_id })
        this.orderData = res.data
        this.modalName = 'order'
      } catch (e) {
        console.error('[chat] order failed:', e)
      }
    },
    hideModal() {
      this.modalName = null
    },
    playVoice(message) {
      this.playMsgid = message.id
      this.AUDIO.src = message.content.url
      this.$nextTick(() => {
        this.AUDIO.play()
      })
    },
    voiceBegin(e) {
      if (e.touches.length > 1) return
      this.initPoint.Y = e.touches[0].clientY
      this.initPoint.identifier = e.touches[0].identifier
      this.RECORDER.start({ format: 'mp3' })
    },
    recordBegin() {
      this.recording = true
      this.voiceTis = this.$t('chat.voice.release-to-end')
      this.recordLength = 0
      this.recordTimer = setInterval(() => {
        this.recordLength++
      }, 1000)
    },
    voiceCancel() {
      this.recording = false
      this.voiceTis = this.$t('chat.voice.hold-to-speak')
      this.recordTis = this.$t('chat.voice.slide-up-to-cancel')
      this.willStop = true
      this.RECORDER.stop()
    },
    voiceIng(e) {
      if (!this.recording) return
      let touche = e.touches[0]
      if (this.initPoint.Y - touche.clientY >= uni.upx2px(200)) {
        this.willStop = true
        this.recordTis = this.$t('chat.voice.release-finger-to-cancel')
      } else {
        this.willStop = false
        this.recordTis = this.$t('chat.voice.slide-up-to-cancel')
      }
    },
    voiceEnd() {
      if (!this.recording) return
      this.recording = false
      this.voiceTis = this.$t('chat.voice.hold-to-speak')
      this.recordTis = this.$t('chat.voice.slide-up-to-cancel')
      this.RECORDER.stop()
    },
    recordEnd(e) {
      clearInterval(this.recordTimer)
      if (!this.willStop) {
        uni.showLoading({ title: this.$t('chat.voice.sending-voice'), mask: true })
        getUploadConfig().then(updata => {
          uni.uploadFile({
            url: updata.uploadurl,
            filePath: e.tempFilePath,
            name: 'file',
            formData: updata.storage == 'local' ? null : updata.multipart,
            success: data => {
              uni.hideLoading()
              let msg = { length: 0, url: JSON.parse(data.data).data.fullurl }
              msg.length = this.recordLength % 60
              if (msg.length > 0) this.sendMsg(msg, 'voice')
            },
            fail: error => {
              uni.hideLoading()
              this.$appKit.msg(JSON.parse(error.data).msg)
            }
          })
        }).catch(() => {
          uni.hideLoading()
        })
      }
      this.willStop = false
    },
    switchVoice() {
      this.hideDrawer()
      this.isVoice = !this.isVoice
    },
    discard() {
      return
    }
  }
}
</script>
<style>
.cu-btn.sm {
  font-size: 26rpx;
}

.cu-modal {
  z-index: 2001;
}

.chatTips {
  display: inline-flex;
  align-items: center;
  position: absolute;
  z-index: 101;
  right: 0;
  left: 0;
  bottom: 120rpx;
  bottom: calc(120rpx + env(safe-area-inset-bottom));
}

.chatTips image {
  width: 100rpx;
  height: 100rpx;
  margin-right: 20rpx;
  flex-shrink: 0;
}

.chatTips .details {
  width: calc(100% - 100rpx - 20rpx);
}

.chatTips .details .title {
  width: 90%;
}

.cu-chat .cu-item>.main.goods .content,
.cu-chat .cu-item>.main.order .content {
  display: block;
}

.cu-chat .cu-item>.main.order {
  max-width: calc(100% - 200rpx);
}

.cu-chat .cu-item>.main.order .product {
  background-color: #f9f9f9;
}

.cu-chat .cu-item>.main.order .product .item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 25rpx;
}

.cu-chat .cu-item>.main.order .product .item:last-of-type {
  margin-bottom: 0;
}

.cu-chat .cu-item>.main.order .product .item .image,
.product .item .image image {
  width: 100rpx;
  height: 100rpx;
  border-radius: 10rpx;
}

.cu-chat .cu-item>.main.order .product .item .details {
  display: flex;
  flex-wrap: wrap;
  width: calc(100% - 120rpx);
  align-content: space-between;
}

.wanl-modal .goods {
  display: flex;
  padding: 20rpx 0;
}

.wanl-modal .goods:last-of-type {
  padding-bottom: 0;
}

.wanl-modal .goods image {
  width: 180rpx;
  height: 180rpx;
  margin-right: 20rpx;
  flex-shrink: 0;
}

.wanl-modal .goods .details {
  flex-wrap: wrap;
  display: flex;
  flex: 1;
  align-content: space-between;
}

.wanl-modal .goods .details .info {
  width: 100%;
}

.order-list-item {
  display: flex;
  flex-direction: column;
  align-items: stretch;
  box-sizing: border-box;
  overflow: hidden;
}

.order-list-item-head {
  display: flex;
  flex-direction: column;
  gap: 8rpx;
  margin-bottom: 16rpx;
  font-size: 28rpx;
}

.order-list-item-goods {
  display: flex;
  align-items: flex-start;
  margin-bottom: 20rpx;
  min-width: 0;
}

.order-list-item-goods image {
  width: 160rpx;
  height: 160rpx;
  border-radius: 10rpx;
  flex-shrink: 0;
  margin-right: 20rpx;
}

.order-list-item-details {
  flex: 1;
  min-width: 0;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.order-list-item-details .title {
  font-size: 26rpx;
  line-height: 1.4;
  margin-bottom: 8rpx;
  word-break: break-all;
}

.order-list-item-details .info {
  align-items: center;
}

.order-list-item-foot {
  flex-shrink: 0;
  display: flex;
  justify-content: flex-end;
  padding-top: 8rpx;
}

.opmenu {
  display: flex;
  flex-wrap: wrap;
  margin-top: 2rpx;
  color: #4c4c4c;
}

.opmenu .box {
  padding-top: 35rpx;
  padding-left: 50rpx;
  text-align: center;
}

.opmenu .box .icon {
  height: 120rpx;
  width: 120rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  justify-items: center;
  background-color: #ffffff;
  border-radius: 20rpx;
  font-size: 68rpx;
  margin-bottom: 10rpx;
}

.emptybottom {
  padding-bottom: 0 !important;
}

.hidden {
  display: none !important;
}

.cu-chat .cu-item>.main .content {
  font-size: 30rpx;
  border-radius: 17rpx;
}

.cu-chat .cu-item [class*='wlIcon-'] {
  font-size: 34rpx;
}

.popup-layer {
  transition: all 0.15s linear;
  width: 100%;
  height: 480rpx;
  background-color: #f5f5f5;
  position: fixed;
  z-index: 2000;
  top: 100%;
}

.popup-layer.showLayer {
  transform: translate3d(0, -480rpx, 0);
}

.popup-layer .emoji .emojinav {
  background-color: #f8f8f8;
}

.popup-layer .emoji .emojinav .item {
  display: flex;
  align-items: center;
  height: 100rpx;
  padding-left: 10rpx;
}

.popup-layer .emoji .emojinav .item .emojibg {
  background-color: #dedede;
}

.popup-layer .emoji .emojinav .item>view {
  margin: 0 25rpx;
  width: 60rpx;
  height: 60rpx;
  border-radius: 18rpx;
  background-repeat: no-repeat;
  background-size: 80%;
  background-position: center;
}

.popup-layer .emoji .subject {
  height: 380rpx;
  background-color: #f1f1f1;
}

.popup-layer .emoji .subject .item {
  padding: 25rpx;
}

.popup-layer .emoji .subject .item>view {
  background-repeat: no-repeat;
  background-size: 56%;
  background-position: center;
  width: 12.5%;
  height: 100rpx;
}

.input-box {
  width: 100%;
  min-height: 100rpx;
  padding-bottom: env(safe-area-inset-bottom);
  background-color: #f2f2f2;
  display: flex;
  align-items: flex-end;
  position: fixed;
  z-index: 2000;
  bottom: -2rpx;
  transition: all 0.15s linear;
}

.input-box [class*='wlIcon-'] {
  font-size: 50rpx;
  color: #323232;
}

.input-box .wlIcon-zhifeiji {
  color: #fe6600;
}

.input-box.showLayer {
  transform: translate3d(0, -480rpx, 0);
}

.input-box .voice,
.input-box .more {
  flex-shrink: 0;
  width: 90rpx;
  height: 100rpx;
  display: flex;
  justify-content: center;
  align-items: center;
}

.input-box .send {
  flex-shrink: 0;
  width: 90rpx;
  height: 100rpx;
  display: flex;
  justify-content: center;
  align-items: center;
}

.input-box .send .btn {
  width: 110rpx;
  height: 70rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 16rpx;
  font-size: 32rpx;
}

.input-box .textbox {
  width: 100%;
}

.input-box .textbox .voice-mode {
  width: calc(100% - 2upx);
  height: 80rpx;
  margin: 10rpx 0;
  border-radius: 16rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 28rpx;
  background-color: #fff;
  color: #555;
}

.input-box .textbox .voice-mode.recording {
  background-color: #e5e5e5;
}

.input-box .textbox .text-mode {
  width: 100%;
  min-height: 80rpx;
  margin: 10rpx 0;
  display: flex;
  background-color: #ffffff;
  border-radius: 16rpx;
}

.input-box .textbox .text-mode .box {
  width: 100%;
  padding-left: 30rpx;
  min-height: 80rpx;
  display: flex;
  align-items: center;
}

.input-box .textbox .text-mode .box textarea {
  width: 100%;
}

.input-box .textbox .text-mode .em {
  flex-shrink: 0;
  width: 80rpx;
  padding-left: 10rpx;
  height: 80rpx;
  display: flex;
  justify-content: center;
  align-items: center;
}

.record {
  width: 39vw;
  height: 39vw;
  position: fixed;
  top: 35%;
  left: 30%;
  background-color: rgba(0, 0, 0, 0.8);
  border-radius: 40rpx;
}

.record .ing {
  width: 100%;
  height: 30vw;
  display: flex;
  justify-content: center;
  align-items: center;
}

@keyframes volatility {
  0% {
    background-position: 0% 130%;
  }

  20% {
    background-position: 0% 150%;
  }

  30% {
    background-position: 0% 155%;
  }

  40% {
    background-position: 0% 160%;
  }

  50% {
    background-position: 0% 145%;
  }

  70% {
    background-position: 0% 150%;
  }

  80% {
    background-position: 0% 170%;
  }

  90% {
    background-position: 0% 160%;
  }

  100% {
    background-position: 0% 135%;
  }
}

.record .ing [class*='wlIcon'] {
  background-image: linear-gradient(to bottom, #ffffff, #565656 50%);
  background-size: 100% 200%;
  animation: volatility 1.5s ease-in-out -1.5s infinite alternate;
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  font-size: 140rpx;
  padding-top: 40rpx;
  color: #f09b37;
}

.record .cancel {
  width: 100%;
  height: 30vw;
  display: flex;
  justify-content: center;
  align-items: center;
}

.record .cancel [class*='wlIcon'] {
  color: #fff;
  font-size: 150rpx;
}

.record .tis {
  width: 100%;
  height: 10vw;
  display: flex;
  justify-content: center;
  font-size: 24rpx;
  color: #fff;
}

.record .tis.change {
  color: #f09b37;
}

.content {
  width: 100%;
}

page {
  background-color: #ececec;
}

.content .msg-list,
.cu-chat {
  position: absolute;
  top: 0;
  bottom: 100rpx;
  bottom: calc(env(safe-area-inset-bottom) + 100rpx);
  background-color: #ececec;
}

.loading {
  display: flex;
  justify-content: center;
}

@keyframes stretchdelay {

  0%,
  40%,
  100% {
    transform: scaleY(0.6);
  }

  20% {
    transform: scaleY(1);
  }
}

.loading .spinner {
  margin: 20upx 0;
  width: 60upx;
  height: 100upx;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.loading .spinner view {
  background-color: #dadada;
  height: 50upx;
  width: 6upx;
  border-radius: 6upx;
  animation: stretchdelay 1.2s infinite ease-in-out;
}

.loading .spinner .rect2 {
  animation-delay: -1.1s;
}

.loading .spinner .rect3 {
  animation-delay: -1s;
}

.loading .spinner .rect4 {
  animation-delay: -0.9s;
}

.loading .spinner .rect5 {
  animation-delay: -0.8s;
}
</style>