<template>
  <view class="chat-item">
    <view
      :class="{
        'chat-container': true,
        'chat-location-me': item.msg_source == 1,
      }"
    >
      <!-- 头像 -->
      <view class="chat-icon-container">
        <image class="chat-icon" :src="avatar" mode="aspectFill" />
      </view>

      <!-- 聊天内容 -->
      <view class="chat-content-container">
        <!-- 名字 -->
        <text
          :class="{
            'chat-user-name': true,
            'chat-location-me': item.msg_source == 1,
          }"
          @tap="jumpOrderDetail(item.order_id)"
        >
          {{
            item.msg_source == 2
              ? (item.order_id ? item.sendType.toUpperCase() + '客户(' + item.order_id + ')':item.sendType.toUpperCase() + '客户')
              : getStorage('storeName')
          }}
        </text>

         <!-- 内容 -->
        <view 
          :style="{
            'display':'flex',
            'justify-content':item.msg_source === 1?'flex-end':'flex-start',
            'margin-right':item.msg_source === 1?'20rpx':'0rpx'
          }" >
          
          <!-- emoji -->
          <view
            :class="{
              'chat-text-container': true,
              'chat-text-container-me': item.msg_source == 1
            }"
            v-if="item.msg_type === 1 || item.msg_type == 11"
            class="emoji-box"
          >
            <template v-for="(i, index) in item.msg_content" :key="index">
              <text 
                v-if="i.type === 'text'" 
                :class="{ 'char-text': true, 'char-text-me': item.msg_source == 1 }" 
                user-select 
                selectable 
              >
                {{ i.text }}
              </text>
              <text
                v-else-if="i.type === 'emoji' && i.emoji.includes('unknown:')"
                :class="{ 'char-text': true, 'char-text-me': item.msg_source == 1 }" 
                user-select 
                selectable
              >
                {{ i.emoji.substring(8) }}
              </text>
              <image v-else :src="`https://www.jxc4.com/emoji/${i.emoji}.png`" alt="" style="width:20px;height:20px;"></image>
            </template>
          </view>

          <!-- 图片 -->
          <view
            :class="{
              'chat-text-container-img': true,
              'chat-text-container-me-img': item.msg_source == 1,
            }"
            v-else-if="item.msg_type == 2 || item.msg_type == 12"
          >
            <image
              @tap="previewImage(item.msg_content)"
              :src="item.msg_content"
              mode="widthFix"
            />
          </view>
          
          <!-- 视频 -->
          <view
           :class="{
              'chat-text-container-img': true,
              'chat-text-container-me-img': item.msg_source == 1,
            }"
            v-else-if="item.msg_type == 6"
          >
            <video
              :src="item.msg_content">
            </video>
          </view>

          <!-- 语音 -->
          <view
            class="chat-text-container yuyin"
            :class="{ isVoice: isVoice }"
            v-else-if="item.msg_type == 3 || item.msg_type == 13"
            @tap="playVoice(item.msg_content)"
          >
            <jx-icon icon="yuyin" :size="42" />
          </view>

          <!-- 商品卡片 -->
          <view class="chat-text-container" v-else-if="item.msg_type == 4 || item.msg_type == 14" @tap="copyInfo(item.msg_content)">
            <!--【暂不支持查看商品-请让客户发送图片】 -->
            skuid:{{ item.msg_content }} <text style="color:rgb(64, 158, 255);text-decoration: underline;" @tap.stop="viewSku(item.msg_content)">查看商品</text>
          </view>

          <!-- 订单卡片 -->
          <view
            class="chat-text-container order-car"
            v-else-if="item.msg_type == 5  && item.msg_content"
            @tap="orderDetail(JSON.parse(item.msg_content).order_view_id, '1')"
          >
            <view class="top">{{ JSON.parse(item.msg_content).food_desc }}</view>
            <view class="bottom">
              <view class="status">{{
                JSON.parse(item.msg_content).status_desc
              }}</view>
              <view>订单详情<jx-icon icon="gengduo" color="#6e6e6e" /></view>
            </view>
          </view>

          <view
            class="chat-text-container"
            v-else-if="item.msg_type == 101">
            <!-- 自定义消息卡片 -->
             <view>
                <view class="top">{{ item.msg_content }}</view>
                <view class="bottom">
                  {{ item.payLoad.content.data.mistTemplate.error }}
                  <!-- {{ JSON.parse(item.payLoad.content).data }} -->
                </view>
             </view>
          </view>

          <!-- 兜底 -->
          <view class="chat-text-container" v-else> 【未知信息】 </view>
        </view>
        
      </view>
    </view>

    <!-- 商品弹框 -->
    <uni-popup ref="popup" type="center">
      <view class="jx-popup-update">
        <view class="text">查看商品信息</view>
        <view>
          <image :src="goodCard.img" />
        </view>
        <view class="goodCard_name">{{ goodCard.name }}</view>
        <jx-price v-if="goodCard.unitPrice" :price="goodCard.skus[0].mtwmPrice" color="#ef5757" />

        <view class="btn-root">
          <view class="btn-ok"  @tap="popup.close()">关闭</view>
        </view>
        
      </view>
    </uni-popup>
  </view>


</template>

<script lang="ts" setup >
import useGlobalFunc from '@/composables/useGlobalFunc'
import useOrderInfo from '@/composables/useOrderInfo'
import { getStorage } from '@/utils/storage'
import toast from '@/utils/toast'
import { computed, ref } from 'vue'
import order from '@/api/https/order'
import merchant from '@/api/https/merchant'
const { previewImage } = useGlobalFunc()
const { orderDetail } = useOrderInfo()

/*************************************************
 * 接收数据
 */
interface PropsType {
  item: any
}
const props = defineProps<PropsType>()
const avatar = computed(() => {
  if (props.item.msg_source == 1) {
    return 'https://image.jxc4.com/image/70143fcf48aefe74537533f35a0a8153.jpg'
  } else {
    if (props.item.sendType == 'mt') {
      return 'https://image.jxc4.com/image/75654ab606494a0efdb0cf7d7ad060d9.png'
    } else {
      return 'https://image.jxc4.com/image/6c2f1dfd95890df8ef5e27bde15c4e7f.png'
    }
  }
})

const popup = ref<any>(null)     // 弹窗实例
const goodCard = ref({           // 商品卡片
  img:'https://image.jxc4.com/image/5c506c8db41719fe4c433979498eb1e7.png',
  name:'三方平台创建商品',
  unit: '',
  unitPrice: '',
  skus: [
    {
      id:'',
      mtwmPrice:''
    }
  ]
})

/*************************************************
 * 播放语音
 */
const isVoice = ref<boolean>(false)
const voice = uni.createInnerAudioContext()
function playVoice(playUrl: string) {
  if (uni.getSystemInfoSync().platform != 'android')
    return toast('ios系统不支持')
  toast('正在播放音频')
  isVoice.value = true
  voice.src = playUrl
  voice.stop()
  voice.play()
  voice.onEnded(() => {
    isVoice.value = false
  })
}

/**
 * 跳转到订单详情页
 */
 async function jumpOrderDetail(orderId: string) {
  if(!orderId) return
  let res = await order.get_orders({ vendorOrderID: orderId })
  if (res.code === '0') orderDetail(res.data.data[0].vendorOrderID, res.data.data[0].vendorID)
}


/*************************************************
 * 查看商品
 */
async function viewSku(skuid: string) {
  console.log(skuid,'skuid',goodCard.value)
  if(skuid == goodCard.value.skus[0].id) return popup.value.open()
  
  let data = {
      storeIDs: JSON.stringify([getStorage('storeID')]),
      isFocus: true,
      skuIDs: JSON.stringify([+skuid])
  }
  let res = await merchant.get_stores_skus(data)
  console.log('走到下面了吗',res)
  if(res.code === '0' && res.data.totalCount === 1) goodCard.value = res.data.skuNames[0]
  popup.value.open()
}

/*************************************************
 * 复制商品shuid
 */
function copyInfo(data:string) {
  uni.setClipboardData({
      data: data,
      success() {
          toast('复制成功', 1)
      },
      fail() {
          toast('复制失败')
      }
  })
}
</script>

<style lang="scss" scoped>
@import './index.scss';
.chat-item {
  display: flex;
  flex-direction: column;
  padding: 20rpx;
  box-sizing: border-box;
}
.chat-time {
  padding: 4rpx 0rpx;
  text-align: center;
  font-size: 22rpx;
  color: #aaaaaa;
}
.chat-container {
  display: flex;
  flex-direction: row;
}
.chat-location-me {
  flex-direction: row-reverse;
  text-align: right;
}
.chat-icon-container {
  margin-top: 12rpx;
}
.chat-icon {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  background-color: #eeeeee;
}
.chat-content-container {
  margin: 0rpx 15rpx;
}
.chat-user-name {
  font-size: 28rpx;
  color: #888888;
}
.chat-text-container {
  background-color: #ffffff;
  border-radius: 8rpx;
  padding: 10rpx 15rpx;
  margin-top: 10rpx;
  /* #ifndef APP-NVUE */
  max-width: 500rpx;
  /* #endif */
  width: fit-content;
}
.chat-text-container-img {
  border-radius: 8rpx;
  margin-top: 10rpx;
  /* #ifndef APP-NVUE */
  max-width: 280rpx;
  /* #endif */

  image {
    width: 280rpx;
    border-radius: 8rpx;
  }
}

.yuyin {
  text-align: center;
}

// 订单卡片
.order-car {
  font-size: 28rpx;

  .top {
    width: 400rpx;
    overflow: hidden;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2;
    text-decoration: underline;
    color: #0867e3;
    margin-bottom: 10rpx;
  }

  .bottom {
    display: flex;
    justify-content: space-between;
    border-top: 1rpx solid #e6e6e6;
    padding-top: 8rpx;
    color: #6e6e6e;

    .status {
      color: #6e6e6e;
    }
  }
}

.chat-text-container-me {
  background-color: #95eb6c;
  text-align: left;
}
.chat-text-container-me-img {
  text-align: left;
}
.char-text {
  font-size: 32rpx;
  /* #ifndef APP-NVUE */
  word-break: break-all;
  /* #endif */
  /* #ifdef APP-NVUE */
  max-width: 500rpx;
  /* #endif */
}
.char-text-me {
  color: #000;
}

.isVoice {
  animation: Gradient 2s linear infinite;
}
@keyframes Gradient {
  0% {
    background: linear-gradient(0deg, #ee7752, #e73c7e, #23a6d5, #23d5ab);
  }
  100% {
    background: linear-gradient(180deg, #ee7752, #e73c7e, #23a6d5, #23d5ab);
  }
}
</style>