<template>
  <view class="container" :class="{ 'panel-active': activePanel !== 'none' }">
    <!-- 状态栏占位（微信小程序用 JS 获取真实高度）-->
    <view class="status-bar" :style="{ height: statusBarHeight + 'px' }"></view>

    <!-- 导航栏 -->
    <view class="nav-bar">
      <view class="back-btn" @click="goBack">
        <text class="back-arrow">‹</text>
      </view>
      <view class="nav-center">
        <text class="nav-title-text">{{ sessionUserName || '在线咨询' }}</text>
        <view class="online-dot"></view>
      </view>
      <view class="nav-right"></view>
    </view>

    <!-- 聊天内容区域 -->
    <scroll-view
      class="chat-body"
      scroll-y
      :scroll-into-view="lastMessageId"
      :style="{ height: chatBodyHeight }"
      :show-scrollbar="false"
      :enhanced="true"
    >
      <view class="message-list">
        <!-- 加载中 -->
        <view v-if="loading" class="tip-row">
          <text class="tip-text">加载中...</text>
        </view>

        <!-- 静态初始卡片区（每次进入均显示） -->
        <view v-if="!loading" class="init-cards">

          <!-- 测评卡片（动态渲染，内容来自 URL 参数）-->
          <view v-if="chatType === 'assessment'" class="msg-row left">
            <image :src="waiterAvatar" class="avatar" mode="aspectFill"></image>
            <view class="msg-content assessment-card-msg">
              <view class="card-left">
                <image
                  :src="assessmentCover || '/static/images/assess_cover.svg'"
                  class="a-cover"
                  mode="aspectFill"
                ></image>
              </view>
              <view class="card-right">
                <text class="a-title">{{ assessmentTitle || '测评咨询' }}</text>
                <view class="a-tags">
                  <text v-if="assessmentLevel" class="a-tag">{{ assessmentLevel }}</text>
                  <text class="a-tag">职业技能测评</text>
                </view>
                <text class="a-price">{{ assessmentPrice ? '￥' + assessmentPrice : '咨询获取' }}</text>
              </view>
            </view>
          </view>

          <!-- 培训报名卡片 -->
          <view v-else-if="chatType === 'training'" class="msg-row left">
            <image :src="waiterAvatar" class="avatar" mode="aspectFill"></image>
            <view class="msg-content training-reg-card shadow">
              <view class="t-card-header">
                <text class="t-card-title">{{ trainingTitle || '审计员线下培训' }}</text>
                <text class="t-card-subtitle">线下培训 | 职业能力提升</text>
              </view>
              <view class="t-card-body">
                <view class="t-item"><text class="t-label">主办单位：</text><text class="t-val">AAAAA单位</text></view>
                <view class="t-item"><text class="t-label">培训时间：</text><text class="t-val">2025-12-12/13/14</text></view>
              </view>
              <view class="t-card-footer">
                <button class="reg-btn" @click="confirmReg">确认报名</button>
              </view>
            </view>
          </view>

          <!-- 招聘卡片（默认） -->
          <view v-else class="msg-row left">
            <image :src="waiterAvatar" class="avatar" mode="aspectFill"></image>
            <view class="msg-content job-card-msg">
              <view class="card-header">
                <view class="ch-left">
                  <text class="card-title">{{ jobName || '审计员' }}</text>
                  <text class="urgent-tag">急招</text>
                </view>
                <text class="card-salary">{{ salaryRange || '13K-23K' }}</text>
              </view>
              <view class="card-tags">
                <text class="c-tag">实习</text>
                <text class="c-tag">五险一金</text>
                <text class="c-tag">985</text>
              </view>
              <view class="card-meta">
                <view class="m-item"><image src="/static/icons/user.svg" class="m-icon"></image><text>招录 1 人</text></view>
                <view class="m-item"><image src="/static/icons/time.svg" class="m-icon"></image><text>截止时间：2025-12-12 24:00</text></view>
              </view>
              <view class="card-company">
                <image src="/static/images/logo1.png" class="c-logo" mode="aspectFit"></image>
                <view class="c-info">
                  <text class="c-name">{{ companyName || '华财仁合' }}</text>
                  <image src="/static/icons/verified.svg" class="v-icon"></image>
                </view>
                <text class="c-loc">{{ workCity ? '上海市·' + workCity : '上海市·黄浦区' }}</text>
              </view>
            </view>
          </view>

        </view>

        <!-- 无后续消息提示（不覆盖初始卡片）-->
        <view v-if="!loading && messages.length === 0" class="tip-row">
          <text class="tip-text">快发一条消息开始吧～</text>
        </view>

        <!-- 消息列表（全部来自真实API） -->
        <block v-for="(msg, index) in messages" :key="msg.id || index">
          <!-- 每隔5分钟显示时间戳 -->
          <view v-if="shouldShowTime(msg, index)" class="time-stamp-row">
            <text class="time-stamp">{{ formatTime(msg.sendTime) }}</text>
          </view>

          <view
            :id="'msg-' + (msg.id || index)"
            class="msg-row"
            :class="msg.senderType === 1 ? 'right' : 'left'"
          >
            <image
              v-if="msg.senderType !== 1"
              :src="resolveAvatarUrl(msg.senderAvatar) || waiterAvatar"
              class="avatar"
              mode="aspectFill"
            ></image>

            <!-- 文本消息 -->
            <view
              v-if="msg.msgType === 'text'"
              class="msg-content text-msg"
              :class="msg.senderType === 1 ? 'user-bubble' : 'shadow'"
            >{{ msg.content }}</view>

            <!-- 图片消息 -->
            <view v-else-if="msg.msgType === 'image'" class="msg-content img-msg">
              <image
                :src="msg.fileUrl"
                mode="widthFix"
                class="chat-img"
                @click="previewImg(msg.fileUrl)"
              ></image>
            </view>

            <!-- 文件消息 -->
            <view v-else-if="msg.msgType === 'file'" class="msg-content file-msg shadow">
              <text class="file-icon-txt">📄</text>
              <view class="file-info">
                <text class="file-name">{{ msg.fileName || '文件' }}</text>
                <text class="file-size">{{ formatFileSize(msg.fileSize) }}</text>
              </view>
            </view>

            <view v-else-if="msg.msgType === 'order_card'" class="msg-content deposit-card">
              <view class="deposit-header">
                <view class="d-header-left">
                  <text class="d-title">您有一笔待付款项</text>
                  <text class="d-subtitle">项目费用及定金支付通知</text>
                </view>
                <view v-if="!msg.isPaid && msg.countdown > 0" class="d-countdown">
                  <text class="c-time">{{ msg.countdown }}s</text>
                  <text class="c-txt">后取消</text>
                </view>
                <view v-if="msg.isPaid" class="d-paid-tag">已支付</view>
              </view>
              <view class="deposit-body">
                <view class="d-row">
                  <text class="label">项目名称：</text>
                  <text class="val">{{ msg.payload && msg.payload.name || '—' }}</text>
                </view>
                <view class="d-row">
                  <text class="label">支付金额：</text>
                  <text class="price">￥{{ formatAmount(msg.payload && msg.payload.amount) }}</text>
                </view>
              </view>
              <view
                class="deposit-action"
                :class="{ paid: msg.isPaid }"
                @click="handlePay(msg)"
              >{{ msg.isPaid ? '已支付' : '立即支付' }}</view>
            </view>

            <!-- 客服推送的岗位卡片 -->
            <view v-else-if="msg.msgType === 'job_card'" class="msg-content api-job-card shadow">
              <view class="jc-header">
                <text class="jc-title">{{ msg.payload && msg.payload.title || '岗位推荐' }}</text>
                <text class="jc-salary">{{ msg.payload && msg.payload.salaryRange || '' }}</text>
              </view>
              <text class="jc-city" v-if="msg.payload && msg.payload.workCity">{{ msg.payload.workCity }}</text>
            </view>

            <!-- 系统消息 -->
            <view v-else-if="msg.senderType === 3" class="system-msg">
              <text>{{ msg.content }}</text>
            </view>

            <!-- 其他未知类型 -->
            <view v-else class="msg-content text-msg shadow">{{ msg.content || '[消息]' }}</view>

            <image
              v-if="msg.senderType === 1"
              :src="resolveAvatarUrl(msg.senderAvatar) || userAvatarUrl"
              class="avatar"
              mode="aspectFill"
            ></image>
          </view>
        </block>

        <view id="bottom-anchor" style="height: 40rpx;"></view>
      </view>
    </scroll-view>

    <!-- 底部输入栏 -->
    <view class="footer-wrap">
      <view class="input-bar">
        <image
          :src="inputMode === 'text' ? '/static/icons/audio_thin.svg' : '/static/icons/keyboard.svg'"
          class="bar-icon"
          mode="aspectFit"
          @click="toggleInputMode"
        ></image>

        <view class="center-area">
          <input
            v-if="inputMode === 'text'"
            v-model="inputValue"
            class="chat-input"
            placeholder="请输入内容..."
            confirm-type="send"
            @confirm="sendMessage"
            @focus="onInputFocus"
          />
          <view v-else class="voice-press-btn" @touchstart="onVoiceStart" @touchend="onVoiceEnd">按住 说话</view>
        </view>

        <image
          src="/static/icons/emoji_thin.svg"
          class="bar-icon"
          :class="{ active: activePanel === 'emoji' }"
          mode="aspectFit"
          @click="togglePanel('emoji')"
        ></image>

        <image
          :src="activePanel === 'plus' ? '/static/icons/plus_active.svg' : '/static/icons/plus_thin.svg'"
          class="bar-icon"
          mode="aspectFit"
          @click="togglePanel('plus')"
        ></image>
      </view>

      <view class="panel-section" :class="{ show: activePanel !== 'none' }">
        <view class="emoji-panel" v-if="activePanel === 'emoji'">
          <scroll-view scroll-y class="emoji-scroll">
            <view class="emoji-grid">
              <text v-for="e in emojiList" :key="e" class="emoji-item" @click="addEmoji(e)">{{e}}</text>
            </view>
          </scroll-view>
        </view>
        <view class="plus-panel" v-if="activePanel === 'plus'">
          <view class="panel-item" @click="chooseImage">
            <view class="icon-box shadow-sm">
              <image src="/static/icons/album_color.svg" mode="aspectFit"></image>
            </view>
            <text>相册</text>
          </view>
          <view class="panel-item" @click="sendMockOrderCard">
            <view class="icon-box shadow-sm">
              <image src="/static/icons/order_color.svg" mode="aspectFit"></image>
            </view>
            <text>订单</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="js">
import { ref, computed, nextTick } from 'vue';
import { onLoad, onUnload } from '@dcloudio/uni-app';
import { getChatHistory, sendTextMessage, sendImageMessage, markChatRead, payOrderCard, createOrderByOrderCard, createWxPayOrder, autoCreateOrderCard } from '../../api/message.js';
import { getStudent } from '../../api/student.js';
import { connectChat, sendTextByWs, disconnectChat, subscribe, unsubscribe, generateMsgNo, isSocketConnected } from '../../utils/chatSocket.js';
import { BASE_URL } from '../../utils/request.js';

// ---- 状态 ----
const loading = ref(true);
const messages = ref([]);
const inputValue = ref('');
const inputMode = ref('text');
const activePanel = ref('none');
const lastMessageId = ref('bottom-anchor');
const statusBarHeight = ref(20); // 状态栏高度，微信小程序动态获取

// ---- 会话信息（从URL参数传入）----
const sessionId = ref(null);
const fromUserId = ref(null);
const sessionUserName = ref('');
const jobName = ref('');
const chatType = ref('job');
const trainingTitle = ref('');

// ---- 测评信息（咨询时从URL参数传入）----
const assessmentTitle = ref('');
const assessmentCover = ref('');
const assessmentLevel = ref('');
const assessmentId = ref('');
const assessmentPrice = ref('');

// ---- 岗位信息（咨询时从URL参数传入）----
const positionId = ref(null);
const salaryRange = ref('');
const companyName = ref('');
const workCity = ref('');

// ---- 头像 ----
const waiterAvatar = ref('/static/images/hr_avatar.svg');
// 将 OSS ID 或无效头像转为可访问的 URL
function resolveAvatarUrl(url) {
  if (!url || url === '' || url === 'undefined') return '';
  const str = String(url).trim();
  // 已经是有效 HTTP URL（后端 ossService.selectUrlByIds 已转为真实 URL）
  if (str.startsWith('http://') || str.startsWith('https://')) return str;
  // 纯数字 → OSS 文件 URL（后端接口）
  if (/^\d+$/.test(str)) {
    return `${BASE_URL}/resource/oss/file/${str}`;
  }
  // 本地路径 → 空值
  if (str.startsWith('/static/')) return '';
  return str;
}
// 判断是否为有效的可访问URL
function isValidAvatar(url) {
  if (!url || url === '' || url === 'undefined') return false;
  const str = String(url).trim();
  if (str.startsWith('/static/')) return false;
  // 纯数字是 OSS ID，不是可访问的图片 URL
  if (/^\d+$/.test(str)) return false;
  return true;
}
const userAvatarUrl = ref('/static/images/user_avatar.png');

const emojiList = ['😀','😃','😄','😁','😆','😅','😂','🤣','😊','😇','🙂','🙃','😉','😌','😍','🥰','😘','😗','😙','😚','😋','😛','😝','😜','🤪','🤨','🧐','🤓','😎','🤩','🥳'];

let wsSubId = null; // WebSocket 订阅 ID

// ---- 生命周期 ----
onLoad(async (options) => {
  // 获取状态栏高度（微信小程序中 env(safe-area-inset-top) 为0，需要通过 JS 获取）
  // #ifdef MP-WEIXIN
  try {
    const sysInfo = uni.getSystemInfoSync();
    statusBarHeight.value = sysInfo.statusBarHeight || 20;
  } catch (e) {}
  // #endif

  if (options.sessionId)  sessionId.value = options.sessionId;
  if (options.fromUserId) fromUserId.value = options.fromUserId;
  if (options.userName)   sessionUserName.value = decodeURIComponent(options.userName);
  if (options.jobName)    jobName.value = decodeURIComponent(options.jobName);
  if (options.type)       chatType.value = options.type;
  // 培训标题
  if (options.title)      trainingTitle.value = decodeURIComponent(options.title || '');
  // 测评参数解析
  if (options.title && options.type === 'assessment') {
    assessmentTitle.value = decodeURIComponent(options.title || '');
  }
  if (options.cover)      assessmentCover.value = decodeURIComponent(options.cover || '');
  if (options.level)      assessmentLevel.value = decodeURIComponent(options.level || '');
  if (options.assessmentId) assessmentId.value = options.assessmentId;
  if (options.price)      assessmentPrice.value = options.price;
  // 岗位参数解析
  if (options.positionId) positionId.value = options.positionId;
  if (options.salaryRange) salaryRange.value = decodeURIComponent(options.salaryRange);
  if (options.companyName) companyName.value = decodeURIComponent(options.companyName);
  if (options.workCity) workCity.value = decodeURIComponent(options.workCity);

  const storedInfo = uni.getStorageSync('userInfo') || {};
  // 用户头像：优先用存储的 avatarUrl，再尝试 avatar（可能是 OSS ID）
  const rawUserAvatar = storedInfo.avatarUrl || storedInfo.avatar || '/static/images/user_avatar.png';
  userAvatarUrl.value = resolveAvatarUrl(rawUserAvatar) || '/static/images/user_avatar.png';
  if (!fromUserId.value && storedInfo.studentId) fromUserId.value = storedInfo.studentId;

  if (!sessionId.value) {
    loading.value = false;
    uni.showToast({ title: '会话参数缺失', icon: 'none' });
    return;
  }

  await loadHistory();

  // 建立 WebSocket 连接，实时接收消息
  connectWebSocket();

  // 自动创建结算单（不管有没有历史消息，后端会防重复）
  if (chatType.value === 'assessment') {
    setTimeout(async () => {
      try {
        const userInfo = uni.getStorageSync('userInfo') || {};
        const res = await autoCreateOrderCard({
          sessionId: sessionId.value,
          studentId: userInfo.studentId || fromUserId.value,
          orderName: assessmentTitle.value || (jobName.value + '-测评服务费'),
          orderPrice: assessmentPrice.value || '0',
          orderType: '测评咨询'
        });
        if (res.code === 200 && res.data) {
          pushOrderCardMsg(res.data);
        } else {
          console.error('自动创建结算单失败:', res);
        }
      } catch (err) {
        console.error('自动创建结算单异常:', err);
      }
    }, 800);
  } else if (chatType.value === 'job' && positionId.value) {
    try {
      const { getAssessmentList } = require('../../api/assessment.js');
      const evalRes = await getAssessmentList({ positionId: positionId.value, pageNum: 1, pageSize: 1 });
      if (evalRes.code === 200 && evalRes.rows && evalRes.rows.length > 0) {
        setTimeout(async () => {
          try {
            const userInfo = uni.getStorageSync('userInfo') || {};
            const firstEval = evalRes.rows[0];
            const res = await autoCreateOrderCard({
              sessionId: sessionId.value,
              studentId: userInfo.studentId || fromUserId.value,
              orderName: (firstEval.evaluationName || jobName.value) + '-测评服务费',
              orderPrice: firstEval.price || assessmentPrice.value || '0',
              orderType: '岗位测评'
            });
            if (res.code === 200 && res.data) {
              pushOrderCardMsg(res.data);
            }
          } catch (err) { console.error('岗位结算单异常:', err); }
        }, 800);
      } else {
        console.log('[Chat] 该岗位无关联测评，不发送结算单');
      }
    } catch (e) {
      console.error('[Chat] 查询关联测评失败:', e);
    }
  }
});

let orderTimer = null;
function startOrderTimer() {
  if (orderTimer) return;
  orderTimer = setInterval(() => {
    messages.value.forEach(m => {
      if (m.msgType === 'order_card' && !m.isPaid && m.countdown > 0) {
        m.countdown--;
      }
    });
  }, 1000);
}

onUnload(() => {
  if (wsSubId) {
    unsubscribe(wsSubId);
    wsSubId = null;
  }
  disconnectChat();
  if (orderTimer) clearInterval(orderTimer);
});

// ---- 加载历史消息 ----
async function loadHistory() {
  try {
    const res = await getChatHistory({ sessionId: sessionId.value, pageNum: 1, pageSize: 50 });
    if (res.rows) {
      messages.value = res.rows.slice().reverse().map(normalizeMsg);
      scrollToBottom();
      
      // 从历史消息中提取客服真实头像（取第一条客服消息的 senderAvatar）
      const firstWaiterMsg = res.rows.find(m => m.senderType === 2);
      if (firstWaiterMsg && firstWaiterMsg.senderAvatar) {
        const resolvedWaiterAvatar = resolveAvatarUrl(firstWaiterMsg.senderAvatar);
        if (resolvedWaiterAvatar) {
          waiterAvatar.value = resolvedWaiterAvatar;
        }
      }
      
      // 标记已读
      if (messages.value.length > 0) {
        const lastMsg = messages.value[messages.value.length - 1];
        if (lastMsg.id && !lastMsg.id.toString().startsWith('temp')) {
          markChatRead({ sessionId: sessionId.value, lastReadMsgId: lastMsg.id });
        }
      }
    }
  } catch (e) {
    console.error('[Chat] 加载历史消息失败:', e);
  } finally {
    loading.value = false;
  }

  // 异步加载用户真实头像（从学员表获取OSS永久URL）
  if (fromUserId.value) {
    try {
      const stuRes = await getStudent(fromUserId.value);
      if (stuRes.code === 200 && stuRes.data) {
        const stu = stuRes.data;
        // 学员表 avatar/avatarUrl 可能是 OSS URL 或 OSS ID
        const resolvedUrl = resolveAvatarUrl(stu.avatarUrl || stu.avatar);
        if (resolvedUrl) {
          userAvatarUrl.value = resolvedUrl;
        }
      }
    } catch (e) {
      console.warn('[Chat] 获取学员头像失败:', e);
    }
  }
}

// ---- WebSocket 实时消息 ----
function connectWebSocket() {
  const token = uni.getStorageSync('token');
  connectChat({
    token,
    onConnect: () => {
      console.log('[Chat] WebSocket 已连接，订阅会话消息');
      // 订阅当前会话的消息频道
      if (sessionId.value) {
        wsSubId = subscribe(`/topic/session/${sessionId.value}`, (data) => {
          console.log('[Chat] 收到 WebSocket 消息:', data);
          onWsMessage(data);
        });
      }
    },
    onDisconnect: () => {
      console.log('[Chat] WebSocket 已断开');
    }
  });
}

/**
 * 处理 WebSocket 推送的消息
 */
function onWsMessage(data) {
  if (!data) return;

  // 如果是数组（批量消息），逐条处理
  const msgList = Array.isArray(data) ? data : [data];

  msgList.forEach(msgData => {
    const normalized = normalizeMsg(msgData);

    // 去重：按 id 判断，同时按 msgNo 判断（解决乐观更新临时消息与服务端回传的重复问题）
    const existIdx = messages.value.findIndex(m =>
      (m.id && normalized.id && m.id === normalized.id) ||
      (m.msgNo && normalized.msgNo && m.msgNo === normalized.msgNo)
    );
    if (existIdx >= 0) {
      // 更新已有消息（临时消息被服务端确认，用真实数据替换）
      messages.value[existIdx] = { ...messages.value[existIdx], ...normalized };
    } else {
      // 追加新消息
      messages.value.push(normalized);
    }
  });

  scrollToBottom();

  // 标记已读
  const lastMsg = messages.value[messages.value.length - 1];
  if (lastMsg && lastMsg.id && !String(lastMsg.id).startsWith('temp')) {
    markChatRead({ sessionId: sessionId.value, lastReadMsgId: lastMsg.id });
  }
}

// ---- 规范化消息（后端字段 → 前端渲染字段）----
function normalizeMsg(msg) {
  let payload = null;
  if (msg.payload) {
    try { payload = typeof msg.payload === 'string' ? JSON.parse(msg.payload) : msg.payload; } catch (e) {}
  }
  return {
    id: msg.msgId,
    msgNo: msg.msgNo,
    senderType: msg.senderType,   // 1=用户  2=客服  3=系统
    senderName: msg.senderName,
    senderAvatar: msg.senderAvatar,
    msgType: msg.msgType || 'text',
    content: msg.content,
    fileUrl: msg.fileUrl,
    fileName: msg.fileName,
    fileSize: msg.fileSize,
    payload,
    sendTime: msg.sendTime,
    isPaid: payload && (payload.status === 'paid' || payload.status === '已支付' || payload.paid === true)
  };
}

// ---- 发送文本消息 ----
async function sendMessage() {
  const content = inputValue.value.trim();
  if (!content || !sessionId.value) return;

  const msgNo = generateMsgNo();
  const tempId = 'temp_' + Date.now();

  // 乐观展示
  messages.value.push({
    id: tempId, msgNo, senderType: 1, msgType: 'text',
    content, sendTime: new Date().toISOString(), payload: null
  });
  inputValue.value = '';
  scrollToBottom();

  try {
    // 优先通过 WebSocket 发送
    if (isSocketConnected()) {
      const sent = sendTextByWs(sessionId.value, content, 'text', msgNo, fromUserId.value);
      if (sent) return; // WebSocket 发送成功，消息会通过订阅回调回来替换临时消息
    }

    // WebSocket 不可用时，降级为 HTTP 发送
    await sendTextMessage({
      sessionId: sessionId.value,
      msgNo,
      content,
      msgType: 'text',
      senderId: fromUserId.value || undefined
    });
  } catch (e) {
    messages.value = messages.value.filter(m => m.id !== tempId);
    uni.showToast({ title: '发送失败，请重试', icon: 'none' });
  }
}

// ---- 发送图片 ----
async function chooseImage() {
  activePanel.value = 'none';
  uni.chooseImage({
    count: 1,
    success: async (res) => {
      const filePath = res.tempFilePaths[0];
      const tempId = 'temp_img_' + Date.now();
      messages.value.push({
        id: tempId, senderType: 1, msgType: 'image',
        fileUrl: filePath, sendTime: new Date().toISOString(), payload: null
      });
      scrollToBottom();
      try {
        const msgNo = 'MSG_' + Date.now() + '_' + Math.random().toString(36).slice(2, 6);
        await sendImageMessage({ sessionId: sessionId.value, msgNo, filePath, senderId: fromUserId.value });
      } catch (e) {
        messages.value = messages.value.filter(m => m.id !== tempId);
        uni.showToast({ title: '图片发送失败', icon: 'none' });
      }
    }
  });
}

// ---- 发送模拟订单卡片 ----
function sendMockOrderCard() {
  activePanel.value = 'none';
  messages.value.push({
    id: 'manual_order_' + Date.now(),
    msgNo: 'ORDER_' + Date.now(),
    senderType: 2,
    msgType: 'order_card',
    content: '为您推送测评费用结算单',
    payload: {
      id: 1,
      name: assessmentTitle.value || '测评费用',
      amount: assessmentPrice.value || '680.00'
    },
    sendTime: new Date().toISOString(),
    isPaid: false
  });
  scrollToBottom();
}

// ---- 推送结算单消息（公共方法，先去重再推送）----
function pushOrderCardMsg(card) {
  // 去重检查：如果已有同 orderCardId 的结算单消息，不再重复推送
  const hasOrderCard = messages.value.some(m =>
    m.msgType === 'order_card' && m.payload && m.payload.orderCardId === card.orderCardId
  );
  if (hasOrderCard) {
    console.log('[Chat] 已存在相同结算单消息，跳过推送');
    return;
  }

  messages.value.push({
    id: 'order_' + card.orderCardId,
    msgNo: 'ORDER_' + Date.now(),
    senderType: card.senderType || 3,
    msgType: 'order_card',
    content: '项目费用结算单',
    countdown: Math.floor((card.countdownSeconds || 1800)),
    payload: {
      orderCardId: card.orderCardId,
      id: card.orderCardId,
      name: card.orderName || assessmentTitle.value || jobName.value,
      // 同时写入amount和price，兼容后端payload字段
      amount: card.orderPrice || assessmentPrice.value || '0',
      price: card.orderPrice || assessmentPrice.value || '0',
      status: 'pending'
    },
    sendTime: new Date().toISOString(),
    isPaid: false
  });
  scrollToBottom();
  startOrderTimer();
}

// ---- 培训报名确认 ----
function confirmReg() {
  uni.showLoading({ title: '预约中...' });
  setTimeout(() => {
    uni.hideLoading();
    uni.showToast({ title: '预约成功', icon: 'success' });
  }, 1200);
}

// ---- 支付（客服发送 order_card 后用户点击）----
async function handlePay(msg) {
  if (msg.isPaid) return;
  
  const orderCardId = msg.payload ? (msg.payload.orderCardId || msg.payload.id) : null;
  const userInfo = uni.getStorageSync('userInfo') || {};
  console.log('🔥 开始支付流程');
  console.log('🔥 orderCardId:', orderCardId, '类型:', typeof orderCardId);
  console.log('🔥 fromUserId:', fromUserId.value, '类型:', typeof fromUserId.value);
  console.log('🔥 userInfo:', JSON.stringify(userInfo));
  console.log('🔥 msg.payload:', JSON.stringify(msg.payload));
  
  // 临时注释掉模拟支付逻辑，测试真实支付
  /*
  // 如果是模拟 ID (比如上面的 1)，我们直接走模拟逻辑
  if (orderCardId === 1) {
    uni.showLoading({ title: '发起支付...' });
    setTimeout(() => {
      msg.isPaid = true;
      uni.hideLoading();
      uni.showToast({ title: '支付成功', icon: 'success' });
      uni.setStorageSync('audit_paid', true);
      // 支付成功后自动跳转到培训/测评开始页 (参考初始版)
      setTimeout(() => {
        uni.navigateTo({ url: `/pages/assessment/training?title=${encodeURIComponent(assessmentTitle.value)}` });
      }, 1200);
    }, 1000);
    return;
  }
  */

  if (!orderCardId) {
    uni.showToast({ title: '无效的结算单', icon: 'none' });
    return;
  }

  try {
    uni.showLoading({ title: '创建支付订单...' });
    
    // 调用新的微信支付接口
    console.log('🔥 调用支付接口，参数:', { orderCardId, userId: fromUserId.value });
    const payRes = await createWxPayOrder(orderCardId, fromUserId.value);
    console.log('🔥 支付接口响应:', payRes);
    
    if (!(payRes.code === 200 || payRes.code === 0)) {
      uni.hideLoading();
      uni.showToast({ title: payRes.msg || '创建支付订单失败', icon: 'none' });
      console.log('🔥 支付接口调用失败:', payRes);
      return;
    }

    // 检查是否返回了微信支付参数
    if (payRes.data && payRes.data.wechatPayParams) {
      const wxPayParams = payRes.data.wechatPayParams;
      
      uni.hideLoading();
      uni.showLoading({ title: '发起微信支付...' });
      
      // 调用微信支付
      uni.requestPayment({
        provider: 'wxpay',
        timeStamp: wxPayParams.timeStamp,
        nonceStr: wxPayParams.nonceStr,
        package: wxPayParams.package,
        signType: wxPayParams.signType || 'RSA',
        paySign: wxPayParams.paySign,
        success: (res) => {
          uni.hideLoading();
          console.log('微信支付成功:', res);
          
          // 支付成功，更新UI
          msg.isPaid = true;
          uni.showToast({ title: '支付成功', icon: 'success' });
          
          // 标记支付状态到storage（供其他页面检测，按positionId区分）
          const paidKey = `audit_paid_${assessmentId.value || ''}`;
          uni.setStorageSync(paidKey, true);
          
          // 更新消息payload
          msg.payload = {
            ...(msg.payload || {}),
            orderCardId,
            orderId: payRes.data.orderId,
            orderNo: payRes.data.orderNo || '',
            status: 'paid'
          };
          
          uni.$emit('payment_done', {
            orderCardId,
            orderId: payRes.data.orderId,
            paid: true
          });
          
          // 支付成功后跳转
          if (chatType.value === 'assessment') {
            setTimeout(() => {
              uni.navigateTo({ url: `/pages/assessment/training?title=${encodeURIComponent(assessmentTitle.value)}` });
            }, 1200);
          }
        },
        fail: (err) => {
          uni.hideLoading();
          console.error('微信支付失败:', err);
          
          if (err.errMsg && err.errMsg.includes('cancel')) {
            uni.showToast({ title: '支付已取消', icon: 'none' });
          } else {
            uni.showToast({ title: '支付失败，请重试', icon: 'none' });
          }
        }
      });
    } else {
      // 没有微信支付参数，可能是免费订单或其他情况
      uni.hideLoading();
      
      if (payRes.data && payRes.data.success) {
        msg.isPaid = true;
        uni.showToast({ title: payRes.data.message || '支付成功', icon: 'success' });
      } else {
        uni.showToast({ title: '支付处理异常', icon: 'none' });
      }
    }
    
  } catch (e) {
    uni.hideLoading();
    console.error('支付失败:', e);
    uni.showToast({ title: '支付失败：' + (e.message || '网络错误'), icon: 'none' });
  }
}

// ---- 工具 ----
const chatBodyHeight = computed(() => {
  const navH = 100;
  const footerH = activePanel.value === 'none' ? 120 : 520;
  return `calc(100vh - ${navH}rpx - ${footerH}rpx - env(safe-area-inset-top) - env(safe-area-inset-bottom))`;
});

function scrollToBottom() {
  nextTick(() => { lastMessageId.value = ''; nextTick(() => { lastMessageId.value = 'bottom-anchor'; }); });
}

function goBack() { uni.navigateBack(); }

function toggleInputMode() {
  inputMode.value = inputMode.value === 'text' ? 'voice' : 'text';
  activePanel.value = 'none';
}

function togglePanel(panel) {
  activePanel.value = activePanel.value === panel ? 'none' : panel;
  if (activePanel.value !== 'none') inputMode.value = 'text';
  scrollToBottom();
}

function onInputFocus() { activePanel.value = 'none'; scrollToBottom(); }
function addEmoji(e) { inputValue.value += e; }

function previewImg(url) { uni.previewImage({ urls: [url], current: url }); }

function formatFileSize(size) {
  if (!size) return '';
  if (size < 1024) return size + 'B';
  if (size < 1024 * 1024) return (size / 1024).toFixed(1) + 'KB';
  return (size / 1024 / 1024).toFixed(1) + 'MB';
}

function formatTime(timeStr) {
  if (!timeStr) return '';
  const d = new Date(timeStr);
  if (isNaN(d)) return timeStr;
  const pad = n => n.toString().padStart(2, '0');
  return `${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`;
}

function shouldShowTime(msg, index) {
  if (index === 0) return true;
  const prev = messages.value[index - 1];
  if (!prev.sendTime || !msg.sendTime) return false;
  return (new Date(msg.sendTime) - new Date(prev.sendTime)) > 5 * 60 * 1000;
}

// 格式化金额显示
function formatAmount(amount) {
  if (!amount && amount !== 0) return '—';
  
  // 如果是字符串，尝试转换为数字
  const num = typeof amount === 'string' ? parseFloat(amount) : amount;
  
  if (isNaN(num)) return '—';
  
  // 保留两位小数，去掉不必要的0
  return num.toFixed(2).replace(/\.?0+$/, '');
}

const onVoiceStart = () => uni.showToast({ title: '录音中...', icon: 'none' });
const onVoiceEnd = () => uni.showToast({ title: '语音功能暂未开放', icon: 'none' });
</script>

<style lang="scss" scoped>
.container { width: 100%; height: 100vh; background-color: #F4F5F7; display: flex; flex-direction: column; overflow: hidden; }
/* 状态栏占位：高度由 JS 动态注入 */
.status-bar { background: #FFF; flex-shrink: 0; }

/* 导航栏 */
.nav-bar {
  height: 100rpx; background: #FFF; display: flex; align-items: center;
  padding: 0 30rpx; border-bottom: 1rpx solid #F0F0F0; flex-shrink: 0;
  .back-btn { width: 60rpx; display: flex; align-items: center;
    .back-arrow { font-size: 56rpx; color: #333; line-height: 1; margin-top: -6rpx; }
  }
  .nav-center { flex: 1; display: flex; align-items: center; justify-content: center; gap: 12rpx;
    .nav-title-text { font-size: 32rpx; font-weight: bold; color: #1A1A1A; }
    .online-dot { width: 14rpx; height: 14rpx; border-radius: 50%; background: #10B981; }
  }
  .nav-right { width: 60rpx; }
}

.chat-body { flex: 1; }
.message-list { padding: 24rpx 30rpx 160rpx; }

.tip-row { padding: 60rpx 0; text-align: center;
  .tip-text { font-size: 26rpx; color: #CCC; }
}

.time-stamp-row { display: flex; justify-content: center; margin: 20rpx 0 30rpx; }
.time-stamp { font-size: 22rpx; color: #BBB; background: rgba(0,0,0,0.05); padding: 4rpx 18rpx; border-radius: 8rpx; }

.msg-row {
  display: flex; margin-bottom: 44rpx;
  .avatar { width: 80rpx; height: 80rpx; border-radius: 50%; flex-shrink: 0; }
  &.left { .avatar { margin-right: 18rpx; } }
  &.right { justify-content: flex-end; .avatar { margin-left: 18rpx; } }
}

.msg-content { max-width: 520rpx; border-radius: 16rpx; padding: 22rpx 26rpx; font-size: 30rpx; line-height: 1.6; word-break: break-all; }
.text-msg { background: #FFF; color: #333; &.shadow { box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.04); } &.user-bubble { background: #FFB700; color: #FFF; } }

.img-msg { padding: 8rpx; background: #FFF; border-radius: 12rpx; box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.06);
  .chat-img { width: 360rpx; border-radius: 8rpx; display: block; }
}

.file-msg { display: flex; align-items: center; gap: 20rpx; background: #FFF; min-width: 300rpx;
  .file-icon-txt { font-size: 56rpx; flex-shrink: 0; }
  .file-info { flex: 1;
    .file-name { display: block; font-size: 28rpx; color: #333; margin-bottom: 6rpx; word-break: break-all; }
    .file-size { font-size: 22rpx; color: #999; }
  }
}

/* 订单卡片 */
.deposit-card {
  background: #FFF; width: 500rpx; border-radius: 20rpx; overflow: hidden; padding: 0; box-shadow: 0 4rpx 20rpx rgba(0,0,0,0.06);
  .deposit-header { padding: 28rpx 28rpx 16rpx; display: flex; justify-content: space-between; align-items: flex-start;
    .d-header-left { flex: 1;
      .d-title { font-size: 32rpx; font-weight: bold; color: #333; }
      .d-subtitle { font-size: 22rpx; color: #BBB; margin-top: 6rpx; display: block; }
    }
    .d-countdown {
      display: flex; gap: 4rpx; align-items: center; justify-content: flex-end;
      .c-time { color: #FF9500; font-size: 26rpx; font-weight: bold; }
      .c-txt { color: #999; font-size: 22rpx; }
    }
    .d-paid-tag { color: #52C41A; font-size: 24rpx; font-weight: bold; }
  }
  .deposit-body { padding: 8rpx 28rpx 24rpx;
    .d-row { margin-bottom: 10rpx; font-size: 26rpx; display: flex;
      .label { color: #AAA; width: 140rpx; } .val { color: #333; flex: 1; } .price { color: #FF3B30; font-size: 34rpx; font-weight: bold; }
    }
  }
  .deposit-action { margin: 0 28rpx 28rpx; height: 76rpx; font-size: 28rpx; background: #FFB700; color: #FFF; border-radius: 38rpx; display: flex; align-items: center; justify-content: center; font-weight: bold; &.paid { background: #EEE; color: #999; } }
}

/* 招聘初始卡片（静态展示用） */
.job-card-msg {
  background: #FFF; border-radius: 20rpx; width: 500rpx; padding: 30rpx; box-shadow: 0 4rpx 20rpx rgba(0,0,0,0.04);
  .card-header { display: flex; justify-content: space-between; margin-bottom: 20rpx;
    .ch-left { display: flex; align-items: center; gap: 10rpx;
      .card-title { font-weight: bold; font-size: 34rpx; }
      .urgent-tag { border: 1rpx solid #FF4D4F; color: #FF4D4F; font-size: 20rpx; padding: 2rpx 10rpx; border-radius: 6rpx; }
    }
    .card-salary { color: #1F6CFF; font-weight: bold; font-size: 32rpx; }
  }
  .card-tags { display: flex; gap: 12rpx; margin-bottom: 24rpx;
    .c-tag { background: #F5F7FA; color: #888; font-size: 22rpx; padding: 6rpx 16rpx; border-radius: 8rpx; }
  }
  .card-meta { display: flex; flex-direction: column; gap: 10rpx; margin-bottom: 24rpx;
    .m-item { display: flex; align-items: center; gap: 10rpx;
      .m-icon { width: 24rpx; height: 24rpx; opacity: 0.4; }
      text { font-size: 24rpx; color: #666; }
    }
  }
  .card-company { display: flex; align-items: center; border-top: 1rpx solid #F5F5F5; padding-top: 24rpx;
    .c-logo { width: 80rpx; height: 80rpx; border-radius: 12rpx; margin-right: 16rpx; }
    .c-info { flex: 1; display: flex; align-items: center; gap: 8rpx;
      .c-name { font-size: 28rpx; font-weight: bold; }
      .v-icon { width: 28rpx; height: 28rpx; }
    }
    .c-loc { font-size: 24rpx; color: #999; }
  }
}

/* 测评初始卡片 */
.assessment-card-msg {
  background: #FFF; width: 480rpx; padding: 24rpx; display: flex; box-shadow: 0 4rpx 20rpx rgba(0,0,0,0.04);
  border-radius: 16rpx;
  .card-left { width: 140rpx; height: 140rpx; margin-right: 20rpx;
    .a-cover { width: 100%; height: 100%; border-radius: 12rpx; }
  }
  .card-right { flex: 1; display: flex; flex-direction: column; justify-content: space-between;
    .a-title { font-weight: bold; font-size: 30rpx; color: #1A1A1A; }
    .a-tags { display: flex; gap: 10rpx; flex-wrap: wrap;
      .a-tag { font-size: 20rpx; color: #999; background: #F5F7FA; padding: 4rpx 12rpx; border-radius: 6rpx; }
    }
    .a-price { color: #FF4D4F; font-weight: bold; font-size: 32rpx; }
  }
}

/* 培训报名初始卡片 */
.training-reg-card {
  background: #FFF; width: 480rpx; padding: 30rpx; border-radius: 20rpx;
  .t-card-header { margin-bottom: 24rpx;
    .t-card-title { font-weight: bold; font-size: 32rpx; color: #1A1A1A; display: block; margin-bottom: 8rpx; }
    .t-card-subtitle { font-size: 24rpx; color: #999; }
  }
  .t-card-body { margin-bottom: 30rpx;
    .t-item { display: flex; font-size: 26rpx; margin-bottom: 10rpx;
      .t-label { color: #888; width: 140rpx; } .t-val { color: #333; }
    }
  }
  .t-card-footer {
    .reg-btn { width: 100%; height: 72rpx; line-height: 72rpx; background: #1F6CFF; color: #FFF; border-radius: 36rpx; font-size: 28rpx; font-weight: bold; &::after { border: none; } }
  }
}

/* API 推送的岗位卡片（客服消息循环中使用）*/
.api-job-card {
  background: #FFF; width: 460rpx; padding: 28rpx; border-radius: 16rpx;
  .jc-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 12rpx;
    .jc-title { font-size: 30rpx; font-weight: bold; color: #1A1A1A; flex: 1; }
    .jc-salary { font-size: 28rpx; color: #1F6CFF; font-weight: bold; }
  }
  .jc-city { font-size: 24rpx; color: #888; }
}

/* 系统消息 */
.system-msg { width: 100%; text-align: center; font-size: 24rpx; color: #BBB; padding: 8rpx 20rpx; background: rgba(0,0,0,0.04); border-radius: 8rpx; }

/* 底部输入栏 */
.footer-wrap { position: fixed; bottom: 0; left: 0; right: 0; background: #FFF; border-top: 1rpx solid #EEE; padding-bottom: env(safe-area-inset-bottom); z-index: 1001; }
.input-bar { height: 120rpx; display: flex; align-items: center; padding: 0 24rpx; gap: 20rpx;
  .bar-icon { width: 60rpx; height: 60rpx; transition: transform 0.2s; &.active { transform: scale(1.1); } }
  .center-area { flex: 1;
    .chat-input { background: #F7F8FA; height: 80rpx; border-radius: 12rpx; border: 1rpx solid #EEE; padding: 0 24rpx; font-size: 28rpx; }
    .voice-press-btn { height: 80rpx; background: #F7F8FA; border: 1rpx solid #DDD; border-radius: 12rpx; display: flex; align-items: center; justify-content: center; font-size: 28rpx; color: #666; &:active { background: #E0E0E0; } }
  }
}
.panel-section { height: 0; overflow: hidden; transition: height 0.3s; &.show { height: 400rpx; border-top: 1rpx solid #F2F2F2; } }
.emoji-panel { height: 100%; .emoji-scroll { height: 100%; } .emoji-grid { display: flex; flex-wrap: wrap; padding: 30rpx; gap: 20rpx; .emoji-item { font-size: 50rpx; width: 84rpx; text-align: center; } } }
.plus-panel { height: 100%; display: flex; padding: 40rpx 60rpx; gap: 80rpx;
  .panel-item { display: flex; flex-direction: column; align-items: center;
    .icon-box { width: 116rpx; height: 116rpx; background: #FFF; border: 1rpx solid #F0F0F0; border-radius: 28rpx; display: flex; align-items: center; justify-content: center; margin-bottom: 20rpx; box-shadow: 0 4rpx 10rpx rgba(0,0,0,0.03); image { width: 60rpx; height: 60rpx; } }
    text { font-size: 26rpx; color: #777; }
  }
}
</style>
