<template>
  <div class="hik-container">
    <div class="tree-section">
      <div class="tree-header">
        <h3>设备列表</h3>
        <button @click="refreshTree">刷新</button>
      </div>
      <div class="tree-container">
        <ul v-if="treeData.length > 0">
          <li
            v-for="device in treeData"
            :key="device.id"
            :class="{ 'has-children': device.channels.length > 0, 'expanded': device.expanded }"
            @click="toggleDevice(device)"
          >
            <span class="device-name">{{ device.name }}</span>
            <span class="device-ip">{{ device.ip }}:{{ device.port }}</span>
            <ul v-if="device.expanded && device.channels.length > 0">
              <li
                v-for="channel in device.channels"
                :key="channel.id"
                :class="{ 'active': activeChannel && activeChannel.id === channel.id }"
                @click.stop="selectChannel(device, channel)"
              >
                <span class="channel-name">通道 {{ channel.id }}</span>
                <div class="channel-actions">
                  <button
                    title="实时预览"
                    :disabled="isPlaying && activeChannel && activeChannel.id === channel.id"
                    @click.stop="startLive(device, channel)"
                  >
                    <i class="icon-live" />
                  </button>
                  <button
                    title="录像回放"
                    :disabled="isPlaying && activeChannel && activeChannel.id === channel.id"
                    @click.stop="showPlayback(device, channel)"
                  >
                    <i class="icon-playback" />
                  </button>
                </div>
              </li>
            </ul>
          </li>
        </ul>
        <div
          v-else
          class="empty-tree"
        >
          <p>暂无设备数据</p>
        </div>
      </div>
    </div>

    <div class="player-section">
      <div
        id="videoContainer"
        style="height: 80%;width: 100%;overflow: hidden;z-index: 0;background-color: #343434;border:solid 1px #FFCC00"
      >
        <div
          v-if="!playerInitialized"
          class="init-placeholder"
        >
          <div class="spinner" />
          <p>播放器初始化中...</p>
        </div>
      </div>

      <div
        v-if="playbackType === 'playback'"
        style="height: 10%;width: 100%;"
      >
        <div class="time-controls">
          <div class="time-input">
            <label>开始时间</label>
            <!--            <input type="datetime-local" v-model="playbackConfig.startTime">-->
            <el-date-picker
              v-model="playbackConfig.startTime"
              type="datetime"
              placeholder="选择开始时间"
              @focus="timeFocus"
              @blur="timeBlur"
            />
          </div>
          <div class="time-input">
            <label>结束时间</label>
            <!--            <input type="datetime-local" v-model="playbackConfig.endTime">-->
            <el-date-picker
              v-model="playbackConfig.endTime"
              type="datetime"
              placeholder="选择结束时间"
              @focus="timeFocus"
              @blur="timeBlur"
            />
          </div>
          <button
            style="border: none;border-radius: 20px;padding: 10px;background-color: #3498db;cursor: pointer"
            :disabled="!activeChannel"
            @click="startPlayback"
          >开始回放
          </button>
        </div>
      </div>

      <div class="player-controls">
        <button
          v-if="playbackType === 'playback'"
          :disabled="!isPlaying || isPaused"
          @click="pausePlay"
        >
          <i class="icon-pause" /> 暂停
        </button>
        <button
          v-if="playbackType === 'playback'"
          :disabled="!isPlaying || !isPaused"
          @click="resumePlay"
        >
          <i class="icon-play" /> 恢复
        </button>
        <button
          :disabled="!isPlaying"
          @click="stopPlay"
        >
          <i class="icon-stop" /> 停止
        </button>
        <button
          :disabled="!isPlaying"
          @click="capturePicture"
        >
          <i class="icon-capture" /> 抓图
        </button>
        <button
          :disabled="!isPlaying"
          :title="isPlaying ? `当前抓图路径: ${nowPath}` : null"
          @click="editPath"
        >
          修改抓图路径
        </button>
        <button
          class="fullscreen-btn"
          @click="toggleFullscreen"
        >
          <i class="icon-fullscreen" />
        </button>
      </div>
    </div>

    <div class="status-section">
      <div class="status-card">
        <h3>播放状态</h3>
        <p :class="statusClass">{{ playerStatus }}</p>
        <div
          v-if="activeChannel"
          class="channel-info"
        >
          <p><strong>设备:</strong> {{ activeDevice.name }}</p>
          <p><strong>通道:</strong> {{ activeChannel.id }}</p>
          <p><strong>模式:</strong> {{ playbackType === 'live' ? '实时预览' : '录像回放' }}</p>
        </div>
      </div>
      <div
        v-if="screenshotData"
        class="screenshot-preview"
      >

        <button @click="screenshotData = null">关闭预览</button>
      </div>
      <p style="color: red">*如无法查看预览或回放，请下载插件</p>
      <p><a href="http://118.253.180.18:8000/HCWebSDKPluginsUserSetup.exe">立即下载</a></p>
    </div>

  </div>
</template>

<script>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import dayjs from 'dayjs'
import { ElMessage } from 'element-plus'

export default {
  name: 'HikvisionPlayer',
  setup() {
    // 播放器状态
    const playerInitialized = ref(false)
    const playerStatus = ref('未初始化')
    const statusClass = ref('status-offline')
    const isPlaying = ref(false)
    const isPaused = ref(false)
    const playbackType = ref('live') // 'live' 或 'playback'
    const nowPath = ref()

    // 设备树数据
    const treeData = ref([
      {
        id: '1',
        name: '设备1',
        ip: '192.168.110.199',
        port: 80,
        username: 'admin',
        password: 'qwe123456',
        expanded: false,
        channels: [
          { id: 1, name: '通道1' },
        ]
      },
      {
        id: '2',
        name: '设备2',
        ip: '192.168.110.4',
        port: 80,
        username: 'admin',
        password: '78585Lc@',
        expanded: false,
        channels: [
          { id: 1, name: '通道1' }
        ]
      },
      {
        id: '3',
        name: '设备3',
        ip: '192.168.110.65',
        port: 80,
        username: 'admin',
        password: '123456qwe',
        expanded: false,
        channels: [
          { id: 1, name: '通道1' }
        ]
      }
    ])

    // 当前选中的设备和通道
    const activeDevice = ref(null)
    const activeChannel = ref(null)

    // 回放配置
    const playbackConfig = ref({
      startTime: new Date(Date.now() - 3600000).toISOString().slice(0, 16),
      endTime: new Date().toISOString().slice(0, 16)
    })

    // 其他数据
    const screenshotData = ref(null)
    let WebVideoCtrl = null
    // const videoContainer = ref(null);

    // 初始化播放器
    const initPlayer = () => {
      if (!window.WebVideoCtrl) {
        playerStatus.value = 'SDK未加载'
        return
      }
      WebVideoCtrl = window.WebVideoCtrl
      // 初始化播放器参数
      const initParams = {
        bWndFull: true,
        // iPackageType: 1,
        iWndowType: 1,
        // iTopHeight: 100,
        cbInitPluginComplete: async() => {
          playerInitialized.value = true
          playerStatus.value = '播放器初始化完成'
          statusClass.value = 'status-ready'
          // 将播放器插入容器
          WebVideoCtrl.I_InsertOBJECTPlugin('videoContainer').then(() => {
            WebVideoCtrl.I_CheckPluginVersion().then((bflag) => {
              if (bflag) {
                showPluginDownloadDialog()
              }
            })
          })
        }
      }

      playerStatus.value = '正在初始化播放器...'
      WebVideoCtrl.I_InitPlugin(initParams)
    }

    function showPluginDownloadDialog() {
      // 创建遮罩层
      const overlay = document.createElement('div')
      overlay.style.cssText = `
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 9999;
  `

      // 创建提示框
      const dialog = document.createElement('div')
      dialog.style.cssText = `
    background-color: white;
    padding: 24px;
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    max-width: 400px;
    width: 90%;
    text-align: center;
  `

      // 添加提示内容
      dialog.innerHTML = `
    <h3 style="color: #333; margin-bottom: 16px;">视频插件未安装或需要升级</h3>
    <p style="color: #666; margin-bottom: 24px;">
      为了正常查看监控画面，请下载并安装最新版视频插件。
    </p>
    <a href="http://118.253.180.18:8000/HCWebSDKPluginsUserSetup.exe" target="_blank" style="
      display: inline-block;
      background-color: #007BFF;
      color: white;
      padding: 10px 20px;
      border-radius: 4px;
      text-decoration: none;
      font-weight: 500;
    ">
      下载视频插件
    </a>
    <button style="
      margin-top: 16px;
      background-color: transparent;
      border: none;
      color: #666;
      text-decoration: underline;
      cursor: pointer;
    " onclick="document.body.removeChild(this.parentNode.parentNode)">
      稍后安装
    </button>
  `

      // 将提示框添加到遮罩层，再添加到页面
      overlay.appendChild(dialog)
      document.body.appendChild(overlay)
    }

    const timeFocus = () => {
      WebVideoCtrl.I_HidPlugin()
    }

    const timeBlur = () => {
      WebVideoCtrl.I_ShowPlugin()
    }

    // 设备登录

    const loggedInDevices = new Set()
    const loginDevice = async(device) => {
      if (!WebVideoCtrl) return
      if (loggedInDevices.has(device.ip)) {
        return true
      }
      playerStatus.value = '正在登录设备...'
      statusClass.value = 'status-loading'

      try {
        await new Promise((resolve, reject) => {
          WebVideoCtrl.I_Login(device.ip, 1, device.port, device.username, device.password, {
            success: () => {
              playerStatus.value = '设备登录成功'
              statusClass.value = 'status-online'
              loggedInDevices.add(device.ip)
              resolve()
            },
            error: () => {
              playerStatus.value = '设备登录失败'
              statusClass.value = 'status-error'
              reject(new Error('登录失败'))
            }
          })
        })

        WebVideoCtrl.I_GetLocalCfg().then(cof => {
          nowPath.value = cof.capturePath
        })

        return true
      } catch (error) {
        console.error('设备登录失败:', error)
        return false
      }
    }

    // 设备登出
    const logoutDevice = async(device) => {
      if (!WebVideoCtrl) return
      WebVideoCtrl.I_Logout(device.ip)
    }

    // 开始实时预览
    const startLive = async(device, channel) => {
      if (!WebVideoCtrl || (isPlaying.value && activeChannel.value && activeChannel.value.id === channel.id)) return

      // 停止当前播放
      if (isPlaying.value) {
        await stopPlay()
      }

      // 如果切换设备，需要重新登录
      // if (!activeDevice.value || activeDevice.value.id !== device.id) {
      //   // if (activeDevice.value) {
      //   //   await logoutDevice(activeDevice.value);
      //   // }
      //   const loginSuccess = await loginDevice(device);
      //   if (!loginSuccess) return;
      // }
      const loginSuccess = await loginDevice(device)
      if (!loginSuccess) return

      activeDevice.value = device
      activeChannel.value = channel
      playbackType.value = 'live'

      playerStatus.value = '正在启动实时预览...'
      isPlaying.value = true

      try {
        await new Promise((resolve, reject) => {
          WebVideoCtrl.I_StartRealPlay(device.ip, {
            iChannelID: channel.id,
            iStreamType: 1, // 主码流
            success: () => {
              playerStatus.value = '实时预览中...'
              statusClass.value = 'status-playing'
              resolve()
            },
            error: () => {
              isPlaying.value = false
              playerStatus.value = '启动预览失败'
              statusClass.value = 'status-error'
              reject(new Error('启动预览失败'))
            }
          })
        })
      } catch (error) {
        console.error('实时预览失败:', error)
        isPlaying.value = false
      }
    }

    // 显示回放界面
    const showPlayback = (device, channel) => {
      activeDevice.value = device
      activeChannel.value = channel
      playbackType.value = 'playback'

      // 设置默认回放时间范围
      playbackConfig.value = {
        startTime: new Date(Date.now() - 3600000).toISOString().slice(0, 16),
        endTime: new Date().toISOString().slice(0, 16)
      }
    }

    // 开始录像回放
    const startPlayback = async() => {
      if (!WebVideoCtrl || !activeDevice.value || !activeChannel.value) return
      // 停止当前播放
      if (isPlaying.value) {
        await stopPlay()
      }

      // 登录设备
      const loginSuccess = await loginDevice(activeDevice.value)
      if (!loginSuccess) return

      playerStatus.value = '正在启动回放...'
      isPlaying.value = true

      var date1 = new Date(playbackConfig.value.startTime)
      var date2 = new Date(playbackConfig.value.endTime)
      if (date2.getTime() <= date1.getTime()) {
        ElMessage({
          message: '结束时间不能早于开始时间！',
          type: 'warning',
        })
        isPlaying.value = false
        playerStatus.value = '启动回放失败'
        statusClass.value = 'status-error'
        return
      }
      try {
        await new Promise((resolve, reject) => {
          WebVideoCtrl.I_StartPlayback(activeDevice.value.ip, {
            iChannelID: activeChannel.value.id,
            szStartTime: dayjs(date1).format('YYYY-MM-DD HH:mm:ss'),
            szEndTime: dayjs(date2).format('YYYY-MM-DD HH:mm:ss'),
            success: () => {
              playerStatus.value = '回放中...'
              statusClass.value = 'status-playing'
              resolve()
            },
            error: (err) => {
              isPlaying.value = false
              playerStatus.value = '启动回放失败'
              statusClass.value = 'status-error'
              console.log('错误', err)
              reject(new Error('启动回放失败'))
            }
          })
        })
      } catch (error) {
        console.error('录像回放失败:', error)
        isPlaying.value = false
      }
    }

    // 暂停播放
    const pausePlay = () => {
      if (!WebVideoCtrl || !isPlaying.value) return
      WebVideoCtrl.I_Pause()
      isPaused.value = true
      playerStatus.value = playbackType.value === 'live'
        ? '预览已暂停'
        : '回放已暂停'
    }

    // 恢复播放
    const resumePlay = () => {
      if (!WebVideoCtrl || !isPlaying.value || !isPaused.value) return

      WebVideoCtrl.I_Resume()
      isPaused.value = false
      playerStatus.value = playbackType.value === 'live'
        ? '实时预览中...'
        : '回放中...'
    }

    // 停止播放
    const stopPlay = async() => {
      if (!WebVideoCtrl || !isPlaying.value) return

      try {
        await new Promise((resolve) => {
          WebVideoCtrl.I_Stop({
            success: () => {
              isPlaying.value = false
              isPaused.value = false
              playerStatus.value = '播放已停止'
              statusClass.value = 'status-ready'
              // loggedInDevices.delete(activeDevice.value.ip)
              resolve()
            }
          })
        })
      } catch (error) {
        console.error('停止播放失败:', error)
      }
    }

    // 修改抓图路径
    const editPath = () => {
      if (!WebVideoCtrl || !isPlaying.value) return
      WebVideoCtrl.I_GetLocalCfg().then(conf => {
        WebVideoCtrl.I_OpenFileDlg(0).then(path => {
          conf.capturePath = path
          conf.playbackPicPath = path
          WebVideoCtrl.I_SetLocalCfg(conf)

          WebVideoCtrl.I_GetLocalCfg().then(cof => {
            nowPath.value = cof.capturePath
          })
        }).catch(() => {
        })
      })
    }

    // 抓图
    const capturePicture = async() => {
      const picName = dayjs().format('YYYYMMDD_HHmmss') + '.jpg'
      WebVideoCtrl.I_CapturePic(picName)
    }

    // 切换设备展开状态
    const toggleDevice = (device) => {
      device.expanded = !device.expanded
    }

    // 选择通道
    const selectChannel = (device, channel) => {
      activeDevice.value = device
      activeChannel.value = channel
    }

    // 刷新设备树
    const refreshTree = () => {
      // 这里可以添加从服务器获取设备列表的逻辑
      console.log('刷新设备树')
    }

    // 全屏切换
    const toggleFullscreen = () => {
      if (!WebVideoCtrl) return
      WebVideoCtrl.I_FullScreen(true)
    }

    // 组件挂载时初始化SDK
    onMounted(() => {
      // 动态加载SDK
      if (!window.WebVideoCtrl) {
        const script = document.createElement('script')
        script.src = '../public/static/webVideoCtrl.js'
        document.head.appendChild(script)
        script.onload = () => {
          initPlayer()
        }
        script.onerror = () => {
          playerStatus.value = 'SDK加载失败'
          statusClass.value = 'status-error'
        }
      } else {
        initPlayer()
      }
    })

    // 组件卸载前清理资源
    onBeforeUnmount(() => {
      if (WebVideoCtrl) {
        if (isPlaying.value) {
          WebVideoCtrl.I_Stop()
        }
        if (activeDevice.value) {
          WebVideoCtrl.I_Logout(activeDevice.value.ip)
        }
        WebVideoCtrl.I_DestroyPlugin()
      }
    })

    return {
      // 响应式数据
      playerInitialized,
      playerStatus,
      statusClass,
      treeData,
      activeDevice,
      activeChannel,
      playbackType,
      playbackConfig,
      isPlaying,
      isPaused,
      screenshotData,
      nowPath,

      // 方法
      toggleDevice,
      selectChannel,
      refreshTree,
      startLive,
      showPlayback,
      startPlayback,
      pausePlay,
      resumePlay,
      stopPlay,
      capturePicture,
      toggleFullscreen,
      timeFocus,
      timeBlur,
      editPath
    }
  }
}
</script>

<style scoped>
.hik-container {
  display: flex;
  height: 83vh;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  background: #f5f7fa;
  overflow: hidden; /* 防止出现滚动条 */
}

.tree-section {
  width: 300px;
  background: #2c3e50;
  color: white;
  display: flex;
  flex-direction: column;
  border-right: 1px solid #34495e;
}

.tree-header {
  padding: 15px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #34495e;
}

.tree-header h3 {
  margin: 0;
  font-size: 16px;
}

.tree-header button {
  background: #3498db;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 5px 10px;
  cursor: pointer;
  font-size: 12px;
}

.tree-header button:hover {
  background: #2980b9;
}

.tree-container {
  flex: 1;
  overflow-y: auto;
  padding: 10px 0;
}

.tree-container ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

.tree-container li {
  padding: 8px 15px;
  cursor: pointer;
  transition: background 0.2s;
}

.tree-container li:hover {
  background: rgba(255, 255, 255, 0.1);
}

.tree-container li.active {
  background: rgba(52, 152, 219, 0.3);
}

.device-name {
  font-weight: 500;
  display: block;
}

.device-ip {
  font-size: 12px;
  color: #95a5a6;
  display: block;
  margin-top: 3px;
}

.has-children::before {
  content: "▶";
  font-size: 10px;
  margin-right: 5px;
  transition: transform 0.2s;
}

.has-children.expanded::before {
  transform: rotate(90deg);
}

.channel-name {
  display: flex;
  align-items: center;
  padding-left: 20px;
}

.channel-actions {
  display: flex;
  margin-left: auto;
}

.channel-actions button {
  background: none;
  border: none;
  color: #95a5a6;
  cursor: pointer;
  margin-left: 5px;
  padding: 2px 5px;
}

.channel-actions button:hover {
  color: #3498db;
}

.channel-actions button:disabled {
  color: #7f8c8d;
  cursor: not-allowed;
}

.empty-tree {
  padding: 20px;
  text-align: center;
  color: #95a5a6;
}

.player-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: #fff;
}

.video-container {
  flex: 1;
  background: #000;
  position: relative;
}

.init-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #aaa;
}

.spinner {
  width: 50px;
  height: 50px;
  border: 5px solid rgba(255, 255, 255, 0.1);
  border-top: 5px solid #3498db;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 15px;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

.playback-controls {
  padding: 15px;
  background: #f8f9fa;
  border-bottom: 1px solid #eee;
  margin-top: 30px;
}

.time-controls {
  display: flex;
  gap: 10px;
  align-items: center;
}

.time-input {
  flex: 1;
}

.time-input label {
  font-size: 12px;
  margin-bottom: 5px;
  color: #555;
  display: block;
}

.time-input input {
  width: 80%;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.player-controls {
  padding: 15px;
  display: flex;
  gap: 10px;
  background: #f8f9fa;
}

.player-controls button {
  padding: 8px 15px;
  border: none;
  border-radius: 4px;
  background: #3498db;
  color: white;
  font-weight: 500;
  cursor: pointer;
  transition: background 0.2s;
  display: flex;
  align-items: center;
  gap: 5px;
}

.player-controls button:hover:not(:disabled) {
  background: #2980b9;
}

.player-controls button:disabled {
  background: #bdc3c7;
  cursor: not-allowed;
}

.fullscreen-btn {
  margin-left: auto;
  padding: 8px 12px !important;
}

.status-section {
  width: 250px;
  background: #ecf0f1;
  padding: 15px;
  display: flex;
  flex-direction: column;
  border-left: 1px solid #ddd;
}

.status-card {
  background: white;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 15px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.status-card h3 {
  margin-top: 0;
  margin-bottom: 10px;
  font-size: 16px;
  color: #2c3e50;
}

.channel-info {
  margin-top: 10px;
  font-size: 14px;
}

.channel-info p {
  margin: 5px 0;
  color: #7f8c8d;
}

.channel-info strong {
  color: #2c3e50;
}

.status-online {
  color: #2ecc71;
}

.status-playing {
  color: #3498db;
}

.status-ready {
  color: #f39c12;
}

.status-offline {
  color: #95a5a6;
}

.status-error {
  color: #e74c3c;
}

.status-loading {
  color: #3498db;
  font-style: italic;
}

.screenshot-preview {
  margin-top: auto;
  background: white;
  border-radius: 8px;
  padding: 15px;
  text-align: center;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.screenshot-preview img {
  max-width: 100%;
  border-radius: 4px;
  margin-bottom: 10px;
}

.screenshot-preview button {
  background: #3498db;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 5px 10px;
  cursor: pointer;
  font-size: 12px;
}

.screenshot-preview button:hover {
  background: #2980b9;
}

.icon-live::before {
  content: "▶";
}

.icon-playback::before {
  content: "⏯";
}

.icon-pause::before {
  content: "⏸";
}

.icon-play::before {
  content: "▶";
}

.icon-stop::before {
  content: "⏹";
}

.icon-capture::before {
  content: "📷";
}

.icon-fullscreen::before {
  content: "⛶";
}
</style>
