<template>
  <view class="content" :style="{paddingBottom: paddingBottom}">
    <view class="item" v-for="(item, index) in json" :class="item.classText.join(' ')" @click="click(item, 0)">
      <p v-if="item.type === 'h5-text'" :style="item.style">{{ item.content }}</p>
      <img :ref="'myImage' + index" @load="handleImageLoad(index, item)" v-if="item.type === 'h5-image'" :src="item.url"/>
	  <view class="image-child" v-if="item.type === 'h5-image'"></view>
	  
      <div v-if="item.type === 'h5-sep'" :class="item.classText.join(' ')"></div>
      <div class="countdown2-box"
           :style="{ backgroundImage: item.bgImage && item.bgImage !== '#' ? `url(${item.bgImage})` : '' }"
           v-if="item.type==='h5-countdown'"
      >
        距结束<span id="days" :style="{background: item.mainColor}">{{ item.days }}</span>天
        <span id="hours" :style="{background: item.mainColor}">{{ item.hours }}</span>时
        <span id="minutes" :style="{background: item.mainColor}">{{ item.minutes }}</span>分
        <span id="seconds" :style="{background: item.mainColor}">{{ item.seconds }}</span>秒
      </div>
      <div :class="item.classText.join(' ')" v-if="item.type==='h5-chat'">
        <div class="chat-container">
          <div class="chat-messages">
            <!-- Messages -->
            <div v-for="(message, index) in item.messages" :key="index"
                 :class="['message-wrapper', message.sender === 'user' ? 'user-message' : 'agent-message']"
            >
			
              <div class="avatar">
                <img :src="message.sender === 'user' ? userAvatar : getAgentAvatar(item)" alt="Avatar"/>
              </div>
              <div class="message-content">
                <div v-if="message.text" class="message-text" v-html="message.text"></div>
                <!-- Options buttons -->
                <div v-if="message.options && message.options.length > 0 && !message.click" class="options-container">
                  <button
                      v-for="(option, optIndex) in message.options"
                      :key="optIndex"
                      :style="{color: item.style.btnTextColor,backgroundColor: item.style.buttonColor}"
                      class="option-button"
                      :class="{ 'selected': isOptionSelected(message.id, option) }"
                      @click="selectOption(message, option)"
                      v-once
                  >
                    {{ option.text }}
                  </button>
                </div>
              </div>
            </div>
			<img v-if="item.showButton" :ref="'addButton' + index" @load="handleImageLoad2(index, item)" :style="item.addWxButtonStyle" :src="item.addWxButtonImg" @click.stop="click(item, 1)" style="width: 100%;" />
          </div>
        </div>
      </div>
    </view>
  </view>
</template>
<script>
// 引入Clipboard
import {getTemplateByNo, getTemplateById, baiduClickCallback, callback, youkuClickCallback, iqiyiClickCallback, dyClickCallback} from '../../api/api.js'
import agentAvatar from '../../static/customer.png'
import userAvatar from '../../static/profile.png'

export default {
  data() {
    return {
      userAvatar: userAvatar, // Placeholder for user avatar
      agentAvatar: agentAvatar,
      images: [],
      params: {},
      site: {},
      data: {},
      json: [],
      vid: '',
      click_id: '',
      aid: '',
      id: null,
      no: null,
      type: 0,
      show: false,
      name: '',
	  url: "",
      tel: '',
      accountId: '',
      ip: '',
      paddingBottom: 0,
      order_plan_id: '',
      creative_id: '',
      impress_id: '',
      sign: '',
      isProcessing: false // 防止按钮重复点击
    }
  },
  mounted() {
    window.vueInstance = this  // 将 Vue 实例暴露到全局
  },
  onLoad(option) {
	this.url = window.location.href;
    this.params = option;
    this.no = this.params.no;
    this.id = this.params.tid;
    if ((this.id == null || this.id == '' || this.id == undefined) && (this.no == null || this.no == '' || this.no == undefined)) {
      uni.showToast({
        icon: 'none',
        title: '推广链接错误'
      })
      return
    }
    this.accountId = this.params.accountId;
    this.type = this.params.type;
    this.no = this.params.no;
    if (this.id) {
      getTemplateById(this.id).then(e => {
        this.data = e.data;
        this.site = e.site;
        this.type = e.site.type;
        this.json = JSON.parse(e.data.json)
      }).finally(() => {
        this.setData();
      })
    } else if (this.no) {
      getTemplateByNo(this.no).then(e => {
        this.data = e.data;
        this.json = JSON.parse(e.data.json)
      }).finally(() => {
        this.setData();
      })
    }
  },
  beforeDestroy() {
    this.json.filter(e => e.type === 'h5-countdown').forEach(item => {
      if (item.intervalId) {
        clearInterval(item.intervalId)
      }
    })
  },
  methods: {
    setData() {
      // 百度
      if (this.type == 0) {
        this.vid = this.params.bd_vid;
      }
      // 优酷
      if (this.type == 1) {
        this.vid = this.params.bd_vid;
        this.aid = this.params.aid;
        this.click_id = this.params.click_id;
        this.ip = this.params.ip;
      }
      // 爱奇艺
      if (this.type == 2) {
        this.order_plan_id = this.params.order_plan_id;
        this.creative_id = this.params.creative_id;
        this.impress_id = this.params.impress_id;
        this.sign = this.params.sign;
      }
      // 巨量（抖音）
      if (this.type == 3) {
        this.click_id = this.params.clickid;
        this.creative_id = this.params.creativeid;
        this.vid = this.params.adid;
      }
	  console.info(this.params.adid)
      this.loadCountdownData();
      this.loadChatMessage();
    },
    getChatMsgIdMax() {
      let h5ChatItem = this.json.filter(e => e.type === 'h5-chat')[0]
      let maxId = Math.max(0, ...h5ChatItem.messages.map(e => e.id))
      return maxId + 1
    },
    // 聊天组件选择了选项
    async selectOption(message, option) {
      try{
        if(this.isProcessing){
          return;
        }
        this.isProcessing = true;
        let h5ChatItem = this.json.filter(e => e.type === 'h5-chat')[0]
        // 防止重复点击
        if(message.handle){
          return;
        } else {
          message.handle = true;
        }
        if (!h5ChatItem) {
          console.error("未找到类型为 'h5-chat' 的元素");
          return;
        }
        // 如果有答案就直接用户消息和客服消息
        let nextMsg = h5ChatItem.agentMsg.shift();
		message.click = true;
        h5ChatItem.messages.push({
          id: this.getChatMsgIdMax(),
          sender: 'user',
          text: option.text,
          options: []
        })
        await this.delay(1000);

        if (option.answer) {
          h5ChatItem.messages.push({
            id: this.getChatMsgIdMax(),
            sender: 'agent',
            text: option.answer,
            options: []
          })
        }
        await this.delay(1000);
        // 不管有没有 answer，都添加 nextMsg（如果存在）
        if (nextMsg) {
          h5ChatItem.messages.push(nextMsg);
          if(nextMsg.options){
            return;
          }
        }

        while (h5ChatItem.agentMsg.length > 0) {
          nextMsg = h5ChatItem.agentMsg.shift();
          if (nextMsg && (!nextMsg.options || nextMsg.options.length === 0)) {
            await this.delay(500 + (Math.random() * 1000) % 500);
            h5ChatItem.messages.push(nextMsg);
          } else {
            //重新放回去
            if(nextMsg){
              h5ChatItem.agentMsg.unshift(nextMsg);
            }
            break;
          }
        }
        if (h5ChatItem.agentMsg.length === 0) {
          await this.delay(200);
		  if(h5ChatItem.addWxFun){
			  //显示加微按钮
			 h5ChatItem.showButton = true; 
		  }
          h5ChatItem.messages.push({
            id: this.getChatMsgIdMax(),
            sender: 'agent',
            text: h5ChatItem.lastMsg.map(e => {
                if(e.type == 0) return e.text;
                if(e.type == 1) return "<span style='color: red'>"+ e.text +"</span>";
              }).join(""),
            options: []
          });
		  
        }
      }catch (err) {
        console.error(err);
      }finally {
        this.isProcessing = false;
      }
    },
    // 辅助函数：延迟
    delay(ms) {
      return new Promise(resolve => setTimeout(resolve, ms));
    },
    // 加载计时器数据
    loadCountdownData() {
      let countdownItems = this.json.filter(e => e.type === 'h5-countdown')
      countdownItems.forEach(item => {
        // 为每个item启动一个定时器
        this.startCountdown(item)
      })
    },
    // 加载聊天组件的消息
    async loadChatMessage() {
      let h5ChatItem = this.json.filter(e => e.type === 'h5-chat')[0]
	  if(!h5ChatItem) return;
      h5ChatItem.messages = []

      // 先输出所有的欢迎信息，欢迎信息为没有options的数据，以及后面一条数据
      let isOutputWelcome = 0;

      while (h5ChatItem.agentMsg.length > 0) {
        let msg = h5ChatItem.agentMsg.shift()

        if (!msg.options || msg.options.length === 0) {
          isOutputWelcome = 1
          await this.delay(1000)
          h5ChatItem.messages.push(msg)

        } else {
          if ((isOutputWelcome === 1) || (isOutputWelcome === 0)) {
            isOutputWelcome = 2
            await this.delay(2000)
              h5ChatItem.messages.push(msg)
            break;
          }
        }
      }

      if (h5ChatItem.agentMsg.length === 0) {
        await this.delay(1000);
        h5ChatItem.messages.push({
          id: this.getChatMsgIdMax(),
          sender: 'agent',
          text: "好的，已经为您分配专业老师。<span style='color:red'>【点击下方按钮】</span>添加老师，获取免费上课链接。!",
          options: []
        });
      }

    },
    startCountdown(item) {
      if (!item.active) {
        return
      }

      let intervalId = setInterval(() => {
        let timeLeft

        if (item.countdownMode == '1') {
          // 模式1：now() - endDateTime 的时间差
          timeLeft = this.calculateTimePassed(item)
        } else if (item.countdownMode == '2') {
          // 模式2：timeDisplay 分钟数倒计时
          timeLeft = this.calculateTimeLeftFromDisplay(item)
        }
        // 不再有 total <= 0 的判断, 因为模式1是不断增加的
        item.days = timeLeft.days
        item.hours = timeLeft.hours
        item.minutes = timeLeft.minutes
        item.seconds = timeLeft.seconds

      }, 1000)
      item.intervalId = intervalId // 存储 intervalId
    },

    calculateTimePassed(item) {
      // 如果已经结束，直接返回
      if (item.isFinished) {
        return {
          days: 0,
          hours: 0,
          minutes: 0,
          seconds: 0
        }
      }

      let endTime = new Date(item.endDateTime)
      let now = new Date()
      let diff = endTime.getTime() - now.getTime()   // 毫秒差, end - now

      if (diff <= 0) {
        // 如果 endDateTime 比当前时间晚, 则显示 0
        clearInterval(item.intervalId)
        item.intervalId = null
        item.isFinished = true
        return {
          days: 0,
          hours: 0,
          minutes: 0,
          seconds: 0
        }
      }

      return this.millisecondsToTimeObject(diff)
    },

    calculateTimeLeftFromDisplay(item) {
      if (!item.startTime) {
        item.startTime = Date.now() // 记录开始时间
      }
      let totalSeconds = item.timeDisplay * 60 // timeDisplay 是分钟数
      let passedSeconds = Math.floor((Date.now() - item.startTime) / 1000)
      let timeLeft = totalSeconds - passedSeconds

      if (timeLeft <= 0) {
        clearInterval(item.intervalId)
        item.intervalId = null//清除id
        return {
          days: 0,
          hours: 0,
          minutes: 0,
          seconds: 0
        }
      }

      return this.secondsToTimeObject(timeLeft)
    },

    millisecondsToTimeObject(milliseconds) {
      let totalSeconds = Math.floor(milliseconds / 1000)
      return this.secondsToTimeObject(totalSeconds)
    },
    secondsToTimeObject(totalSeconds) {
      let days = Math.floor(totalSeconds / (3600 * 24))
      let hours = Math.floor((totalSeconds % (3600 * 24)) / 3600)
      let minutes = Math.floor((totalSeconds % 3600) / 60)
      let seconds = Math.floor(totalSeconds % 60)
      return {
        days: days,
        hours: hours,
        minutes: minutes,
        seconds: seconds
      }
    },
    getAgentAvatar(item) {
      console.log(item.style.avatar)
      if (item.style.avatar) {
        return item.style.avatar
      }
      return this.agentAvatar
    },
    isOptionSelected(messageId, option) {
      let messages = this.json.find(t => t.type === 'h5-chat').messages
      const message = messages.find(m => m.id === messageId)
      return message && message.userSelection && message.userSelection.id === option.id
    },
    handleImageLoad(index, item) {
      if (item.classText.indexOf("footer") != -1) {
        const imgElement = this.$refs["myImage" + index];
        // 获取真实高度（包含以下两种方式）
        const naturalHeight = imgElement[0].naturalHeight; // 原始高度
        const clientHeight = imgElement[0].clientHeight;   // 渲染高度
        this.paddingBottom = clientHeight + "px";
      }
    },
    handleImageLoad2(index, item) {
		const imgElement = this.$refs["addButton" + index][0]; // 获取图片 DOM 元素
		
		// 1. 获取图片原始宽高
		const naturalWidth = imgElement.naturalWidth;
		const naturalHeight = imgElement.naturalHeight;
		
		// 2. 获取容器尺寸（假设容器是图片的父元素）
		const container = imgElement.parentElement;
		const containerWidth = container.clientWidth;
		const containerHeight = container.clientHeight;
		
		// 3. 计算缩放后的宽高（保持比例）
		const imageAspectRatio = naturalWidth / naturalHeight; // 原始宽高比
		const containerAspectRatio = containerWidth / containerHeight; // 容器宽高比
		
		let targetWidth, targetHeight;
		
		// 根据容器宽高比决定以哪一边为基准缩放
		if (containerAspectRatio > imageAspectRatio) {
		  // 容器更宽，以高度为基准
		  targetHeight = containerHeight;
		  targetWidth = targetHeight * imageAspectRatio;
		} else {
		  // 容器更高，以宽度为基准
		  targetWidth = containerWidth;
		  targetHeight = targetWidth / imageAspectRatio;
		}
		
		// 4. 应用缩放后的尺寸
		imgElement.style.width = `${targetWidth - 16}px`;
		imgElement.style.height = `${targetHeight}px`;
    },
    confirm() {
      this.show = false
    },
    clickToWx(workUrl) {
		if(this.site && this.site.workUrl != null && this.site.workUrl != undefined && this.site.workUrl != ''){
			workUrl = this.site.workUrl;
		}
      // 百度
      if (this.type == 0) {
        let data = {
          id: this.id,
          url: window.location.href,
          vid: this.vid,
          clickType: 79,
        };
        baiduClickCallback(data).then(e => {
          window.location.href = workUrl + "?customer_channel=" + this.vid;
        })
      }
      // 优酷
      if (this.type == 1) {
        let data = {
          id: this.id,
          url: window.location.href,
          vid: this.vid,
          aid: this.aid,
          clickId: this.click_id,
          ip: this.ip,
		  clickType: "wechat"
        };
        youkuClickCallback(data).then(e => {
          window.location.href = workUrl + "?customer_channel=" + this.vid;
        })
      }
      // 爱奇艺
      if (this.type == 2) {
        if (this.id) {
          let data = {
            url: window.location.href,
            id: this.id,
            planId: this.order_plan_id,
            creativeId: this.creative_id,
            vid: this.impress_id,
            sign: this.sign,
            clickType: "200"
          };
          iqiyiClickCallback(data).then(e => {
            window.location.href = workUrl + "?customer_channel=" + this.impress_id;
          })
        } else {
          let data = {
            accountId: this.accountId,
            url: window.location.href,
            no: this.no,
            planId: this.order_plan_id,
            creativeId: this.creative_id,
            vid: this.impress_id,
            sign: this.sign,
            clickType: "200"
          };
          dyClickCallback(data).then(e => {
            window.location.href = workUrl + "?customer_channel=" + this.impress_id;
          })
        }
      }
      // 爱奇艺
      if (this.type == 3) {
		let data = {
		  url: window.location.href,
		  id: this.id,
		  clickId: this.click_id,
		  creativeId: this.creative_id,
		  vid:this.vid
		};
		dyClickCallback(data).then(e => {
		  window.location.href = workUrl + "?customer_channel=" + this.vid;
		})
      }
	  
	  
	  if (this.type == 99) {
		  window.location.href = workUrl + "?customer_channel=" + '{"siteId":'+this.id+'}';
		}

    },
    click(item, type) {
		if(type == 0){
		console.info(item)
			if (!item.addWxFun || item.type === "h5-chat") {
			  return
			}
			this.clickToWx(item.workUrl)
		}else{
			this.clickToWx(item.workUrl)
		}
    }
  }
}
</script>

<style lang="scss" scoped>
.chat-container {
  width: 100%;
  display: flex;
  flex-direction: column;
  background-color: #f8f8f8;
  font-family: Arial, sans-serif;
  min-height: 500px;
  box-sizing: border-box;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 12px;
  display: flex;
  flex-direction: column;
  width: 100%;
  box-sizing: border-box;
  font-weight: bold;
}

.message-wrapper {
  display: flex;
  margin-bottom: 16px;
  max-width: 80%;
  width: auto;
  align-items: flex-start;
}
.message-wrapper:last-child{
	margin-bottom: 0 !important;
}

.agent-message {
  align-self: flex-start;
}

.user-message {
  align-self: flex-end;
  flex-direction: row-reverse;
  justify-content: flex-end;
  width: auto;
}

.avatar {
  font-size: 14px;
  display: flex;
  padding-right: 5px;
  padding-left: 0;
  margin-bottom: 0;
  flex-shrink: 0;
  width: 36px;
}

.avatar img {
  width: 32px;
  height: 32px;
  border-radius: 50%;
}

.message-content {
  display: flex;
  flex-direction: column;
  min-width: 0;
  width: auto;
}
.message-content>.message-text,.message-content .option-button{
	font-size: 17px;
}

.message-text {
  padding: 10px 12px;
  border-radius: 18px;
  font-size: 14px;
  line-height: 1.4;
  word-break: break-word;
  display: inline-block;
  max-width: 100%;
}

.agent-message .message-text {
  background-color: white;
  color: #333;
  border-top-left-radius: 4px;
}

.user-message .message-text {
  background-color: #4a90e2;
  color: white;
  border-top-right-radius: 4px;
}

.options-container {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-top: 8px;
}

.option-button {
  background-color: #4a90e2;
  color: white;
  border: none;
  border-radius: 18px;
  padding: 1px 12px;
  font-size: 14px;
  cursor: pointer;
  transition: background-color 0.2s;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
  max-width: 100%;
}

.option-button:hover {
  background-color: #045dba;
}

.option-button.selected {
  background-color: #2a70c2;
}

/* Media queries for responsive design */
@media screen and (max-width: 768px) {
  .chat-messages {
    padding: 10px;
  }

  .message-wrapper {
    max-width: 90%;
  }
}

@media screen and (max-width: 480px) {
  .chat-messages {
    padding: 8px;
  }

  .message-wrapper {
    max-width: 95%;
  }

  .message-text {
    padding: 8px 10px;
    font-size: 13px;
  }

  .avatar img {
    width: 28px;
    height: 28px;
  }

  .options-container {
    gap: 6px;
  }

  .option-button {
    padding: 1px 10px;
    font-size: 13px;
  }
}

/* Fix for iOS Safari viewport height issues */
@supports (-webkit-touch-callout: none) {
  .chat-container {
    min-height: -webkit-fill-available;
  }
}

/* Fix for potential input and button styling on mobile */
input, button {
  -webkit-appearance: none;
  -moz-appearance: none;
  appearance: none;
}

/* Ensure touch targets are big enough */
.option-button {
  min-height: 32px;
}
.item {
	position: relative;
  display: flex;
  flex-direction: column;
  flex: 1;
  margin: 0;
  width: 100%;
	.image-child{
		position: absolute;
		top: 0%;
		left: 0;
		width: 100%;
		height: 100%;
		background-color: transparent; /* 设置为透明 */
		z-index: 1000;
	}
  img {
    width: 100%;
  }

  p {
    white-space: pre-line;
  }
}

.footer {
  position: fixed;
  bottom: 0;
  left: 0;
  z-index: 44444;
}

.countdown2-box {
  background: url('#') no-repeat center;
  background-size: 100%;
  width: 100%;
  height: 54px;
  line-height: 54px;
  color: #515A6E;
  font-size: 14px;
  text-align: center;
}

.countdown2-box span {
  display: inline-block;
  color: #fff;
  width: 22px;
  line-height: 20px;
  text-align: center;
  height: 20px;
  border-radius: 3px;
  margin: 7px;
  background: #FF5A29;
}
</style>
