<template>
  <!-- 文本消息 -->
  <text v-if="message.type === 'TIMTextElem'" class="message-text">
    {{ message.payload.text }}
  </text>

  <!-- 图片消息 -->
  <image v-else-if="message.type === 'TIMImageElem'" class="message-image" :src="message.payload.imageInfoArray[0].LocalURL ||
    message.payload.imageInfoArray[0].url
    " mode="aspectFill" :style="getImageStyle(message.payload.imageInfoArray[0])" @click="
      $emit(
        'previewImage',
        message.payload.imageInfoArray[0].LocalURL ||
        message.payload.imageInfoArray[0].url
      )
      " />

  <!-- 语音消息 -->
  <view v-else-if="message.type === 'TIMSoundElem'" class="voice-message" :class="{ 'voice-playing': isPlaying }"
    :style="getVoiceStyle(message.payload.second)" @click="$emit('playVoice', message)">
    <view class="voice-content">
      <view class="voice-icon-wrapper">
        <uni-icons type="sound" size="20" :color="message.flow === 'out' ? '#fff' : '#333'"
          :class="{ 'icon-animate': isPlaying }" />
        <!-- 播放中的声波动画 -->
        <view v-if="isPlaying" class="sound-wave">
          <view class="wave-bar" :style="{ background: message.flow === 'out' ? '#fff' : '#0877f1' }"
            style="animation-delay: 0s"></view>
          <view class="wave-bar" :style="{ background: message.flow === 'out' ? '#fff' : '#0877f1' }"
            style="animation-delay: 0.2s"></view>
          <view class="wave-bar" :style="{ background: message.flow === 'out' ? '#fff' : '#0877f1' }"
            style="animation-delay: 0.4s"></view>
        </view>
      </view>
      <text class="voice-duration">{{ message.payload.second }}"</text>
    </view>
  </view>

  <!-- 自定义消息卡片 -->
  <template v-else-if="message.type === 'TIMCustomElem'">
    <!-- 文章消息 -->
    <view v-if="getCustomMessageType(message) === 'article'" class="article-card" @click="handleArticleClick(message)">
      <view class="article-content">
        <view class="article-title">{{ getArticleData(message).title }}</view>
        <view class="article-desc">{{ getArticleData(message).desc }}</view>
      </view>
      <image v-if="getArticleData(message).cover" class="article-image" :src="getArticleData(message).cover"
        mode="aspectFill" />
    </view>

    <!-- 问卷消息 -->
    <view v-else-if="getCustomMessageType(message) === 'survey'" class="survey-card"
      @click="handleSurveyClick(message)">
      <view class="survey-content">
        <view class="survey-title">{{ getSurveyData(message).title }}</view>
        <view class="survey-desc">{{ getSurveyData(message).desc }}</view>
      </view>
      <image v-if="getSurveyData(message).imgUrl" class="survey-image" :src="getSurveyData(message).imgUrl"
        mode="aspectFill" />
    </view>

    <!-- 其他自定义消息 -->
    <!-- <view
      v-else
      class="card-avatar-row"
      @click="() => console.log('点击头像', message)"
    >
      <MessageCard
        :payload="message.payload"
        :messageData="getParsedCustomMessage(message, formatTime)"
        :flow="message.flow"
        @viewDetail="$emit('viewDetail', $event)"
      />
    </view> -->
  </template>
</template>

<script setup>
import { computed } from "vue";
import { storeToRefs } from "pinia";
import api from "@/utils/api.js";
import { getParsedCustomMessage } from "@/utils/chat-utils.js";
import { toast } from '@/utils/widget'
import useAccountStore from "@/store/account.js";

// import MessageCard from "./message-card/message-card.vue";

const props = defineProps({
  corpId: String,
  message: Object,
  patientInfo: Object,
  formatTime: Function,
  playingVoiceId: {
    type: String,
    default: null,
  },
});

defineEmits(["playVoice", "previewImage", "viewDetail"]);
const { account, openid } = storeToRefs(useAccountStore());

// 计算当前语音是否正在播放
const isPlaying = computed(() => {
  return props.playingVoiceId === props.message.ID;
});

const payloadData = computed(() => {
  try {
    return JSON.parse(props.message.payload.data);
  } catch (e) {
    return {}
  }
})


// 计算图片样式
const getImageStyle = (imageInfo) => {
  // 如果没有尺寸信息，使用默认样式
  imageInfo.width = imageInfo.width || imageInfo.Width;
  imageInfo.height = imageInfo.height || imageInfo.Height;
  if (!imageInfo || !imageInfo.width || !imageInfo.height) {
    return {
      width: "400rpx",
      height: "300rpx",
    };
  }

  const maxWidth = 400; // 最大宽度400rpx
  const maxHeight = 400; // 最大高度400rpx
  const minHeight = 120; // 最小高度120rpx

  let width = imageInfo.width;
  let height = imageInfo.height;

  // 如果图片尺寸超过限制，按比例缩放
  if (width > maxWidth || height > maxHeight) {
    const ratio = Math.min(maxWidth / width, maxHeight / height);
    width = Math.floor(width * ratio);
    height = Math.floor(height * ratio);
  }

  // 确保最小高度
  if (height < minHeight) {
    height = minHeight;
  }

  return {
    width: width + "rpx",
    height: height + "rpx",
  };
};

// 计算语音消息宽度
const getVoiceStyle = (duration) => {
  // 语音时长，单位：秒
  const second = Number(duration) || 1;

  // 基础宽度：100rpx（包含图标和时长文字的最小宽度）
  const baseWidth = 100;

  // 最小宽度：100rpx，最大宽度：400rpx
  const minWidth = 100;
  const maxWidth = 400;

  // 每秒增加的宽度：15rpx
  // 1秒：100rpx，2秒：115rpx，3秒：130rpx ... 60秒：400rpx
  const widthPerSecond = 15;

  // 计算宽度
  let width = baseWidth + (second - 1) * widthPerSecond;

  // 限制在最小和最大宽度之间
  width = Math.max(minWidth, Math.min(width, maxWidth));

  return {
    width: width + "rpx",
  };
};

// 获取自定义消息类型
const getCustomMessageType = (message) => {
  try {
    if (message.payload && message.payload.data) {
      const data = JSON.parse(message.payload.data);
      return data.type || "";
    }
  } catch (error) {
    console.error("解析自定义消息失败:", error);
  }
  return "";
};

// 获取文章数据
const getArticleData = (message) => {
  try {
    if (message.payload && message.payload.data) {
      const data = JSON.parse(message.payload.data);
      return data;
    }
  } catch (error) {
    console.error("解析文章数据失败:", error);
  }
  return {
    title: "宣教文章",
    desc: "宣教文章",
    url: "",
    imgUrl: "",
  };
};

// 处理文章点击
const handleArticleClick = (message) => {
  if (isWechatChannels()) {
    uni.openChannelsActivity({
      finderUserName: payloadData.value.wechatChannels.finderUserName,
      feedId: payloadData.value.wechatChannels.feedId,
      success: () => {
        markArticleRead(payloadData.value.sendId, payloadData.value.articleId);
      },
      fail: err => {
        const errMsg = err.errMsg || '';
        if (/cancel/i.test(errMsg)) {
          return
        }
        toast(`打开视频号失败:${errMsg}`)
      }
    })
    return
  }
  const { articleId, sendId } = getArticleData(message);
  uni.navigateTo({
    url: `/pages/article/article-detail?id=${articleId}&sendId=${sendId || ''}&corpId=${props.corpId}`,
  });
};

// 获取问卷数据
const getSurveyData = (message) => {
  try {
    if (message.payload && message.payload.data) {
      const data = JSON.parse(message.payload.data);
      return {
        ...data,
        title: data.title || "填写问卷",
        desc: data.desc || "请填写问卷",
        url: data.url || "",
        imgUrl: data.imgUrl || "",
      };
    }
  } catch (error) {
    console.error("解析问卷数据失败:", error);
  }
  return {
    title: "填写问卷",
    desc: "请填写问卷",
    url: "",
    imgUrl: "",
    err: true
  };
};

// 处理问卷点击
const handleSurveyClick = (message) => {
  const surveyData = getSurveyData(message);
  if (surveyData.err) {
    return
  }
  if (surveyData.isSystem) {
    uni.navigateTo({
      url: `/pages/web-view/web-view?src=${encodeURIComponent(surveyData.url)}`
    })
    return
  }
  if (surveyData.answerId) {
    uni.navigateTo({
      url: `/pages/survey/fill?name=${surveyData.name}&memberId=${surveyData.memberId}&surveryId=${surveyData.surveryId}&corpId=${surveyData.corpId}&answerId=${surveyData.answerId}`
    })
  }
};

function isWechatChannels() {
  const wechatChannels = payloadData.value.wechatChannels || {};
  return typeof wechatChannels.finderUserName === 'string' && wechatChannels.finderUserName.trim() && typeof wechatChannels.feedId === 'string' && wechatChannels.feedId.trim();
}

async function markArticleRead(sendId, articleId) {
  const unionid = account.value?.unionid;
  if (!unionid || !articleId) return;
  try {
    const { success } = await api(
      "addArticleReadRecord",
      { corpId: props.corpId, articleId, unionid, sendId },
      false
    );
  } catch (err) {
    console.warn("markArticleRead failed:", err?.message || err);
  }
};
</script>

<style scoped lang="scss">
@import "../chat.scss";
</style>