<template>
  <view class="container">
    <!-- 聊天记录区域 -->
    <scroll-view 
      class="chat-container" 
      scroll-y 
      :scroll-top="scrollTop"
      :scroll-with-animation="true"
      @scroll="onScroll"
      :style="{ 
        height: `calc(100vh - ${inputHeight}px)`,
        marginTop: '0'
      }"
    >
      <view class="chat-list">
        <view 
          v-for="(message, index) in chatMessages" 
          :key="index" 
          class="message-item"
          :class="{ 'message-ai': message.sender === 'ai', 'message-user': message.sender === 'user' }"
        >
          <!-- AI消息 -->
          <template v-if="message.sender === 'ai'">
            <view class="avatar-container">
              <image class="avatar" src="/static/icons/ai.png" mode="aspectFill"></image>
            </view>
            <view class="message-content">
              <view class="message-bubble ai-bubble" :class="{'typing': message.isTyping, 'welcome': message.isWelcome || index === 0}">
                <view v-if="message.isTyping" class="typing-indicator">
                  <view class="typing-dot"></view>
                  <view class="typing-dot"></view>
                  <view class="typing-dot"></view>
                </view>
                <text v-else class="message-text" :class="{'highlight': containsKeywords(message.content)}">{{ message.content }}</text>
              </view>
              <text class="message-time">{{ message.time }}</text>
            </view>
          </template>
          
          <!-- 用户消息 -->
          <template v-else>
            <view class="message-content user-content">
              <text class="message-time">{{ message.time }}</text>
              <view class="message-bubble user-bubble">
                <text class="message-text">{{ message.content }}</text>
              </view>
            </view>
            <view class="avatar-container">
              <image class="avatar" src="/static/images/user-avatar.svg" mode="aspectFill"></image>
            </view>
          </template>
        </view>
      </view>
    </scroll-view>
    
    <!-- 底部输入区 -->
    <view class="input-container" :style="{ paddingBottom: `${isIOS ? safeAreaBottom : 20}rpx` }">
      <!-- 问题建议区 -->
      <scroll-view 
        v-if="chatMessages.length <= 3 && !inputMessage" 
        class="suggested-questions" 
        scroll-x
      >
        <view 
          v-for="(question, index) in suggestedQuestions" 
          :key="index"
          class="question-chip"
          @click="useQuestion(question)"
        >
          <text>{{ question }}</text>
        </view>
      </scroll-view>
      
      <view class="input-wrapper">
        <textarea 
          class="message-input" 
          v-model="inputMessage" 
          placeholder="请输入您的问题..." 
          maxlength="300"
          @confirm="submitQuestion"
          confirm-type="send"
          @focus="onInputFocus"
          :disabled="isProcessing"
          auto-height
          :maxlength="300"
          :style="{ maxHeight: '120rpx' }"
        />
              <view 
        class="send-button" 
        :class="{ 'disabled': !inputMessage.trim() || isProcessing }"
        @click="submitQuestion"
        hover-class="button-hover"
      >
        <image 
          class="send-icon-image" 
          :src="inputMessage.trim() && !isProcessing ? '/static/icons/chat.png' : '/static/icons/chat_off.png'" 
          mode="aspectFit"
        ></image>
      </view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      inputMessage: '',
      chatMessages: [
        {
          sender: 'ai',
          content: '您好！我是农小禹，您的智能农业助手🌱 我可以帮您解答农业种植、病虫害防治、农产品管理等方面的问题。有什么可以帮助您的吗？',
          time: this.getFormattedTime(new Date(Date.now() - 3600000)), // 1小时前
          timestamp: Date.now() - 3600000,
          isWelcome: true
        },
        {
          sender: 'user',
          content: '南方现在适合种什么蔬菜？',
          time: this.getFormattedTime(new Date(Date.now() - 60000)), // 1分钟前
          timestamp: Date.now() - 60000
        },
        {
          sender: 'ai',
          content: '您可以考虑种植以下蔬菜：\n\n1. 空心菜：耐热耐湿，生长快速\n2. 丝瓜：适应性强，产量高\n3. 茄子：耐热性好，病虫害较少\n4. 辣椒：喜温喜光，南方气候适宜\n5. 秋葵：抗病性强，营养价值高\n\n记得注意排水和通风，南方雨水多，做好防涝措施。建议早晚浇水，避开中午高温时段。',
          time: this.getFormattedTime(new Date()),
          timestamp: Date.now()
        }
      ],
      scrollTop: 0,
      inputHeight: 120, // 单位px
      scrollTimer: null,
      isProcessing: false, // 是否正在处理请求
      suggestedQuestions: [
        '水稻插秧后如何管理？',
        '果树夏季修剪技巧？',
        '如何防治蔬菜常见病虫害？',
        '农药使用注意事项？',
        '有机肥和化肥怎么搭配使用？'
      ],
      statusBarHeight: 20, // 默认值，会在mounted中获取真实值
      safeAreaBottom: 34, // 默认值，会在mounted中获取真实值
      isIOS: false, // 是否是iOS设备
      lastMessageDate: '' // 上一条消息的日期，用于判断是否显示日期分割线
    }
  },
  // 设置页面标题
  onNavigationBarButtonTap(e) {
    console.log("导航栏按钮点击：", e);
  },
  mounted() {
    // 获取系统信息
    const systemInfo = uni.getSystemInfoSync();
    this.statusBarHeight = systemInfo.statusBarHeight || 20;
    this.isIOS = systemInfo.platform === 'ios';
    this.safeAreaBottom = systemInfo.safeAreaInsets ? (systemInfo.safeAreaInsets.bottom || 0) : 0;
    
    // 初始化消息
    this.initMessages();
    
    // 滚动到底部
    this.$nextTick(() => {
      this.scrollToBottom();
    });
  },
  methods: {
    onInputFocus() {
      // 输入框获取焦点时，确保滚动到底部
      this.$nextTick(() => {
        this.scrollToBottom();
      });
    },
    scrollToBottom() {
      // 使用nextTick确保DOM更新后再滚动
      this.$nextTick(() => {
        const query = uni.createSelectorQuery().in(this);
        query.select('.chat-list').boundingClientRect(data => {
          if (data) {
            this.scrollTop = data.height + 1000; // 加上足够大的值确保滚动到底部
            
            // 在H5环境下，还可以使用以下方法确保滚动到底部
            if (this.isH5) {
              setTimeout(() => {
                const scrollEl = document.querySelector('.chat-container');
                if (scrollEl) {
                  scrollEl.scrollTop = scrollEl.scrollHeight;
                }
              }, 100);
            }
          }
        }).exec();
      });
    },
    onScroll(e) {
      // 可以添加滚动事件处理
    },
    getCurrentTime() {
      return this.getFormattedTime(new Date());
    },
    getFormattedTime(date) {
      const hours = date.getHours().toString().padStart(2, '0');
      const minutes = date.getMinutes().toString().padStart(2, '0');
      return `${hours}:${minutes}`;
    },
    submitQuestion() {
      if (!this.inputMessage.trim() || this.isProcessing) return;
      
      this.isProcessing = true;
      
      // 添加用户消息
      this.chatMessages.push({
        sender: 'user',
        content: this.inputMessage,
        time: this.getCurrentTime()
      });
      
      const userQuestion = this.inputMessage;
      this.inputMessage = '';
      
      // 滚动到底部
      this.scrollToBottom();
      
      // 先添加一个"正在输入"的消息
      this.chatMessages.push({
        sender: 'ai',
        content: '正在思考...',
        time: this.getCurrentTime(),
        isTyping: true
      });
      
      // 模拟AI回复（实际项目中替换为API调用）
      setTimeout(() => {
        // 删除"正在输入"消息
        this.chatMessages.pop();
        
        // 模拟回复
        let aiResponse = "感谢您的提问！作为您的农技助理，我很高兴能帮助您解决农业相关问题。您询问的内容我已收到，我们团队正在研究适合的解决方案。";
        
        if (userQuestion.includes('水稻')) {
          aiResponse = "水稻种植需要注意水肥管理和病虫害防治。目前南方地区水稻插秧时间已到，建议您选择抗病性强的品种，如'中优84'。插秧后7天开始浅水促根，分蘖期保持3-5cm水层。";
        } else if (userQuestion.includes('蔬菜')) {
          aiResponse = "夏季蔬菜种植需注意遮阳和水分管理。建议种植耐热品种如空心菜、苋菜、茄子等。可以采用遮阳网减少强光照射，早晚浇水避开高温时段。";
        } else if (userQuestion.includes('果树')) {
          aiResponse = "果树现在应注意夏季修剪和病虫害防治。柑橘类果树可以进行夏季修剪，去除徒长枝和内膛枝。同时注意柑橘黄龙病和炭疽病的预防，建议定期喷施药剂保护。";
        }
        
        this.chatMessages.push({
          sender: 'ai',
          content: aiResponse,
          time: this.getCurrentTime()
        });
        
        this.scrollToBottom();
        this.isProcessing = false;
      }, 2000);
    },
    useQuestion(question) {
      this.inputMessage = question;
    },
    containsKeywords(text) {
      const keywords = ['水稻', '小麦', '玉米', '病虫害', '农药', '化肥', '有机肥', '种植技术'];
      return keywords.some(keyword => text.includes(keyword));
    },
    formatMessage(text) {
      // 将文本中的换行符转换为<br>标签
      return text.replace(/\n/g, '<br>');
    },
    initMessages() {
      // 确保消息有时间戳
      this.chatMessages.forEach(msg => {
        if (!msg.timestamp) {
          msg.timestamp = new Date().getTime();
        }
      });
      
      // 按时间排序
      this.chatMessages.sort((a, b) => a.timestamp - b.timestamp);
    },
    showDateSeparator(index) {
      // 判断是否需要显示日期分割线
      if (index === 0) return true;
      
      const currentMsg = this.chatMessages[index];
      const prevMsg = this.chatMessages[index - 1];
      
      // 如果两条消息相隔超过30分钟，或者是不同日期，显示日期分割线
      return this.isDifferentDay(currentMsg.timestamp, prevMsg.timestamp) || 
             (currentMsg.timestamp - prevMsg.timestamp > 30 * 60 * 1000);
    },
    isDifferentDay(timestamp1, timestamp2) {
      const date1 = new Date(timestamp1);
      const date2 = new Date(timestamp2);
      
      return date1.getDate() !== date2.getDate() || 
             date1.getMonth() !== date2.getMonth() || 
             date1.getFullYear() !== date2.getFullYear();
    },
    formatDateSeparator(timestamp) {
      const now = new Date();
      const msgDate = new Date(timestamp);
      
      // 今天
      if (this.isSameDay(msgDate, now)) {
        return '今天 ' + this.getFormattedTime(msgDate);
      }
      
      // 昨天
      const yesterday = new Date(now);
      yesterday.setDate(now.getDate() - 1);
      if (this.isSameDay(msgDate, yesterday)) {
        return '昨天 ' + this.getFormattedTime(msgDate);
      }
      
      // 一周内
      const oneWeekAgo = new Date(now);
      oneWeekAgo.setDate(now.getDate() - 7);
      if (msgDate >= oneWeekAgo) {
        const weekdays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
        return weekdays[msgDate.getDay()] + ' ' + this.getFormattedTime(msgDate);
      }
      
      // 其他日期
      return msgDate.getFullYear() + '年' + (msgDate.getMonth() + 1) + '月' + msgDate.getDate() + '日 ' + this.getFormattedTime(msgDate);
    },
    isSameDay(date1, date2) {
      return date1.getDate() === date2.getDate() && 
             date1.getMonth() === date2.getMonth() && 
             date1.getFullYear() === date2.getFullYear();
    }
  }
}
</script>

<style>
/* 容器样式 */
.container {
  position: relative;
  min-height: 100vh;
  background-color: #f5f5f5;
  overflow: hidden; /* 防止内容溢出 */
}

/* 聊天容器 */
.chat-container {
  padding: 20rpx 30rpx;
  box-sizing: border-box;
  background-color: #f8f8f8;
  background-image: url('/static/images/chat-bg-pattern.png');
  background-size: 300rpx;
  background-blend-mode: overlay;
  background-opacity: 0.05;
  -webkit-overflow-scrolling: touch; /* 增强iOS滚动体验 */
}

.chat-list {
  padding-bottom: 30rpx;
}

/* 消息项 */
.message-item {
  display: flex;
  margin-bottom: 30rpx;
  position: relative;
}

.message-ai {
  justify-content: flex-start;
}

.message-user {
  justify-content: flex-end;
}

/* 头像 */
.avatar-container {
  width: 90rpx;
  height: 90rpx;
  flex-shrink: 0;
}

.avatar {
  width: 90rpx;
  height: 90rpx;
  border-radius: 50%;
  background-color: #e0e0e0;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
  object-fit: cover;
}

/* 消息内容 */
.message-content {
  max-width: 70%;
  margin: 0 20rpx;
  display: flex;
  flex-direction: column;
}

.user-content {
  align-items: flex-end;
}

.message-bubble {
  padding: 24rpx;
  border-radius: 24rpx;
  position: relative;
  margin-bottom: 10rpx;
  word-wrap: break-word;
  min-width: 80rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  max-width: 100%;
}

.ai-bubble {
  background-color: #e8f5e9;
  border-top-left-radius: 4rpx;
}

.user-bubble {
  background-color: #e3f2fd;
  border-top-right-radius: 4rpx;
}

.message-text {
  font-size: 28rpx;
  color: #333;
  line-height: 1.5;
  word-break: break-all;
}

.message-time {
  font-size: 22rpx;
  color: #999;
}

/* 输入区域 */
.input-container {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  padding: 20rpx 30rpx;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  z-index: 10;
}

.input-wrapper {
  display: flex;
  align-items: flex-end;
}

.message-input {
  flex: 1;
  min-height: 70rpx;
  max-height: 120rpx;
  border-radius: 35rpx;
  background-color: #f5f5f5;
  padding: 15rpx 30rpx;
  font-size: 28rpx;
  color: #333;
  border: 1rpx solid #e0e0e0;
  line-height: 1.4;
}

.send-button {
  margin-left: 16rpx;
  width: 76rpx;
  height: 76rpx;
  border-radius: 50%;
  background-color: transparent;
  background-image: none;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s ease;
  position: relative;
  align-self: center;
}

.send-button.disabled {
  background-color: transparent;
  background-image: none;
  opacity: 1;
}

.button-hover {
  transform: scale(0.95);
}

@keyframes pulse {
  0% { transform: scale(1); }
  50% { transform: scale(0.95); }
  100% { transform: scale(1); }
}

.send-button:active:not(.disabled) {
  animation: pulse 0.3s ease-in-out;
}

/* 删除或注释掉之前的样式 */
.send-icon {
  display: none;
}

.send-icon:before {
  display: none;
}

.send-icon-text {
  display: none;
}

/* 推荐问题区域 */
.suggested-questions {
  display: flex;
  white-space: nowrap;
  margin-bottom: 15rpx;
  padding: 5rpx 0;
}

.question-chip {
  display: inline-block;
  padding: 12rpx 20rpx;
  margin-right: 15rpx;
  background-color: #e8f5e9;
  color: #4CAF50;
  font-size: 24rpx;
  border-radius: 30rpx;
  border: 1rpx solid #a5d6a7;
}

/* AI正在输入的样式 */
.message-bubble.ai-bubble.typing {
  background-color: #f0f0f0;
}

.typing-indicator {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 40rpx;
  padding: 0 20rpx;
}

.typing-dot {
  width: 10rpx;
  height: 10rpx;
  margin: 0 5rpx;
  background-color: #4CAF50;
  border-radius: 50%;
  opacity: 0.5;
  animation: typingAnimation 1.4s infinite both;
}

.typing-dot:nth-child(2) {
  animation-delay: 0.2s;
}

.typing-dot:nth-child(3) {
  animation-delay: 0.4s;
}

@keyframes typingAnimation {
  0% { opacity: 0.3; transform: translateY(0); }
  50% { opacity: 1; transform: translateY(-5rpx); }
  100% { opacity: 0.3; transform: translateY(0); }
}

/* 关键词高亮 */
.message-text.highlight {
  color: #2E7D32;
  font-weight: 500;
}

/* 欢迎消息特殊样式 */
.welcome {
  background-color: #e3f2fd !important;
  border-left: none !important;
  border-radius: 24rpx !important;
}

/* 日期分割线样式 */
.date-separator {
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 20rpx 0;
}

.date-separator text {
  background-color: rgba(0, 0, 0, 0.1);
  color: #666;
  font-size: 24rpx;
  padding: 4rpx 20rpx;
  border-radius: 20rpx;
}

/* 纸飞机图标 */
.plane-svg {
  display: none;
}

.send-icon-image {
  width: 76rpx;
  height: 76rpx;
}

.material-icon {
  font-family: 'Material Icons';
  font-weight: normal;
  font-style: normal;
  font-size: 48rpx;
  line-height: 1;
  letter-spacing: normal;
  text-transform: none;
  display: inline-block;
  white-space: nowrap;
  word-wrap: normal;
  direction: ltr;
  -webkit-font-smoothing: antialiased;
  color: white;
}

/* 删除不需要的导航栏样式 */
.custom-navbar {
  display: none;
}

.navbar-bg, .navbar-content, .navbar-left, .navbar-title, .navbar-right, .back-icon, .arrow-left {
  display: none;
}
</style>
