<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
      :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover" :style="{ height: '70px' }">
          <el-row :gutter="20" align="middle">
            <!-- 设备数量 -->
            <el-col :span="6" style="display: flex; justify-content: center; align-items: center">
              <el-statistic :value="totalNum">
                <template #title>
                  <div style="display: inline-flex; align-items: center">设备总数</div>
                </template>
              </el-statistic>
            </el-col>
            <!-- 在线设备 -->
            <el-col :span="6" style="display: flex; justify-content: center; align-items: center">
              <el-statistic :value="onlineNum">
                <template #title>
                  <div style="display: inline-flex; align-items: center">在线设备</div>
                </template>
              </el-statistic>
            </el-col>
            <!-- 离线设备 -->
            <el-col :span="6" style="display: flex; justify-content: center; align-items: center">
              <el-statistic :value="offlineNum">
                <template #title>
                  <div style="display: inline-flex; align-items: center">离线设备</div>
                </template>
              </el-statistic>
            </el-col>
            <!-- 未接入设备 -->
            <el-col :span="6" style="display: flex; justify-content: center; align-items: center">
              <el-statistic :value="initNum">
                <template #title>
                  <div style="display: inline-flex; align-items: center">待接入</div>
                </template>
              </el-statistic>
            </el-col>
          </el-row>
        </el-card>
        <el-card shadow="hover" :style="{ marginTop: '10px', height: '60px' }">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="0px">
            <el-form-item label="" prop="name">
              <el-input v-model="queryParams.name" style="width: 120px" placeholder="请输入设备名称" clearable
                        @keyup.enter="handleQuery"/>
            </el-form-item>
            <el-form-item label="" prop="serialNumber">
              <el-input v-model="queryParams.serialNumber" style="width: 120px" placeholder="请输入设备SN" clearable
                        @keyup.enter="handleQuery"/>
            </el-form-item>
            <el-form-item label="" prop="mac">
              <el-input v-model="queryParams.mac" style="width: 125px" placeholder="请输入设备MAC" clearable
                        @keyup.enter="handleQuery"/>
            </el-form-item>
            <el-form-item label="" prop="onlineStatus">
              <el-select v-model="queryParams.onlineStatus" placeholder="请选择设备状态" clearable @change="handleQuery"
                         style="width: 150px">
                <el-option v-for="item in sys_device_online" :key="item.label" :value="item.value"
                           :label="item.label"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
              <el-button v-hasPermi="['smsb:device:add']" type="primary" plain icon="Plus" @click="handleAdd">设备添加
              </el-button>
              <el-button type="warning" plain icon="Picture" :disabled="single" @click="screenShot()">回采画面 </el-button>
              <el-button type="success" plain icon="VideoPlay" :disabled="single" @click="startMonitor()">回调视频
              </el-button>
              <el-button v-hasPermi="['smsb:device:remove']" type="danger" plain icon="Delete" :disabled="multiple"
                @click="handleDelete()">删除
              </el-button>
              <el-button v-hasPermi="['smsb:device:query']" type="info" plain icon="Position" :disabled="single"
                @click="handleInfo()">
                详情
              </el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <div class="table-content">
        <el-table v-loading="loading" :data="deviceList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="设备名称" align="left" prop="name" width="300" :show-overflow-tooltip="true" >
            <template #default="scope">
              <div @click="handleInfo(scope.row)" class="two-line" style="text-decoration: underline;color: #1890FF;">{{ scope.row.name }}</div>
            </template>
          </el-table-column>
<!--
          <el-table-column label="设备名称" align="left" prop="name" width="300" :show-overflow-tooltip="true" />
-->
          <el-table-column label="设备型号" align="left" prop="deviceModel" width="120" :show-overflow-tooltip="true" />
          <el-table-column label="设备SN" align="left" prop="serialNumber" width="220" :show-overflow-tooltip="true" />
          <el-table-column label="设备MAC" align="left" prop="mac" width="180" />
          <el-table-column label="设备标识" align="left" prop="identifier" width="220" :show-overflow-tooltip="true" />
          <el-table-column label="分辨率" align="left" prop="resolution" width="100" />
<!--          <el-table-column label="开机时间" align="left" prop="openTime" width="80" />
          <el-table-column label="关机时间" align="left" prop="closeTime" width="80" />-->
          <el-table-column label="在线状态" align="center" prop="onlineStatus" width="80">
            <template #default="scope">
              <dict-tag :options="sys_device_online" :value="scope.row.onlineStatus" />
            </template>
          </el-table-column>
          <el-table-column label="上线时间" align="left" prop="lastOnline" width="160">
            <template #default="scope">
              <span>{{ parseTime(scope.row.lastOnline, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="上次离线" align="left" prop="offlineTime" width="160">
            <template #default="scope">
              <span>{{ parseTime(scope.row.offlineTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="具体地址" align="left" prop="address" width="180" :show-overflow-tooltip="true" />
          <el-table-column label="创建时间" align="left" prop="createTime" width="160">
            <template #default="scope">
              <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="备注" align="left" prop="remark" width="200" :show-overflow-tooltip="true" />
          <el-table-column label="操作" align="center" fixed="right" class-name="small-padding fixed-width" width="100">
            <template #default="scope">
              <el-tooltip content="修改" placement="top">
                <el-button v-hasPermi="['smsb:device:edit']" link type="primary" icon="Edit"
                  @click="handleUpdate(scope.row)"></el-button>
              </el-tooltip>
              <el-tooltip content="删除" placement="top">
                <el-button v-hasPermi="['smsb:device:remove']" link type="primary" icon="Delete"
                  @click="handleDelete(scope.row)"></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
        :total="total" @pagination="getList" />
    </el-card>
    <!-- 添加或修改设备对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="850px" append-to-body>
      <el-form ref="deviceFormRef" :model="form" :rules="rules" label-width="78px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="设备名称" prop="name">
              <el-input v-model="form.name" maxlength="30" clearable @input="removeSpaces" placeholder="请输入设备名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备型号" prop="deviceModel">
              <el-select v-model="form.deviceModel" placeholder="请选择设备型号" style="width: 100%">
                <el-option v-for="dict in manufacturerList" :key="dict.id" :label="dict.manufacturerName"
                  :value="dict.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="设备SN" prop="serialNumber">
              <el-input v-model="form.serialNumber" @input="removeSpaces" maxlength="20" placeholder="请输入SN号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="MAC" prop="mac">
              <el-input v-model="form.mac" placeholder="ff:ff:ff:ff:ff:ff" maxlength="17" clearable />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="10">
            <el-form-item label="分辨率" prop="width">
              <el-input-number v-model="form.width" controls-position="right" placeholder="请输入宽度" :min="1" :max="100000"
                style="width: 180px" :maxlength="6" />
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="" prop="height" width="10px">
              <el-input-number v-model="form.height" controls-position="right" placeholder="请输入高度" :min="1" :max="100000"
                style="width: 180px" :maxlength="6" />
            </el-form-item>
          </el-col>
        </el-row>
<!--        <el-row>
          <el-col :span="8">
            <el-form-item label="开关机" prop="openTime">
              <el-time-picker v-model="form.range" is-range value-format="HH:mm:ss" :clearable="false" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="异形屏" prop="isAlien">
              <el-radio-group v-model="form.isAlien">
                <el-radio v-for="dict in smsb_yes_no" :key="dict.value" :value="parseInt(dict.value)">{{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="视频监看" prop="isWatch">
              <el-radio-group v-model="form.isWatch">
                <el-radio v-for="dict in smsb_yes_no" :key="dict.value" :value="parseInt(dict.value)">{{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>-->
        <el-form-item label="具体地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入具体地址" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" :rows="5" maxlength="254" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!--设备详情弹窗-->
    <el-dialog v-model="viewDialog.visible" :title="viewDialog.title" width="900px" style="height: 680px"
               append-to-body>
      <el-tabs v-model="activeName" style="height: 500px" @tab-click="handleClickTab">
        <el-tab-pane label="设备详情" name="info">
          <div>
            <span>设备名称：{{ deviceRunInfo.deviceBase.name }}</span>
            <span style="margin-left: 50px">SN：{{ deviceRunInfo.deviceBase.serialNumber }}</span>
            <span style="margin-left: 50px">MAC：{{ deviceRunInfo.deviceBase.mac }}</span>
            <br/>
          </div>
          <div style="margin-top: 20px">
            <span>分辨率：{{ deviceRunInfo.deviceBase.width }}*{{ deviceRunInfo.deviceBase.height }}</span>
            <span style="margin-left: 50px">加密标识：{{ deviceRunInfo.deviceBase.identifier }}</span>
          </div>
          <div style="margin-top: 20px">
            <span>最后一次上线：{{ deviceRunInfo.deviceBase.lastOnline }}</span>
            <span style="margin-left: 50px">上次离线：{{ deviceRunInfo.deviceBase.offlineTime }}</span>
            <span style="margin-left: 50px">创建时间：{{ deviceRunInfo.deviceBase.createTime }}</span>
          </div>
          <!-- 音量 -->
          <div class="slider-block">
            <span style="width: 50px">音量</span>
            <el-slider v-model="deviceRunInfo.volume" :disabled="true" :step="10" show-stops />
          </div>
          <!-- 亮度 -->
          <div class="slider-block">
            <span style="width: 50px">亮度</span>
            <el-slider v-model="deviceRunInfo.bright" :disabled="true" :min="0" :max="255" :step="25.5" show-stops />
          </div>

          <div>
            <span style="display: flex;">
              <!-- cpu -->
              <div class="slider-block">
                <span style="width: 50px">CPU</span>
                <el-progress type="circle" :percentage="deviceRunInfo.cpuUsage" />
              </div>
              <div class="slider-block">
                <span style="width: 50px;margin-left: 20px">内存</span>
                <el-progress type="circle" :percentage="deviceRunInfo.ramUsage" />
              </div>
              <div class="slider-block">
                <span style="width: 50px;margin-left: 20px">存储</span>
                <el-progress type="circle" :percentage="deviceRunInfo.externalUsage" />
              </div>
            </span>
          </div>
          <div style="margin-top: 20px">
            <span>系统构建时间：{{ deviceRunInfo.systemBuildDate }}</span>
            <span style="margin-left: 50px">系统构建版本：{{ deviceRunInfo.systemBuildVersion }}</span>
            <br />
          </div>
          <div style="margin-top: 20px">
            <span>版本CODE：{{ deviceRunInfo.versionCode }}</span>
            <span style="margin-left: 50px">应用版本：{{ deviceRunInfo.versionName }}</span>
            <span style="margin-left: 50px">状态时间：{{ deviceRunInfo.createTime }}</span>
            <br />
          </div>
        </el-tab-pane>
        <el-tab-pane label="远程操作" name="control">
          <div style="margin-top: 10px">
            <el-button :loading="buttonLoading" type="primary" @click="handleControl('reboot')">设备重启</el-button>
            <el-button :loading="buttonLoading" type="primary" @click="handleControl('restartApp')">应用重启</el-button>
            <!--          <el-button :loading="buttonLoading" type="primary" @click="handleControl('shutdown')">远程关机</el-button>-->
            <el-button :loading="buttonLoading" type="primary" @click="handleControl('standby/true')">设备亮屏</el-button>
            <el-button :loading="buttonLoading" type="primary" @click="handleControl('standby/false')">设备息屏</el-button>
            <el-button :loading="buttonLoading" type="primary" @click="handleVoice">音量调节</el-button>
            <el-button :loading="buttonLoading" type="primary" @click="handleBrightness">亮度调节</el-button>
          </div>
          <el-divider border-style="double"/>
          <el-table :data="deviceMultiCardList">
            <el-table-column label="电源端口" align="center" prop="indexNum"/>
            <el-table-column label="电源类型" align="center" prop="powerType">
              <template #default="scope">
                <dict-tag :options="smsb_multi_card_type" :value="scope.row.powerType"/>
              </template>
            </el-table-column>
            <el-table-column label="同步时间" align="center" prop="syncTime"/>
            <el-table-column label="状态" align="center" prop="powerStatus">
              <template #default="scope">
                <dict-tag :options="smsb_multi_card_status" :value="scope.row.powerStatus"/>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="报警信息" name="alarm">
          <div class="table-content">
            <el-table v-loading="loading" :data="alarmList" row-key="id">
              <el-table-column v-if="true" label="主键ID" align="left" prop="id" />
              <el-table-column label="设备名称" align="left" prop="deviceName" :show-overflow-tooltip="true" />
              <el-table-column label="告警等级" align="center" prop="errorLevel" width="100">
                <template #default="scope">
                  <dict-tag :options="smsb_device_error_level" :value="scope.row.errorLevel" />
                </template>
              </el-table-column>
              <el-table-column label="告警类型" align="center" prop="errorType" width="100">
                <template #default="scope">
                  <dict-tag :options="smsb_device_error_type" :value="scope.row.errorType"/>
                </template>
              </el-table-column>
              <el-table-column label="创建时间" align="left" prop="createTime" width="160"/>
            </el-table>
          </div>
          <pagination v-show="alarmTotal > 0" v-model:page="dialogQueryParams.pageNum"
                      v-model:limit="dialogQueryParams.pageSize" :total="alarmTotal" @pagination="getAlarmList"/>
        </el-tab-pane>
        <el-tab-pane label="电源控制" name="power">
          <div style="margin-top: 10px">
            <el-button :loading="buttonLoading" type="primary" @click="handlePower('on')">一键开启</el-button>
            <el-button :loading="buttonLoading" type="primary" @click="handlePower('off')">一键关闭</el-button>
            <el-button :loading="buttonLoading" type="primary" @click="handleSchedule">定时新增</el-button>
            <el-button :loading="buttonLoading" type="primary" @click="handleScheduleSet">定时应用</el-button>
          </div>
          <el-divider border-style="double"/>
          <el-table :data="powerScheduleList">
            <el-table-column label="电源类型" align="center" prop="powerType">
              <template #default="scope">
                <dict-tag :options="smsb_multi_card_type" :value="scope.row.powerType"/>
              </template>
            </el-table-column>
            <el-table-column label="开始日期" align="center" prop="startDate"/>
            <el-table-column label="结束日期" align="center" prop="endDate"/>
            <el-table-column label="亮屏时间" align="center" prop="powerOnTime"/>
            <el-table-column label="息屏时间" align="center" prop="powerOffTime"/>
            <el-table-column label="状态" align="center" prop="status">
              <template #default="scope">
                <dict-tag :options="smsb_multi_card_status" :value="scope.row.status"/>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template #default="scope">
                <el-tooltip content="修改" placement="top">
                  <el-button link type="primary" icon="Edit" @click="handleUpdateSchedule(scope.row)"></el-button>
                </el-tooltip>
                <el-tooltip content="禁用" placement="top">
                  <el-button link type="primary" icon="CircleClose" @click="handleStopSchedule(scope.row)"></el-button>
                </el-tooltip>
                <el-tooltip content="删除" placement="top">
                  <el-button link type="primary" icon="Delete" @click="handleDeleteSchedule(scope.row)"></el-button>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
    <!--推流弹窗-->
    <el-dialog v-model="watchDialog.visible" :title="watchDialog.title" width="900px" append-to-body
      @closed="onDialogClosed">
      <div v-if="watchDialog.visible" style="width: 100%; height: 500px">
        <video ref="flvPlayerRef" style="width: 100%; height: 100%" controls></video>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelStream">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!--截图弹窗-->
    <el-dialog v-model="shotDialog.visible" :title="shotDialog.title" width="900px" append-to-body
      @closed="onDialogClosed">
      <div style="text-align: center">
        <!--        <image-preview :src="screenshotImageUrl" style="width: 40px; height: 40px; cursor: pointer" />-->
        <el-image v-loading="screenshotLoading" :src="screenshotImageUrl" style="width: 600px; height: 600px" />
      </div>
    </el-dialog>
    <!--音量调节弹窗-->
    <el-dialog v-model="voiceDialog.visible" :title="voiceDialog.title" width="600px" append-to-body>
      <el-slider style="margin: 20px" v-model="volumeValue" :min="0" :max="100" :step="10" show-stops />
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="volumeSubmit">确 定</el-button>
          <el-button @click="volumeCancel">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
    <!--亮度调节弹窗-->
    <el-dialog v-model="brightDialog.visible" :title="brightDialog.title" width="700px" append-to-body>
      <el-slider style="margin: 20px" v-model="brightnessValue" :min="0" :max="255" :step="1"/>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="brightSubmit">确 定</el-button>
          <el-button @click="brightCancel">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
    <!--电源开关弹窗-->
    <el-dialog v-model="powerDialog.visible" :title="powerDialog.title" width="600px" append-to-body>
      <el-form ref="powerFormRef" :model="powerForm" :rules="powerRules" label-width="70px">
        <el-form-item label="电源类型" prop="powerType">
          <el-select v-model="powerForm.powerType" placeholder="请选择电源类型" style="width: 150px">
            <el-option v-for="dict in smsb_multi_card_type" :key="dict.value" :label="dict.label"
                       :value="dict.value"/>
          </el-select>
        </el-form-item>
        <el-form-item label="日期范围" prop="dateRange">
          <el-date-picker v-model="powerForm.dateRange" value-format="YYYY-MM-DD" type="daterange" range-separator="-"
                          start-placeholder="开始日期" end-placeholder="结束日期" style="width: 100px"
                          :default-time="[new Date(2025, 1, 1, 0, 0, 0), new Date(2025, 1, 1, 23, 59, 59)]"/>

        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="亮屏时间" prop="powerOnTime">
              <el-time-picker clearable v-model="powerForm.powerOnTime" value-format="HH:mm:ss" placeholder="请选择亮屏时间"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="息屏时间" prop="powerOffTime">
              <el-time-picker clearable v-model="powerForm.powerOffTime" value-format="HH:mm:ss" placeholder="请选择息屏时间"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitPowerForm">确 定</el-button>
          <el-button @click="powerCancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Device" lang="ts">
import {
  addDevice,
  brightSet,
  delDevice,
  deviceStatistics,
  getDevice,
  getDeviceMultiCardList,
  getDeviceRunInfo,
  getDeviceScreenshot,
  listDevice,
  powerSet,
  reboot,
  restartApp,
  scheduleSet,
  shutdown,
  standby,
  startStream,
  stopStream,
  updateDevice,
  volumeSet
} from '@/api/smsb/device/device';
import {DeviceForm, DeviceMultiCardVo, DeviceQuery, DeviceStatisticsVo, DeviceVO} from '@/api/smsb/device/device_type';
import {DeviceManufacturerVO} from '@/api/smsb/device/deviceManufacturer_type';
import {listDeviceManufacturer} from '@/api/smsb/device/deviceManufacturer';
import type {TabsPaneContext} from 'element-plus';
import {onBeforeUnmount, ref} from 'vue';
import flvjs from 'flv.js';
import {DeviceRunInfoVO} from '@/api/smsb/device/device_run_type';
import {DeviceErrorRecordQuery, DeviceErrorRecordVO} from '@/api/smsb/device/errorRecord_type';
import {listDeviceErrorRecord} from '@/api/smsb/device/errorRecord';
import {storeToRefs} from 'pinia';
import useScreenshotStore from '@/store/modules/screenshot';
import {DevicePowerScheduleForm, DevicePowerScheduleVO} from "@/api/smsb/device/device_power_schedule_type";
import {
  addDevicePowerSchedule,
  delDevicePowerSchedule,
  getDevicePowerSchedule,
  listPowerScheduleByDevice,
  stopDevicePowerSchedule,
  updateDevicePowerSchedule
} from "@/api/smsb/device/device_power_schedule";

const screenshotStore = storeToRefs(useScreenshotStore());
const screenshotImageUrl = ref<string>();
const alarmList = ref<DeviceErrorRecordVO[]>([]);
const powerScheduleList = ref<DevicePowerScheduleVO[]>([]);
const {proxy} = getCurrentInstance() as ComponentInternalInstance;
const {
  sys_device_online,
  smsb_yes_no,
  smsb_device_error_level,
  smsb_device_error_type,
  smsb_multi_card_type,
  smsb_multi_card_status
} = toRefs<any>(
  proxy?.useDict('sys_device_online', 'smsb_yes_no', 'smsb_device_error_level', 'smsb_device_error_type', 'smsb_multi_card_type', 'smsb_multi_card_status')
);
const deviceList = ref<DeviceVO[]>([]);
const deviceMultiCardList = ref<DeviceMultiCardVo[]>([]);
const deviceStatisticsVo = ref<DeviceStatisticsVo>();
const manufacturerList = ref<DeviceManufacturerVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const screenshotLoading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const queryFormRef = ref<ElFormInstance>();
const deviceFormRef = ref<ElFormInstance>();
const powerFormRef = ref<ElFormInstance>();
const deviceId = ref<string | number>();
const totalNum = ref(0);
const alarmTotal = ref(0);
const onlineNum = ref(0);
const offlineNum = ref(0);
const streamDeviceId = ref<string | number>();
const initNum = ref(0);
const volumeValue = ref(0);
const brightnessValue = ref(0);
const powerForm = ref<DevicePowerScheduleForm>({
  id: null,
  powerType: "1",
  dateRange: null,
  powerOnTime: null,
  powerOffTime: null,
  deviceId: null
});
const deviceRunInfo = reactive<DeviceRunInfoVO>({
  deviceBase: undefined,
  id: undefined,
  deviceId: undefined,
  bright: undefined,
  volume: undefined,
  cpuUsage: undefined,
  externalMemoryTotal: undefined,
  externalMemoryUsage: undefined,
  externalUsage: undefined,
  ramTotalOfByte: undefined,
  ramUsageOfByte: undefined,
  systemBuildDate: undefined,
  systemBuildVersion: undefined,
  versionCode: undefined,
  versionName: undefined,
  createTime: undefined,
  ramUsage: undefined,
});
const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const viewDialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
const voiceDialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
const brightDialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
const powerDialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
// 播放器实例引用
const flvPlayer = ref<flvjs.Player | null>(null);
const flvPlayerRef = ref<HTMLVideoElement | null>(null);
const watchDialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
const shotDialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
const activeName = ref('info');

const initFormData: DeviceForm = {
  id: undefined,
  identifier: undefined,
  name: undefined,
  productId: undefined,
  deviceModel: undefined,
  serialNumber: undefined,
  mac: undefined,
  openTime: '08:00:00',
  closeTime: '22:00:00',
  address: undefined,
  longitude: undefined,
  latitude: undefined,
  remark: undefined,
  onlineStatus: undefined,
  bound: undefined,
  range: ['08:00:00', '22:00:00'],
  isAlien: undefined,
  height: undefined,
  width: undefined,
  isWatch: undefined
};
const data = reactive<PageData<DeviceForm, DeviceQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    identifier: undefined,
    name: undefined,
    mac: undefined,
    onlineStatus: undefined,
    params: {}
  },
  rules: {
    name: [{ required: true, message: '设备名称不能为空', trigger: 'blur' }],
    deviceModel: [{ required: true, message: '设备型号不能为空', trigger: 'blur' }],
    serialNumber: [{ required: true, message: '设备SN不能为空', trigger: 'blur' }],
    mac: [{ required: true, message: '设备MAC不能为空', trigger: 'blur' }],
    openTime: [{ required: true, message: '开机时间不能为空', trigger: 'blur' }],
    closeTime: [{ required: true, message: '关机时间不能为空', trigger: 'blur' }],
    width: [
      { required: true, message: '宽不能为空', trigger: 'blur' },
      { pattern: /^[0-9]*$/, message: '分辨率必须为数字', trigger: 'blur' }
    ],
    height: [
      { required: true, message: '高度不能为空', trigger: 'blur' },
      { pattern: /^[0-9]*$/, message: '分辨率必须为数字', trigger: 'blur' }
    ]
  }
});
const dialogData = reactive<DialogPageData<DeviceErrorRecordQuery>>({
  dialogQueryParams: {
    pageNum: 1,
    pageSize: 10,
    deviceId: undefined,
    params: {}
  }
});

const {queryParams, form, rules} = toRefs(data);
const {dialogQueryParams} = toRefs(dialogData);
const submitPowerForm = async () => {
  buttonLoading.value = true;
  if (powerForm.value.id){
    await updateDevicePowerSchedule(powerForm.value).finally(() => (buttonLoading.value = false));
  }else {
    await addDevicePowerSchedule(powerForm.value).finally(() => (buttonLoading.value = false));
  }
  await getPowerScheduleList();
  powerDialog.visible = false;
};
const powerCancel = () => {
  powerDialog.visible = false;
};
const removeSpaces = () => {
  if (form.value.name != null) {
    form.value.name = form.value.name.replace(/\s+/g, '');
  }
  if (form.value.serialNumber != null) {
    form.value.serialNumber = form.value.serialNumber.replace(/\s+/g, '');
  }
};
/** 查询设备列表 */
const getList = async () => {
  loading.value = true;
  const res = await listDevice(queryParams.value);
  deviceList.value = res.rows;
  deviceList.value.forEach((data) => {
    data.resolution = data.width + 'x' + data.height;
  });
  total.value = res.total;
  loading.value = false;
};
const getDeviceStatistics = async () => {
  const res = await deviceStatistics();
  deviceStatisticsVo.value = res.data;
  totalNum.value = deviceStatisticsVo.value.totalNum;
  onlineNum.value = deviceStatisticsVo.value.onlineNum;
  offlineNum.value = deviceStatisticsVo.value.offlineNum;
  initNum.value = deviceStatisticsVo.value.initNum;
};
const volumeSubmit = async () => {
  buttonLoading.value = true;
  const deviceId = deviceRunInfo.deviceId;
  await volumeSet(deviceId,volumeValue.value).finally(() => buttonLoading.value = false);
  buttonLoading.value = false;
  proxy?.$modal.msgSuccess('音量设置成功');
  voiceDialog.visible = false;
}
const brightSubmit = async () => {
  buttonLoading.value = true;
  const deviceId = deviceRunInfo.deviceId;
  await brightSet(deviceId,brightnessValue.value).finally(() => buttonLoading.value = false);
  buttonLoading.value = false;
  proxy?.$modal.msgSuccess('亮度设置成功');
  brightDialog.visible = false;
}
const volumeCancel = () => {
  voiceDialog.visible = false;
  buttonLoading.value = false;
}
const brightCancel = () => {
  brightDialog.visible = false;
  buttonLoading.value = false;
}
const handleScheduleSet = async () => {
  buttonLoading.value = true;
  const deviceId = deviceRunInfo.deviceId;
  await scheduleSet(deviceId).finally(() => buttonLoading.value = false);
  proxy?.$modal.msgSuccess("应用成功");
}
const handleSchedule = async () => {
  const deviceId = deviceRunInfo.deviceId;
  powerForm.value.dateRange = [];
  powerForm.value.powerOffTime = null;
  powerForm.value.powerOnTime = null;
  powerForm.value.deviceId = deviceId;
  powerDialog.visible = true;
  powerDialog.title = '定时设置';
}
const handleUpdateSchedule = async (row?: DevicePowerScheduleVO) => {
  const _id = row?.id
  powerForm.value.dateRange = [];
  powerForm.value.powerOffTime = null;
  powerForm.value.powerOnTime = null;
  const res = await getDevicePowerSchedule(_id);
  Object.assign(powerForm.value, res.data);
  powerForm.value.dateRange.push(res.data.startDate);
  powerForm.value.dateRange.push(res.data.endDate);
  powerDialog.visible = true;
  powerDialog.title = "定时设置";
}
const handleStopSchedule = async (row?: DevicePowerScheduleVO) => {
  const id = row?.id
  await proxy?.$modal.confirm('是否确认禁用当前定时配置？').finally(() => loading.value = false);
  await stopDevicePowerSchedule(id);
  proxy?.$modal.msgSuccess("删除成功");
  await getPowerScheduleList();
}
const handleDeleteSchedule = async (row?: DevicePowerScheduleVO) => {
  const _ids = row?.id
  await proxy?.$modal.confirm('是否确认删除定时配置ID为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delDevicePowerSchedule(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getPowerScheduleList();
}
const handlePower = async (type: string) => {
  buttonLoading.value = true;
  const deviceId = deviceRunInfo.deviceId;
  await powerSet(deviceId, type).finally(() => buttonLoading.value = false);
  buttonLoading.value = false;
  proxy?.$modal.msgSuccess('命令下发成功');
}
const handleVoice = () => {
  // console.log("volume num = " + deviceRunInfo.volume)
  voiceDialog.visible = true;
  voiceDialog.title = '音量设置';
  volumeValue.value = deviceRunInfo.volume;
}
const handleBrightness = () => {
  // console.log("volume num = " + deviceRunInfo.volume)
  brightDialog.visible = true;
  brightDialog.title = '亮度设置';
  brightnessValue.value = deviceRunInfo.bright;
}
const getManufacturerList = async () => {
  const queryParams = {
    pageNum: 1,
    pageSize: 100,
    type: 8
  };
  const res = await listDeviceManufacturer(queryParams);
  manufacturerList.value = res.rows;
  manufacturerList.value.forEach((item) => {
    item.manufacturerName = item.manufacturerName + '(' + item.deviceModel + ')';
  });
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
  viewDialog.visible = false;
  watchDialog.visible = false;
  // 关闭播放器
  if (flvPlayer.value) {
    flvPlayer.value.destroy();
  }
};

const cancelStream = () => {
  stopMonitor();
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  deviceFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: DeviceVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  form.value.isAlien = 0;
  form.value.isWatch = 0;
  dialog.visible = true;
  dialog.title = '添加设备';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: DeviceVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getDevice(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改设备';
};

/** 提交按钮 */
const submitForm = () => {
  deviceFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      if (!/^[0-9a-fA-F]{2}(:[0-9a-fA-F]{2}){5}$/.test(form.value.mac)) {
        proxy?.$modal.msgWarning('MAC格式不正确，例 ff:ff:ff:ff:ff:ff');
        return;
      }
      buttonLoading.value = true;
      form.value.openTime = form.value.range[0];
      form.value.closeTime = form.value.range[1];
      if (form.value.id) {
        await updateDevice(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addDevice(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
      await getDeviceStatistics();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: DeviceVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除设备编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delDevice(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
  await getDeviceStatistics();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'system/device/export',
    {
      ...queryParams.value
    },
    `device_${new Date().getTime()}.xlsx`
  );
};
const handleInfo = async (row?: DeviceVO) => {
  activeName.value = 'info';
  deviceId.value = row?.id || ids.value[0];
  const runInfo = await getDeviceRunInfo(deviceId.value);
  Object.assign(deviceRunInfo, runInfo.data);
  deviceRunInfo.ramUsage = (parseFloat(deviceRunInfo.ramUsageOfByte) * 100 / parseFloat(deviceRunInfo.ramTotalOfByte)).toFixed(1)
  viewDialog.title = '设备详情';
  viewDialog.visible = true;
  const multiCardRsp = await getDeviceMultiCardList(deviceId.value);
  deviceMultiCardList.value = multiCardRsp.data;
};

const handleControl = async (type: string) => {
  buttonLoading.value = true;
  if (type === 'reboot') {
    const res = await reboot(deviceId.value).finally(() => buttonLoading.value = false);
  } else if (type === 'restartApp') {
    const res = await restartApp(deviceId.value).finally(() => buttonLoading.value = false);
  } else if (type === 'shutdown') {
    const res = await shutdown(deviceId.value).finally(() => buttonLoading.value = false);
  } else if (type === 'standby/true') {
    const action = true;
    const res = await standby(deviceId.value,action).finally(() => buttonLoading.value = false);
  }else {
    const action = false;
    const res = await standby(deviceId.value,action).finally(() => buttonLoading.value = false);
  }
  buttonLoading.value = false;
  proxy?.$modal.msgSuccess('指令下发成功');
};
let intervalId = null;
const screenShot = async (row?: DeviceVO) => {
  const deviceId = row?.id || ids.value[0];
  shotDialog.title = '回传画面';
  shotDialog.visible = true;
  const res = await getDeviceScreenshot(deviceId);

  intervalId = setInterval(getScreenshot, 1000);
};
const getScreenshot = async () => {
  screenshotImageUrl.value = screenshotStore.state.value.imageUrl;
  console.log('device.vue screenshotImageUrl.value = ' + screenshotImageUrl.value);
  if (screenshotImageUrl.value !== null) {
    clearInterval(intervalId);
    screenshotLoading.value = false;
  }
};
// 对话框关闭时清理
const onDialogClosed = () => {
  destroyPlayer();
  screenshotImageUrl.value = null;
  screenshotStore.state.value.imageUrl = null;
  screenshotLoading.value = true;
  // 清除定时器
  clearInterval(intervalId);
};

const startMonitor = async (row?: DeviceVO) => {
  try {
    const res = await startStream(ids.value[0]);
    streamDeviceId.value = ids.value[0];

    if (res.data.pushResult) {
      // 先销毁已有播放器
      destroyPlayer();
      watchDialog.visible = true;
      watchDialog.title = '回采画面';
      // 确保DOM已更新
      await nextTick();
      if (flvPlayerRef.value && res.data.viewUrl) {
        flvPlayer.value = flvjs.createPlayer({
          type: 'flv',
          url: res.data.viewUrl
        });
        // 错误处理
        /*flvPlayer.value.on(flvjs.Events.ERROR, (errType, errDetail) => {
          console.error('播放错误:', errType, errDetail);
          proxy?.$modal.msgError('视频播放失败，请检查流地址');
          destroyPlayer();
        });*/
        flvPlayer.value.attachMediaElement(flvPlayerRef.value);
        flvPlayer.value.load();
        // 处理浏览器自动播放策略
        flvPlayer.value.play().catch(() => {
          // proxy?.$modal.msgWarning('请点击视频播放按钮以开始播放');
        });
      }
    } else {
      proxy?.$modal.msgError('开启推流失败！');
    }
  } catch (error) {
    proxy?.$modal.msgError('请求推流失败');
  }
};
// 清理播放器
const destroyPlayer = () => {
  if (flvPlayer.value) {
    flvPlayer.value.pause();
    flvPlayer.value.unload();
    flvPlayer.value.detachMediaElement();
    flvPlayer.value.destroy();
    flvPlayer.value = null;
  }
};

const stopMonitor = async () => {
  const res = await stopStream(streamDeviceId.value);
  watchDialog.visible = false;
};

const getAlarmList = async () => {
  dialogQueryParams.value.deviceId = deviceId.value;
  const res = await listDeviceErrorRecord(dialogQueryParams.value);
  alarmList.value = res.rows;
  alarmTotal.value = res.total;
};

const handleClickTab = async (tab: TabsPaneContext, event: Event) => {
  console.log(tab, event);
  if (tab.props.name === 'alarm') {
    await getAlarmList();
  }
  if (tab.props.name === 'power') {
    await getPowerScheduleList();
  }
  if (tab.props.name === 'control') {
    const multiCardRsp = await getDeviceMultiCardList(deviceId.value);
    deviceMultiCardList.value = multiCardRsp.data;
  }
};

const getPowerScheduleList = async () => {
  const deviceId = deviceRunInfo.deviceId;
  const res = await listPowerScheduleByDevice(deviceId);
  powerScheduleList.value = res.data;
};

// 组件卸载前清理
onBeforeUnmount(() => {
  destroyPlayer();
});
onMounted(() => {
  getList();
  getManufacturerList();
  getDeviceStatistics();
});
</script>
<style>
.slider-block {
  max-width: 600px;
  display: flex;
  align-items: center;
  margin-top: 20px;
}
</style>
