<template>
  <div class="h-full bg-white p-6 flex flex-col">
    <!-- 头部 -->
    <div class="flex justify-between items-center mb-8">
      <h2 class="text-xl font-medium">通话录音</h2>
      <!-- <el-icon class="cursor-pointer text-gray-400 hover:text-gray-600" @click="drawerVisible = false">
        <Close />
      </el-icon> -->
    </div>
    <!-- 音频播放器 -->
    <div class="bg-gray-50 rounded-lg p-6 mb-6">
      <div class="flex flex-col items-center gap-4 mb-4">
        <audio ref="audioPlayer" @timeupdate="updateTime"></audio>
        <el-button class="w-16 h-16 !rounded-full flex items-center justify-center"
          :type="isPlaying ? 'danger' : 'primary'" @click="togglePlay">
          <el-icon class="text-4xl">
            <component :is="isPlaying ? 'VideoPause' : 'VideoPlay'" />
          </el-icon>
        </el-button>
        <div class="flex items-center gap-2">
              <span class="text-sm text-gray-500">播放速度：</span>
              <el-radio-group v-model="playbackRate" size="small" @change="handlePlaybackRateChange">
                <el-radio-button :label="0.5">0.5x</el-radio-button>
                <el-radio-button :label="1.0">1.0x</el-radio-button>
                <el-radio-button :label="1.5">1.5x</el-radio-button>
                <el-radio-button :label="2.0">2.0x</el-radio-button>
              </el-radio-group>
            </div>
      </div>
      <!-- 进度条 -->
      <div class="mb-2">
        <el-slider v-model="progress" :max="100" @change="handleProgressChange" />
      </div>
      <!-- 时间显示 -->
      <div class="flex justify-between text-sm text-gray-500">
        <span>{{ formatTime(currentTime) }}</span>
        <span>{{ formatTime(duration) }}</span>
      </div>
    </div>
    <!-- 操作按钮 -->
    <div class="mb-6">
      <el-button type="primary" class="w-full !rounded-button whitespace-nowrap" @click="handleDownload">
        <el-icon class="mr-2">
          <Download />
        </el-icon>
        下载录音
      </el-button>
    </div>
    <!-- 转写内容 -->
    <div class="bg-white rounded-lg p-4 flex flex-col flex-grow overflow-hidden mb-6"
      v-if="transcriptionMessages.length">
      <h3 class="text-lg font-medium mb-4">语音转写内容</h3>
      <div class="text-gray-600 leading-relaxed overflow-y-auto flex-grow space-y-2">
        <div v-for="(message, index) in transcriptionMessages" :key="index" :class="[
            'p-3 transition-colors rounded-lg cursor-pointer group',
            message.direction === 1 ? 'bg-gradient-to-r from-gray-100 to-gray-200 hover:from-gray-200 hover:to-gray-300' : 'bg-gradient-to-r from-blue-50 to-blue-100 hover:from-blue-100 hover:to-blue-200'
          ]">
          <div class="flex justify-between items-center mb-2">
            <div class="flex items-center gap-2">
              <div class="text-xs text-gray-400">{{ message.timestamp }}</div>
              <div :class="[
                'px-2 py-1 rounded-full text-xs font-medium whitespace-nowrap',
                message.direction === 1 ? 'bg-gray-200 text-gray-700 border border-gray-300' : 'bg-blue-100 text-blue-600 border border-blue-200'
              ]">
                {{ message.direction === 1 ? '客服' : '客户' }}
              </div>
            </div>
            <el-button v-if="currentIndex !== index" class="!rounded-button opacity-0 group-hover:opacity-100 transition-opacity" size="small"
              type="text" @click.stop="playSegment(message.startTime, message.endTime, index)">
              <el-icon class="text-lg">
                <VideoPlay />
              </el-icon>
            </el-button>
            <el-icon v-else class="text-lg">
              <VideoPause />
            </el-icon>
          </div>
          <div class="text-gray-700">{{ message.page_content }}</div>
          <!-- <div class="text-xs text-gray-400 mt-1">置信度: {{ message.confidence }}%</div> -->
        </div>
      </div>
    </div>
    <!-- 关键词模块 -->
    <div class="mb-6" v-if="keywords.length">
      <h2 class="text-lg font-semibold mb-4">关键词</h2>
      <div class="flex flex-wrap gap-3">
        <div v-for="(keyword, index) in keywords" :key="index"
          class="relative inline-flex items-center px-3 py-1 rounded-full text-sm font-medium bg-blue-100 text-blue-800">
          {{ keyword.text }}
          <span v-if="keyword.count > 1"
            class="absolute -top-2 -right-2 flex items-center justify-center w-5 h-5 text-xs font-bold text-white bg-red-500 rounded-full">{{
            keyword.count }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, watch, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { Close, VideoPlay, VideoPause, Download } from '@element-plus/icons-vue';
import { flatten } from 'lodash';

import { getPageListData } from '@/api/main/system/system';
import { stripHtmlByRegex, formatMilliseconds } from '@/utils/tools';
import { exportFileWav } from '@/utils';

const drawerVisible = ref(false);
const deleteDialogVisible = ref(false);
const isPlaying = ref(false);
// const recordId = ref(null);
// const filePath = ref(null);
const audioPlayer = ref(null);
const playbackRate = ref(1.0);
const props = defineProps({
  recordId: {
    type: Number,
    default: null,
  },
  filePath: {
    type: String,
    default: null,
  },
});

watch(props, (newValue, oldValue) => {
  if (newValue) {
    console.log(newValue, 'newValue')
    if (newValue.recordId !== oldValue.recordId) {
      getDetail();
    }
    if (newValue.filePath !== oldValue.filePath) {
      loadRemoteAudio()
    }
    
   
  }
}, {
  deep: true,
});

const progress = ref(0);
const currentTime = ref(0);
const duration = ref(0); // 示例时长3分钟
const transcriptionMessages: any = ref([]);
const formatTime = (seconds = 0): string => {
  console.log(seconds, 'seconds');
  const minutes = Math.floor(seconds / 60);
  const remainingSeconds = Math.floor(seconds % 60);
  return `${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`;
};

const timer = ref(null);

const togglePlay = (isFragment = false) => {
  if (!isFragment) currentIndex.value = 0;
  isPlaying.value = !isPlaying.value;
  if (isPlaying.value) {
    play();
    // 模拟播放进度
    timer.value = setInterval(() => {
      if (progress.value >= 100 || (isFragment && currentTime.value >= endTime.value)) {
        pause();
        return;
      }

      // currentTime.value+= 1;

      progress.value = (currentTime.value / duration.value) * 100;
      // currentTime.value = (progress.value / 100) * duration.value;
    }, 1000);
  } else {
    pause();
  }
};

const handlePlaybackRateChange = (value: number) => {
  playbackRate.value = value;
  
  audioPlayer.value.playbackRate = value;
};


const handleProgressChange = (value: number) => {
  console.log(value, duration.value, 'handleProgressChange-value');
  currentTime.value = (value / 100) * duration.value;
  audioPlayer.value.currentTime = currentTime.value;
  pause();
  
  togglePlay();
};

const handleDownload = () => {
  ElMessage.success('录音文件下载中...');
  exportFileWav(props.filePath);
};
let keywords = reactive([]);

const getDetail = () => {
  // props.recordId = 526;
  if (!props.recordId) return;
  getPageListData(`/call/translate/${props.recordId}`).then(({ data }) => {
    console.log(data, 'res')
    if (data.translate) {
      const translate = JSON.parse(data.translate);
      transcriptionMessages.value = translate.map((msg: any) => {

        const msgInfo: any = {
          direction: msg.Number.toString().length > 4 ? 2 : 1,
          page_content: msg.Speech || '',
          startTime: 0,
          endTime: 0,
          timestamp: '',
        };
        // console.log(msg.Time, 'msgInfo');
        if (msg.Time) {
          const times = JSON.parse(msg.Time);
          if (times?.length) {
            const timeArray = flatten(times);
            const time = timeArray?.[0];
            if (time) {
              msgInfo.timestamp = formatMilliseconds(time);
              msgInfo.startTime = timeArray[0];
              msgInfo.endTime = timeArray[timeArray.length - 1];
            }
          }
        }

        return msgInfo;

      })

    }

    if (data.translateJson) {
      keywords = JSON.parse(data.translateJson);

    }
  })
}

const startTime = ref(0);
const endTime = ref(0);
// const duration = ref(0);
// const isPlaying = ref(false);
// const currentTime = ref(0);
const currentIndex = ref(-1);
const playSegment = (sTime: number, eTime: number, index) => {
  currentIndex.value = index;
  if (isPlaying.value) isPlaying.value = false
  if (timer.value) clearInterval(timer.value);
  progress.value = (sTime / 1000 / duration.value) * 100;
  currentTime.value = sTime / 1000;
  audioPlayer.value.currentTime = currentTime.value;
  endTime.value = eTime / 1000;

  togglePlay(true);

  // isPlaying.value = true;
  // playVideoSegment();
};

// // 播放指定区间
// const playVideoSegment = () => {
//   if (!audioPlayer.src) return;

//   audioPlayer.currentTime = startTime.value;
//   audioPlayer.play();
//   isPlaying.value = true;

//   // 模拟播放到指定片段结束
//   const timer = setInterval(() => {
//     if (currentTime.value >= endTime.value || !isPlaying.value) {
//       clearInterval(timer);
//       isPlaying.value = false;
//       return;
//     }
//     progress.value = (currentTime.value / duration.value) * 100;
//     currentTime.value += 1;
//   }, 1000);

//   // 设置区间结束监听
//   const checkEnd = () => {
//     if (audioPlayer.currentTime >= endTime.value) {
//       pause();
//       audioPlayer.currentTime = startTime.value; // 回到起点
//     } else if (isPlaying.value) {
//       requestAnimationFrame(checkEnd);
//     }
//   };
//   requestAnimationFrame(checkEnd);
// };

// 暂停播放
const pause = () => {
  console.log(audioPlayer, 'audioPlayer');
  // 清除定时器
  clearInterval(timer.value);
  audioPlayer.value.pause();
  isPlaying.value = false;
  currentIndex.value = -1;
  
}
const play = () => {
  audioPlayer.value.play();
  // isPlaying.value = true;
}

// 更新当前时间
const updateTime = () => {
  console.log('audioPlayer.value.currentTime', audioPlayer.value.currentTime)
  currentTime.value = audioPlayer.value.currentTime;
}

const loadRemoteAudio = async () => {
  if (!props.filePath) return

  try {
    // 创建音频对象
    const audio = audioPlayer.value
    audio.src = props.filePath //'http://1.194.161.64:9000/files/luyin/20250305/1011/69010260-1ec7-402a-b588-18e30f4f579a.wav'// 

    // 等待元数据加载
    await new Promise((resolve, reject) => {
      audio.onloadedmetadata = () => {
        duration.value = audio.duration || 0
        console.log(duration.value, 'duration.value')
        startTime.value = 0
        endTime.value = audio.duration
        resolve(1)
      }

      audio.onerror = (e) => {
        reject(new Error('音频加载失败'))
      }

      // 设置超时处理
      setTimeout(() => {
        reject(new Error('音频加载超时'))
      }, 10000)
    })
  } catch (err) {
    console.log(err)
  } finally {
  }
}

onMounted(() => {
  // props.recordId = props.recordId;
  console.log('recordId', props.recordId, props.recordId, `props.filePath=>${props.filePath}`);
  // props.filePath = 'http://1.194.161.64:9000/files/luyin/20250228/1002/eb445cb0-8fbb-44dc-af52-d1e11b778d53.wav';
  if (props.filePath) {
    loadRemoteAudio();
  } 
  getDetail();
});
</script>
<style scoped>
.el-drawer__body {
  padding: 0;
  overflow: hidden;
}

/* 隐藏滚动条但保留滚动功能 */
.overflow-y-auto::-webkit-scrollbar {
  display: none;
}

.overflow-y-auto {
  -ms-overflow-style: none;
  scrollbar-width: none;
}
</style>