<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="名称" prop="cameraName">
        <el-input
          v-model="queryParams.cameraName"
          placeholder="请输入摄像头名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="摄像头厂家" prop="cameraFactory">
        <el-select v-model="queryParams.cameraFactory" placeholder="摄像头厂家">
          <el-option
            v-for="dict in dict.type.camera_factory"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="运营商类型" prop="operatorType">
        <el-select v-model="queryParams.operatorType" placeholder="运营商类型">
          <el-option
            v-for="dict in dict.type.operator_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="摄像头用途" prop="cameraUse">
        <el-select v-model="queryParams.cameraUse" placeholder="摄像头用途">
          <el-option
            v-for="dict in dict.type.camera_use"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="摄像头ip" prop="cameraIp">
        <el-input
          v-model="queryParams.cameraIp"
          placeholder="请输入摄像头ip"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="工作状态" prop="workingStatus">
        <el-select v-model="queryParams.workingStatus" placeholder="工作状态" clearable>
          <el-option
            v-for="dict in dict.type.device_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="离线时间">
        <el-date-picker
          v-model="dateRange"
          style="width: 280px"
          value-format="yyyy-MM-dd HH:mm:ss"
          :default-time="['00:00:00', '23:59:59']"
          type="datetimerange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['camera:camera:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['camera:camera:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['camera:camera:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['camera:camera:export']"
        >导出
        </el-button>
      </el-col>
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          icon="el-icon-refresh"-->
      <!--          size="mini"-->
      <!--          :disabled="multiple"-->
      <!--          @click="replayPreview_hik"-->
      <!--        >查看电视墙-->
      <!--        </el-button>-->
      <!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
          icon="el-icon-refresh"
          type="success"
          size="mini"
          @click="synchronizeCamera"
          v-hasPermi="['DahuaController:DahuaController:edit']"
        >同步设备状态
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :visible.sync="loading" :data="cameraList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="摄像头名称" align="center" prop="cameraName"/>
      <el-table-column label="ip" align="center" prop="cameraIp"/>
      <el-table-column label="摄像头厂家" align="center" prop="cameraFactory" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.camera_factory" :value="scope.row.cameraFactory"/>
        </template>
      </el-table-column>
      <el-table-column label="融合平台" align="center" prop="convergencePlatform">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.convergence_platform" :value="scope.row.convergencePlatform"/>
        </template>
      </el-table-column>
      <!--      <el-table-column label="所属区域" align="center" prop="cameraRegion"/>-->
      <el-table-column label="设备状态" align="center" prop="workingStatus" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.device_status" :value="scope.row.workingStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="离线原因" align="center" prop="offlineReason">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.camera_offline_reason" :value="scope.row.offlineReason"/>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" width="550" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-video-camera"
            @click="preview(scope.row)"
            v-hasPermi="['camerachannel:camerachannel:selectchannel']"
          >预览
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-video-camera"
            @click="playBack(scope.row)"
            v-hasPermi="['camerachannel:camerachannel:selectchannel']"
          >回放
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['camera:camera:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['camera:camera:remove']"
          >删除
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleSee(scope.row)"
            v-hasPermi="['camera:camera:query']"
          >查看
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-link"
            @click="handleCameraChannel(scope.row)"
            v-hasPermi="['camerachannel:camerachannel:list']"
          >通道管理
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-s-management"
            @click="handleCameraDept(scope.row)"
            v-hasPermi="['aidevicedept:aidevicedept:list']"
          >部门管理
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-document"
            @click="handleCameraEvent(scope.row)"
            v-hasPermi="['aideviceevent:aideviceevent:list']"
          >事件管理
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-document"
            @click="handleCameraLog(scope.row)"
            v-hasPermi="['camera:camera:listLog']"
          >运行历史
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getListByDept"
    />
    <!-- 添加或修改摄像头对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body :close-on-click-modal="false">
      <el-card class="box-card">
        <el-steps :active="active" align-center>
          <el-step title="设备基础信息" icon="el-icon-video-camera-solid"></el-step>
          <el-step title="设备详细信息" icon="el-icon-success"></el-step>
        </el-steps>
      </el-card>
      <el-card class="box-card" style="margin-top:15px;">
        <el-form ref="form" :model="form" :rules="rules" label-width="100px">
          <div v-show="active == 1">
            <el-row>
              <el-col :span="20">
                <el-form-item label="摄像头厂家" prop="cameraFactory">
                  <el-select v-model="form.cameraFactory" placeholder="摄像头厂家">
                    <el-option v-for="dict in dict.type.camera_factory" :key="dict.value" :label="dict.label"
                               :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item label="融合平台" prop="convergencePlatform">
                  <el-select v-model="form.convergencePlatform" placeholder="融合平台">
                    <el-option v-for="dict in dict.type.convergence_platform" :key="dict.value" :label="dict.label"
                               :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item label="摄像头名称" prop="cameraName">
                  <el-input v-model="form.cameraName" placeholder="请输入摄像头名称"/>
                </el-form-item>
                <el-form-item label="所属区域" prop="cameraRegion">
                  <el-input v-model="form.cameraRegion" placeholder="请输入所属区域"/>
                </el-form-item>
                <el-form-item label="半径" prop="cameraRadius">
                  <el-input v-model="form.cameraRadius" placeholder="请输入半径"/>
                </el-form-item>
                <el-form-item label="高度" prop="height">
                  <el-input v-model="form.height" placeholder="请输入高度"/>
                </el-form-item>
                <el-form-item label="经度" prop="longitude">
                  <el-input v-model="form.longitude" placeholder="请输入经度" @dblclick.native="showMap"/>
                </el-form-item>
                <el-form-item label="纬度" prop="latitude">
                  <el-input v-model="form.latitude" placeholder="请输入纬度" @dblclick.native="showMap"/>
                </el-form-item>
                <el-form-item label="摄像头用途" prop="cameraUse">
                  <el-select v-model="form.cameraUse" placeholder="请选择摄像头用途">
                    <el-option
                      v-for="dict in dict.type.camera_use"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
          <div v-show="active == 2 ">
            <el-row>
              <el-col :span="18">
                <el-form-item label="ip" prop="cameraIp">
                  <el-input v-model="form.cameraIp" placeholder="请输入ip"/>
                </el-form-item>
                <el-form-item label="端口" prop="cameraPort">
                  <el-input v-model="form.cameraPort" maxlength="10" placeholder="请输入端口"/>
                </el-form-item>
                <el-form-item label="账号" prop="cameraAccount">
                  <el-input v-model="form.cameraAccount" maxlength="20" placeholder="请输入账号"/>
                </el-form-item>
                <el-form-item label="密码" prop="cameraPasword">
                  <el-input v-model="form.cameraPasword" maxlength="20" placeholder="请输入密码" show-password
                            autocomplete="new-password"
                  />
                </el-form-item>
                <el-form-item label="摄像头编码" prop="cameraCode">
                  <el-input v-model="form.cameraCode" :disabled="cameraCodeDisabled" placeholder="请输入摄像头编码"/>
                </el-form-item>
                <el-form-item label="通道编号" prop="channelNum">
                  <el-input v-model="form.channelNum" placeholder="请输入通道编号"/>
                </el-form-item>
                <el-form-item label="摄像头类型" prop="cameraType">
                  <el-select v-model="form.cameraType" placeholder="请选择摄像头类型">
                    <el-option
                      v-for="dict in dict.type.camera_type"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="可用系统" prop="list">
                  <el-select v-model="form.list" multiple placeholder="请选择用途">
                    <el-option
                      v-for="dict in dict.type.camera_system"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="运营商类型" prop="operatorType">
                  <el-select v-model="form.operatorType" placeholder="请选择运营商类型">
                    <el-option
                      v-for="dict in dict.type.operator_type"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="图片" prop="cameraImagesList">
                  <image-upload v-model="form.cameraImagesList"/>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </el-form>
      </el-card>
      <div slot="footer" class="dialog-footer" v-show="active != 3">
        <el-button v-if="active < 2 && form.cameraFactory !== undefined" :disabled="isFormIncomplete()"
                   style="margin-top: 12px" type="primary" @click="next"
        >下一步
        </el-button>
      </div>
      <div slot="footer" class="dialog-footer" v-show="active == 2">
        <el-button v-if="active > 1" style="margin-top: 12px" @click="pre">上一步</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </div>
    </el-dialog>

    <!-- 详情 -->
    <el-dialog :title="title" :visible.sync="openSee" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <!--<el-form-item label="数据所属部门" prop="dataDeptId">
              <deptselector :setValue=setDataDeptId ></deptselector>
            </el-form-item>-->
            <el-form-item label="融合平台" prop="convergencePlatform" label-width="120px">
              <el-select v-model="form.convergencePlatform" placeholder="融合平台" :disabled="true"
                         style="width: 360px;"
              >
                <el-option
                  v-for="dict in dict.type.convergence_platform"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="摄像头厂家" prop="cameraFactory" label-width="120px">
              <el-select v-model="form.cameraFactory" placeholder="摄像头厂家" :disabled="true " style="width: 360px;">
                <el-option
                  v-for="dict in dict.type.camera_factory"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="摄像头类型" prop="cameraType" label-width="120px">
              <el-select v-model="form.cameraType" placeholder="请选择摄像头类型" :disabled="true"
                         style="width: 360px;"
              >
                <el-option
                  v-for="dict in dict.type.camera_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="摄像头名称" prop="cameraName" label-width="120px">
              <el-input v-model="form.cameraName" :disabled="true"/>
            </el-form-item>
            <el-form-item label="摄像头编码" prop="cameraCode" label-width="120px">
              <el-input v-model="form.cameraCode" :disabled="true"/>
            </el-form-item>
            <el-form-item label="通道编号" prop="channelNum" label-width="120px">
              <el-input v-model="form.channelNum" :disabled="true"/>
            </el-form-item>
            <el-form-item label="账号" prop="cameraAccount" label-width="120px">
              <el-input v-model="form.cameraAccount" :disabled="true"/>
            </el-form-item>
            <el-form-item label="密码" prop="cameraPasword" label-width="120px">
              <el-input v-model="form.cameraPasword" :disabled="true" show-password/>
            </el-form-item>
            <el-form-item label="摄像头用途" prop="cameraUse" label-width="120px">
              <el-select v-model="form.cameraUse" placeholder="请选择摄像头用途" :disabled="true" style="width: 360px;">
                <el-option
                  v-for="dict in dict.type.camera_use"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属区域" prop="cameraRegion" label-width="120px">
              <el-input v-model="form.cameraRegion" :disabled="true"/>
            </el-form-item>
            <el-form-item label="运营商类型" prop="operatorType" label-width="120px">
              <el-select v-model="form.operatorType" placeholder="请选择运营商类型" :disabled="true"
                         style="width: 360px;"
              >
                <el-option
                  v-for="dict in dict.type.operator_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="半径" prop="cameraRadius" label-width="120px">
              <el-input type="number" v-model="form.cameraRadius" :disabled="true"/>
            </el-form-item>
            <el-form-item label="高度" prop="height" label-width="120px">
              <el-input type="number" v-model="form.height" :disabled="true"/>
            </el-form-item>
            <el-form-item label="经度" prop="longitude" label-width="120px">
              <el-input type="number" v-model="form.longitude" :disabled="true"/>
            </el-form-item>
            <el-form-item label="纬度" prop="latitude" label-width="120px">
              <el-input type="number" v-model="form.latitude" :disabled="true"/>
            </el-form-item>
            <el-form-item label="ip" prop="cameraIp" label-width="120px">
              <el-input v-model="form.cameraIp" :disabled="true"/>
            </el-form-item>
            <el-form-item label="端口" prop="cameraPort" label-width="120px">
              <el-input v-model="form.cameraPort" :disabled="true"/>
            </el-form-item>
            <el-form-item label="可用系统" prop="list" label-width="120px">
              <el-select v-model="form.list" multiple placeholder="请选择用途" :disabled="true" style="width: 360px;">
                <el-option
                  v-for="dict in dict.type.camera_system"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelSel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 超图弹框 -->
    <ISuperMap ref="ISuperMap" v-if="ISuperMapvisible" @send="send"/>
    <!--<el-dialog :title="titleLongitude" :visible.sync="showLongitude">-->
    <!--<el-input v-show="false" v-model="form.longitude"></el-input>-->
    <!--<el-input v-show="false" v-model="form.latitude"></el-input>-->
    <!--<supermap style="width: 100%;height: 500px;" :mapDiv="'cameraMap'" :mapSite="{doubleClickZoom:false}"-->
    <!--:codes="['9fa5']" :isSideBySide="false" :showLatLng="showLatLng"></supermap>-->
    <!--<el-button type="primary" @click="showLongitude=false">确 定</el-button>-->
    <!--</el-dialog>-->
    <!-- 通道管理弹框 -->
    <el-dialog :title="titleCameraChannel" :visible.sync="showCameraChannel" @close="closeDialog">
      <camerachannel v-if="showCameraChannel" ref="cameraChannel" :sonId="sonIdValue" :channelCameraIp="channelCameraIp"
                     :channelCameraPort="channelCameraPort" :channelCameraAccount="channelCameraAccount"
                     :channelCameraPasword="channelCameraPasword" :deviceCode="deviceCode"
                     :deviceSn="deviceSn" :deviceProtocolType="deviceProtocolType" :deviceLoginType="deviceLoginType"
                     :cameraUse="cameraUse" style="width: 100%;height: 100%;"
      ></camerachannel>
    </el-dialog>

    <!-- 运行历史弹框 -->
    <el-dialog :title="titleCameraLog" :visible.sync="showCameraLog" @close="closeDialog">
      <camerastatelog v-if="showCameraLog" ref="cameraLog" :sonId="sonIdValue"
                      style="width: 100%;height: 100%;"
      ></camerastatelog>
    </el-dialog>

    <!-- 部门管理弹框 -->
    <el-dialog :title="titleCameraDept" :visible.sync="showCameraDept" @close="closeDialog">
      <aidevicedept v-if="showCameraDept" ref="cameraDept" :sonId="sonIdValue" :sonCode="sonCodeValue"
                    :sonName="sonNameValue" :sonType="sonTypeValue" style="width: 100%;height: 100%;"
      ></aidevicedept>
    </el-dialog>

    <!-- 事件管理弹框 -->
    <el-dialog :title="titleCameraEvent" :visible.sync="showCameraEvent" @close="closeDialog">
      <!--<cameraevent v-if="showCameraEvent" ref="cameraEvent" :sonId="sonIdValue"
                   style="width: 100%;height: 100%;"></cameraevent>-->
      <aideviceevent v-if="showCameraEvent" ref="cameraEvent" :sonId="sonIdValue" :sonCode="sonCodeValue"
                     :sonName="sonNameValue" :sonType="sonTypeValue"
                     style="width: 100%;height: 100%;"
      ></aideviceevent>
    </el-dialog>
    <!--大华预览回放窗口-->
    <el-dialog :title="dssPreviewTitle" :visible.sync="dssPreviewVisible" v-if="dssPreviewVisible"
               customClass="videoCustomWidth"
               @close="destroy" append-to-body
    >
      <div id="dssPreview" style="width:1020px;height:625px;position:relative;"></div>
    </el-dialog>
    <!--海康预览回放窗口-->
    <!--预览-->
    <el-dialog :title="cameraTitle" :visible.sync="cameraVisible" v-if="cameraVisible" customClass="videoCustomWidth"
               @close="hikDisconnect" append-to-body
    >
      <div id="playWnd" style="width:1020px;height:625px;position:relative;"></div>
    </el-dialog>
    <!--回放-->
    <el-dialog :title="cameraTitlePlayBack" :visible.sync="cameraVisiblePlayBack" v-if="cameraVisiblePlayBack"
               customClass="videoCustomWidthPlayBack"
               @close="cancelEventLocationShow()"
    >
      <div class="item" style="z-index: 99999"><span class="label">回放开始时间：</span>
        <input type="datetime-local" value-format="yyyy-MM-dd HH:mm:ss" v-model="startTimeStamp"/>
        <span class="label">回放结束时间：</span>
        <input type="datetime-local" value-format="yyyy-MM-dd HH:mm:ss" v-model="endTimeStamp"/>
      </div>
      <div class="item" style="margin-top: 20px;margin-left: -20px;">
        <button style="width:90px;padding:0;margin:0;" class="btn" @click="startPlayback">回放</button>
        <button style="width:90px;padding:0;margin:0;" class="btn" @click="stopAllPlayback">停止全部回放</button>
      </div>
      <div style="width:1020px;height:625px;position:relative;">
        <div id="playWndPlayBack" class="playWndPlayBack" style="left: 0px; top: 0px;"></div>
      </div>
    </el-dialog>
    <haikang-t-v-walls ref="haikangTVWalls"></haikang-t-v-walls>
  </div>
</template>

<script>
import {
  listCamera,
  listCameraByDept,
  getCamera,
  delCamera,
  addCamera,
  updateCamera,
  selectchannelCodeByCameraId,
  listStateLog,
  synchronizeOfflineCamera
} from '@/api/centerMonitor/camera/camera'
import { listCamerachannel } from '@/api/centerMonitor/camera/camerachannel'
import deptselector from '@/views/components/deptselector'
import supermap from '@/views/components/supermap'
import ISuperMap from '@/views/components/ISuperMap'
import camerachannel from './camerachannel'
import camerastatelog from './camerastatelog'
import aidevicedept from '@/views/centerMonitor/aidevicedept/aidevicedept'
import aideviceevent from '@/views/centerMonitor/aideviceevent/aideviceevent'
import haikangTVWalls from '@/views/components/haikangTVWalls.vue'
import { checkNonnegativeInteger, checkLat, checkLon } from '@/api/system/rules'
import {
  selectConfigKey
} from '@/api/system/config'

// import moment from 'moment';
/** ----------------------------------摄像头预览开始------------------------------------- */
import { getDahuaVideoServer } from '@/api/centerMonitor/dahua/dahua'
import DHWs from '@/daHua/lib/DHWs'
import {
  getHaiKangVideoServer
} from '@/api/haikang/haikang'

/** ----------------------------------摄像头预览结束------------------------------------- */

export default {
  name: 'Camera',
  metaInfo() {
    return {
      title: this.pageName
    }
  },
  components: {
    deptselector,
    supermap,
    camerachannel,
    camerastatelog,
    aidevicedept,
    aideviceevent,
    ISuperMap,
    haikangTVWalls
  },
  dicts: ['camera_system', 'operator_type', 'camera_factory', 'camera_type', 'camera_use', 'device_status', 'camera_offline_reason', 'convergence_platform'],
  data() {
    let disabledDate = date => {
      return date.getTime() > new Date().getTime() - 24 * 60 * 60 * 1000
    }
    return {
      pageName: '态势感知平台',
      pickerOptions: {
        disabledDate,
        // selectableRange 用来限制时分秒的选择，这里要求只能选择当前时间之后到0点的时间点 但应该只限今天
        selectableRange: '00:00:00 - 23:59:59'
      },
      /***海康***/
      cameraTitle: '',
      cameraVisible: false,
      cameraTitlePlayBack: '',
      cameraVisiblePlayBack: false,
      cameraIndexCodePlayBack: '',
      startTimeStamp: '',
      endTimeStamp: '',
      initCount: 0,
      pubKey: '',
      oWebControl: null,
      /***大华***/
      dssPreviewTitle: '',
      dssPreviewVisible: false,
      ctrl: 'ctrl1',
      active: 1,
      // 选中数组
      ids: [],
      //摄像头编码是否可编辑
      cameraCodeDisabled: true,
      // 遮罩层
      loading: true,
      // 选中数组
      cameraCodes: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 日期范围
      dateRange: [],
      // 总条数
      total: 0,
      // 摄像头表格数据
      cameraList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 是否显示详情弹出层
      openSee: false,
      // 超图
      sign: 1,
      ISuperMapvisible: false,
      showLongitude: false,
      titleLongitude: '',
      // 通道
      showCameraChannel: false,
      titleCameraChannel: '',
      // 日志
      showCameraLog: false,
      titleCameraLog: '',
      // 部门
      showCameraDept: false,
      titleCameraDept: '',
      // 事件
      showCameraEvent: false,
      titleCameraEvent: '',
      //传递到子页面摄像头ID
      sonIdValue: null,
      //传递到子页面摄像头Code
      sonCodeValue: null,
      //传递到子页面摄像头Name
      sonNameValue: null,
      //传递到子页面设备类型
      sonTypeValue: null,
      //通道子页面传值
      channelCameraIp: null,
      channelCameraPort: null,
      channelCameraAccount: null,
      channelCameraPasword: null,
      cameraUse: null,
      deviceCode: null,
      deviceSn: null,
      deviceProtocolType: null,
      deviceLoginType: null,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        dataStatus: null,
        dataDeptId: null,
        cameraName: null,
        cameraIp: null,
        cameraPort: null,
        cameraAccount: null,
        cameraPasword: null,
        cameraCode: null,
        cameraFactory: null,
        convergencePlatform: null,
        cameraRegion: null,
        cameraRadius: null,
        height: null,
        longitude: null,
        latitude: null,
        operatorType: null,
        cameraUse: null,
        channelNum: null,
        workingStatus: null,
        cameraImg: null,
        deviceCode: null,
        deviceSn: null,
        deviceProtocolType: null,
        deviceLoginType: null
      },
      // 通道查询参数
      queryChannelParams: {
        pageNum: 1,
        pageSize: 10,
        dataStatus: null,
        cameraId: null,
        channelCode: null,
        channelName: null,
        channelType: null
      },
      cameraSystemList: [],
      // 表单参数
      form: {
        cameraImages: [],
        cameraImagesList: []
      },
      // 表单校验
      rules: {
        cameraName: [
          { required: true, message: '摄像头名称不能为空', trigger: 'blur' }
        ],
        // cameraIp: [
        //   {
        //     required: true,
        //     pattern: /^(?:[1-9]|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])\.(?:\d|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])\.(?:\d|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])\.(?:\d|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])$/,
        //     message: "请输入正确的IP地址",
        //     trigger: "blur",
        //     validator: (rule, value, callback) => {
        //       if (this.form.cameraFactory == 0 && !value.match(rule.pattern)) {
        //         callback(new Error("请输入正确的IP地址"));
        //       } else if (this.form.cameraFactory == 0 && !value) {
        //         callback(new Error("IP不能为空"));
        //       } else {
        //         callback();
        //       }
        //     },
        //   },
        // ],
        cameraIp: [
          {
            validator: (rule, value, callback) => {
              if (!value) {
                // 如果值为空，则不进行验证
                callback()
              } else {
                // 进行 IP 地址格式验证
                if (!value.match(/^(?:[1-9]|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])\.(?:\d|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])\.(?:\d|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])\.(?:\d|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])$/)) {
                  // 如果值不符合规定格式，则返回错误
                  callback(new Error('请输入正确的IP地址'))
                } else {
                  callback()
                }
              }
            }
          }
        ],

        cameraPort: [
          {
            validator: (rule, value, callback) => {
              if (!value) {
                callback()
              } else if (!value.match(/^[1-9]\d*$/)) {
                callback(new Error('请输入正确的端口'))
              } else {
                callback()
              }
            }
          }
        ],

        // cameraPort: [
        //   {
        //     validator: (rule, value, callback) => {
        //       // 处理存入前的值
        //       const processedValue = value === null ? '' : value;
        //
        //       if (processedValue === "") {
        //         // 如果值为空，则不进行验证
        //         callback();
        //       } else if (!/^[1-9]\d*$/.test(processedValue)) {
        //         // 如果值不符合规定格式，则返回错误
        //         callback(new Error("请输入正确的端口"));
        //       } else {
        //         callback();
        //       }
        //     },
        //   },
        // ],

        // cameraAccount: [
        //   {required: true, message: "账号不能为空", trigger: "blur",
        //     validator: (rule, value, callback) => {
        //       if (this.form.cameraFactory == 0 && !value) {
        //         callback(new Error("账号不能为空"));
        //       } else {
        //         callback();
        //       }
        //     },
        //
        //   },
        // ],
        // cameraPasword: [
        //   {required: true, message: "密码不能为空", trigger: "blur",
        //     validator: (rule, value, callback) => {
        //       if (this.form.cameraFactory == 0 && !value) {
        //         callback(new Error("密码不能为空"));
        //       } else {
        //         callback();
        //       }
        //     },
        //   },
        // ],
        cameraCode: [
          { required: true, message: '摄像头编码不能为空', trigger: 'blur' }
        ],
        convergencePlatform: [
          { required: true, message: '融合平台不能为空', trigger: 'blur' }
        ],
        cameraFactory: [
          { required: true, message: '摄像头厂家不能为空', trigger: 'blur' }
        ],
        height: [
          { required: true, message: '高度不能为空', trigger: 'blur' }
        ],
        cameraRegion: [
          { required: true, message: '所属区域不能为空', trigger: 'blur' }
        ],
        cameraRadius: [
          { required: true, message: '半径不能为空', trigger: 'blur' },
          { validator: checkNonnegativeInteger, trigger: 'blur' }
        ],
        longitude: [
          { required: true, message: '经度不能为空', trigger: 'change' },
          { validator: checkLon, trigger: 'blur' }
        ],
        latitude: [
          { required: true, message: '纬度不能为空', trigger: 'change' },
          { validator: checkLat, trigger: 'blur' }
        ],
        list: [
          { required: true, message: '可用系统不能为空', trigger: 'blur' }
        ],
        cameraType: [
          { required: true, message: '摄像头类型不能为空', trigger: 'blur' }
        ],
        cameraUse: [
          { required: true, message: '摄像头用途不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  activated: function() {
    let startTime = this.$route.query.startTime // 从url中获取startTime参数
    let endTime = this.$route.query.endTime // 从url中获取endTime参数
    if (startTime && endTime) {
      startTime = startTime + ' 00:00:00'
      endTime = endTime + ' 23:59:59'
      this.dateRange = [startTime, endTime]
    }
    this.queryParams.workingStatus = this.$route.query.workingStatus
    this.queryParams.deptId = this.$route.query.deptId
    this.queryParams.pageNum = 1
    if (this.queryParams.deptId != null && this.queryParams.workingStatus != null) {
      this.getListByDept()
    } else {
      this.getList()
    }
  },
  created() {
    //此处必须第二次调用  防止组件注册后直接F5刷新页面 导致不走getList方法
    this.getList()
    /** ----------------------------------摄像头预览开始------------------------------------- */
    const DHWsInstance = DHWs.getInstance()
    this.ws = DHWsInstance
    /** ----------------------------------摄像头预览结束------------------------------------- */
  },
  mounted() {
    this.cameraSystemList = this.dict.type.camera_system
    window.alertLoginFailed = this.alertLoginFailed// 登陆失败
    window.alertReinstall = this.alertReinstall// 请重新安装客户端
    setTimeout(() => {
      this.pageName = '全域视联平台'
    }, 2000)
  },
  methods: {
    isFormIncomplete() {
      return !this.form.cameraFactory || !this.form.cameraName || !this.form.cameraRegion || !this.form.cameraRadius || !this.form.height || !this.form.longitude || !this.form.latitude
    },
    login: function(row) { // 调用登录接口
      console.log('row', row)
    },
    next() {
      this.$refs['form'].validateField('longitude', (valid, message) => {
        if (valid == '') {

          this.$refs['form'].validateField('latitude', (valids, message) => {
            if (valids == '') {
              if (this.active++ > 5) this.active = 1
            }
          })
        }
      })
    },
    pre() {
      if (this.active-- < 1) this.active = 1
    },
    showMap() {
      this.ISuperMapvisible = true
      this.$nextTick(() => {
        this.$refs.ISuperMap.init(this.sign, {
          id: this.form.id,
          longitude: this.form.longitude,
          latitude: this.form.latitude,
          xiantude: this.form.longitude//this.form.longitude换成每个页面对应线或者面对应的字段
        })
      })
    },
    send(val) {
      if (val === true) {
        this.ISuperMapvisible = false
        return
      }
      if (this.sign === 1) {
        this.form.longitude = val.longitude
        this.form.latitude = val.latitude
      }
      if (this.sign === 2 || this.sign === 3) this.form.longitude = val.xiantude//this.form.longitude 换成对应的线或区域的字段
      this.ISuperMapvisible = false
    },
    showLatLng: function(lat, lng) {
      this.form.latitude = lat
      this.form.longitude = lng
    },
    // 取消按钮
    cancelSel() {
      this.openSee = false
      this.reset()
    },
    /** 查询摄像头详情 */
    handleSee(row) {
      this.reset()
      const id = row.id || this.ids
      getCamera(id).then(response => {
        this.form = response.data
        const selectList = []
        for (let index in this.form.list) {
          selectList.push(this.form.list[index].type)
        }
        this.form.list = selectList
        this.openSee = true
        this.title = '详情'
      })
    },
    /** 查询摄像头列表 */
    getList() {
      this.loading = true
      listCamera(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.cameraList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    /** 查询摄像头列表 */
    getListByDept() {
      if (this.queryParams.workingStatus != null && this.queryParams.deptId != null) {
        this.loading = true
        listCameraByDept(this.queryParams).then(response => {
          this.cameraList = response.rows
          this.total = response.total
          this.loading = false
        })
      } else {
        // 执行查询所有列表的逻辑
        this.getList()
      }
    },
    /** 通道管理列表 */
    handleCameraChannel(row) {
      const id = row.id || this.ids
      this.sonIdValue = id
      this.channelCameraIp = row.cameraIp
      this.channelCameraPort = row.cameraPort
      this.channelCameraAccount = row.cameraAccount
      this.channelCameraPasword = row.cameraPasword
      this.cameraUse = row.cameraUse
      this.deviceCode = row.deviceCode
      this.deviceSn = row.deviceSn
      this.deviceProtocolType = row.deviceProtocolType
      this.deviceLoginType = row.deviceLoginType
      this.showCameraChannel = true
      this.titleCameraChannel = '通道管理列表'
    },
    /** 日志管理列表 */
    handleCameraLog(row) {
      const id = row.id || this.ids
      this.sonIdValue = id
      this.showCameraLog = true
      this.titleCameraLog = '运行历史列表'
    },
    /** 部门管理列表 */
    handleCameraDept(row) {
      const id = row.id
      this.sonIdValue = id
      this.sonTypeValue = 'device_type_1'
      this.sonCodeValue = row.cameraCode
      this.sonNameValue = row.cameraName
      this.showCameraDept = true
      this.titleCameraDept = '部门管理列表'
    },
    /** 事件类型管理列表 */
    handleCameraEvent(row) {
      const id = row.id
      this.sonIdValue = id
      this.sonTypeValue = 'device_type_1'
      this.sonCodeValue = row.cameraCode
      this.sonNameValue = row.cameraName
      this.showCameraEvent = true
      this.titleCameraEvent = '事件类型管理列表'
    },
    closeDialog() {
      this.showCameraChannel = false
      this.showCameraDept = false
      this.showCameraEvent = false
      this.showCameraLog = false
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    setDataDeptId(e) {
      this.form.dataDeptId = e
      this.queryParams.dataDeptId = e
    },
    // 表单重置
    reset() {
      this.active = 1
      this.form = {
        id: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        dataStatus: 'data_status_1',
        dataDeptId: null,
        cameraName: null,
        cameraIp: null,
        cameraPort: null,
        cameraAccount: null,
        cameraPasword: null,
        cameraCode: null,
        cameraFactory: null,
        convergencePlatform: null,
        cameraRegion: null,
        cameraRadius: null,
        height: null,
        longitude: null,
        latitude: null,
        workingStatus: '0',
        deptId: null
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      this.resetForm('queryForm')
      this.handleQuery()
    },
    /** 新增按钮操作 */
    handleAdd() {
      //设置新增时可以改摄像头编码
      this.cameraCodeDisabled = false
      this.reset()
      this.open = true
      this.title = '添加摄像头'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      //设置修改时不能改摄像头编码
      this.cameraCodeDisabled = false
      const id = row.id || this.ids
      getCamera(id).then(response => {
        this.form = response.data
        const updateList = []
        for (let index in this.form.list) {
          updateList.push(this.form.list[index].type)
        }
        this.form.list = updateList
        this.open = true
        this.title = '修改摄像头'
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除摄像头数据？').then(function() {
        return delCamera(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {
      })
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** ----------------------------------摄像头预览开始------------------------------------- */
    preview(row) {
      selectConfigKey('DssVersion').then(res => {
        if (this.ws.getLocalDssVersion() != res.data) {
          this.$modal.confirm('系统检测到新客户端版本，请更新后使用', '系统提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            selectConfigKey('video_plugin_url').then(response => {
              window.open(response.data)
            })
          }).catch(() => {
            return
          })
          return
        }
        const convergencePlatform = row.convergencePlatform
        const cameraCode = row.cameraCode
        const cameraName = row.cameraName
        const deviceSn = row.deviceSn
        const deviceCode = row.deviceCode
        const deviceProtocolType = row.deviceProtocolType
        const deviceLoginType = row.deviceLoginType
        console.log(convergencePlatform)
        //如果是大华摄像头
        if (convergencePlatform === '1') {
          selectchannelCodeByCameraId(row.id).then(res => {
            if (cameraCode != null && cameraCode.length > 0) {
              this.dssPreviewTitle = '视频预览'
              this.dssPreviewVisible = true
              this.preview_dss(cameraCode, cameraName, deviceCode, deviceSn, deviceProtocolType, deviceLoginType)
            } else {
              this.$modal.msg('没有匹配到相对应摄像头！！！')
            }
          })
        } else {
          //海康头
          console.log('haikang')
          const cameraIndexCode = row.cameraCode
          this.$refs.haikangTVWalls.showTVWall(cameraIndexCode, 0)
        }
      })
    },
    /** ----------------------------------摄像头预览结束------------------------------------- */


    /** ----------------------------------摄像头回放开始------------------------------------- */
    playBack(row) {
      selectConfigKey('DssVersion').then(res => {
        if (this.ws.getLocalDssVersion() != res.data) {
          this.$modal.confirm('系统检测到新客户端版本，请更新后使用', '系统提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            selectConfigKey('video_plugin_url').then(response => {
              window.open(response.data)
            })
          }).catch(() => {
            return
          })
          return
        }
        const cameraCode = row.cameraCode
        const cameraName = row.cameraName
        const deviceSn = row.deviceSn
        const deviceCode = row.deviceCode
        const deviceProtocolType = row.deviceProtocolType
        const deviceLoginType = row.deviceLoginType
        const convergencePlatform = row.convergencePlatform
        //如果是大华摄像头
        if (convergencePlatform === '1') {
          selectchannelCodeByCameraId(row.id).then(res => {
            if (cameraCode != null && cameraCode.length > 0) {
              this.dssPreviewTitle = '视频回放'
              this.dssPreviewVisible = true
              this.playBack_dss(cameraCode, cameraName, deviceCode, deviceSn, deviceProtocolType, deviceLoginType)
            } else {
              this.$modal.msg('没有匹配到相对应摄像头！！！')
            }
          })
        } else {
          //海康头
          console.log('haikang')
          const cameraIndexCode = row.cameraCode
          this.$refs.haikangTVWalls.showTVWall(cameraIndexCode, 1)
        }
      })
    },
    /** ----------------------------------摄像头回放结束------------------------------------- */


    /** ----------------------------------大华摄像头预览开始------------------------------------- */
    alertLogin: function() {
      this.$modal.msg('登录中....')
    },
    alertLoginSuccess: function() {
      this.$modal.msgSuccess('登录成功！')
    },
    alertLoginFailed: function() {
      this.$modal.msgError('登陆失败！')
    },
    alertReinstall: function() {
      this.$modal.msgWarning('请重新安装客户端')
    },
    /** 预览按钮操作 */
    preview_dss(cameraCode, cameraName, deviceCode, deviceSn, deviceProtocolType, deviceLoginType) {
      getDahuaVideoServer().then(newResponse => {
        this.ws.detectConnectQt().then(res => {
          console.log('检测连接结果：', res);
          if (res) { // 连接客户端成功
            this.alertLogin()
            this.ws.login({
              loginIp: newResponse.loginIp,
              loginPort: newResponse.loginPort,
              userName: newResponse.userName,
              userPwd: newResponse.userPwd,
              token: '',
              https: 1
            })
            console.log('登录结果：', res);
            this.ws.on('loginState', (res) => {
              this.isLogin = res
              if (res) {
                this.alertLoginSuccess()
                this.activePanel = 'key2'
                // this.realTimeVideoDialog(channelCode)
                let channelList = []
                for (let i = 0; i < cameraCode.length; i++) {
                  let code = { 'channelId': cameraCode }
                  channelList.push(code)
                }
                // 构建参数对象
                let params;
                if (deviceCode === null && deviceSn === null && deviceProtocolType === null && deviceLoginType === null) {
                  params = this.careteListJson(cameraCode, cameraName);
                } else {
                  params = this.careteListJson(cameraCode, cameraName, deviceCode, deviceSn, deviceProtocolType, deviceLoginType);
                }
                // 过滤掉 null 参数
                if (deviceCode === null) delete params.deviceCode
                if (deviceSn === null) delete params.deviceSn
                if (deviceProtocolType === null) delete params.deviceProtocolType
                if (deviceLoginType === null) delete params.deviceLoginType
                this.create(params, channelList, 'dssPreview', 'realMonitorUI')
                this.playRealMonitorVideo(channelList)
              } else {
                this.alertLoginFailed()
              }
            })
          } else { // 连接客户端失败
            this.alertReinstall()
          }
        })
      })
    },
    careteListJson(cameraCode, cameraName, deviceCode=null, deviceSn=null, deviceProtocolType=null, deviceLoginType=null) {
      const treeLabels = [{
        'id': null,
        'labelCode': '999',
        'labelName': '电视墙',
        'cameraType': null,
        'parentLabelCode': ''
      },
        {
          'id': null,
          'labelCode': cameraCode,
          'labelName': cameraName,
          'cameraType': '1',
          'parentLabelCode': '999'
        }]
      const channelDates = []
      for (let i in cameraCode) {
        let currentParams = {
          'channelCode': cameraCode,
          'channelName': cameraName,
          'channelSn': null,
          'cameraType': '1',
          'online': '1',
          'cameraCode': '1'
        };
        if (deviceCode!== null) {
          currentParams.deviceCode = deviceCode;
        }
        if (deviceSn!== null) {
          currentParams.deviceSn = deviceSn;
        }
        if (deviceProtocolType!== null) {
          currentParams.deviceProtocolType = deviceProtocolType;
        }
        if (deviceLoginType!== null) {
          currentParams.deviceLoginType = deviceLoginType;
        }
        channelDates.push(currentParams);
      }
      const labelChannels = [{
        'labelCode': cameraCode,
        'channelDates': channelDates
      }]
      let tvListJson = [{
        'switchTab': '2',
        'treeLabels': treeLabels,
        'labelChannels': labelChannels
      }]
      console.log('11111111111111111111111111', {
        cameraCode, cameraName, deviceCode, deviceSn, deviceProtocolType, deviceLoginType
      })
      return tvListJson
    },
    create(tvListJson, channelList, domId, ctrlType) { // 调用创建控件接口
      let _this = this
      const params = [
        {
          'ctrlType': ctrlType,
          'ctrlCode': 'ctrl1',
          'ctrlProperty': {
            'displayMode': 1,
            'splitNum': 1,
            'channelList': [
              {
                'channelId': ''
              }
            ]
          },
          'visible': true,
          'domId': domId
        }
      ]
      this.setPos(domId)
      this.customizeTree(tvListJson)
      _this.ws.createCtrl(params)
    },
    setPos(domId) {
      let target = document.getElementById(domId)
      target.style.right = `19px`
      target.style.top = `-20px`
      target.style.width = `1070px`
      target.style.height = `700px`
      if (document.createEvent) {
        var event = document.createEvent('HTMLEvents')
        event.initEvent('resize', true, true)
        window.dispatchEvent(event)
      } else if (document.createEventObject) {
        window.fireEvent('onresize')
      }
    },
    destroy() { // 调用销毁控件接口
      if (!this.isLogin) {
        this.$modal.msgWarning('正在登陆客户端，请稍等......')
        return false
      }
      const ctrls = this.ws.ctrls.map(i => {
        if (i.ctrlCode === this.ctrl) {
          return i.ctrlCode
        }
      })
      this.ws.destroyCtrl(ctrls)
    },
    customizeTree(tvListJson) { // 调用控件接口树
      const config = this.ws.config
      const { loginIp, userCode } = config
      this.ws.postMessage('customizeTree', {
        loginIp,
        userCode,
        params: {
          array: tvListJson
        }
      })
    },
    playRealMonitorVideo(array) { // 自定义设备树自动播放指定通道编码视频
      const config = this.ws.config
      const { loginIp, userCode } = config
      this.ws.postMessage('playRealMonitorVideo', {
        loginIp,
        userCode,
        params: {
          ctrlCode: 'ctrl1',
          array: array
        }
      })
    },
    /** ----------------------------------大华摄像头预览结束------------------------------------- */
    /** ----------------------------------大华摄像头回放开始------------------------------------- */
    /** 预览按钮操作 */
    // playBack_dss(channelCode, channelName,cameraCode,cameraName) {
    playBack_dss(cameraCode, cameraName, deviceCode, deviceSn, deviceProtocolType, deviceLoginType) {
      getDahuaVideoServer().then(newResponse => {
        this.ws.detectConnectQt().then(res => {
          if (res) { // 连接客户端成功
            this.alertLogin()
            this.ws.login({
              loginIp: newResponse.loginIp,
              loginPort: newResponse.loginPort,
              userName: newResponse.userName,
              userPwd: newResponse.userPwd,
              token: '',
              https: 1
            })
            this.ws.on('loginState', (res) => {
              this.isLogin = res
              if (res) {
                this.alertLoginSuccess()
                this.activePanel = 'key2'
                let channelList = []
                for (let i = 0; i < cameraCode.length; i++) {
                  let code = { 'channelId': cameraCode }
                  channelList.push(code)
                }
                this.create(this.careteListJson(cameraCode, cameraName, deviceCode, deviceSn, deviceProtocolType, deviceLoginType), channelList, 'dssPreview', 'playbackUI')
              } else {
                this.alertLoginFailed()
              }
            })
          } else { // 连接客户端失败
            this.alertReinstall()
          }
        })
      })
    },
    /** ----------------------------------大华摄像头回放结束------------------------------------- */
    /** ----------------------------------海康摄像头预览开始------------------------------------- */
    /** 预览按钮操作 */
    preview_hik(row) {
      let that = this
      let cameraCode = row.cameraCode
      getHaiKangVideoServer({ cameraCode: cameraCode }).then(newResponse => {
        if (newResponse.code == 200) {
          that.cameraVisible = true
          that.cameraTitle = '摄像头-' + newResponse.data.cameraName
          that.initPlugin(newResponse.data.appkey, newResponse.data.loginIp, newResponse.data.secret, newResponse.data.loginPort)
          setTimeout(function() {
            that.playhk(newResponse.data.channelCode)
          }, 5000)
        }
      })
    },
    replayPreview_hik(row) {
      const cameraCodes = row.cameraCode || this.cameraCodes
      let that = this
      that.cameraVisible = true
      that.cameraTitle = '查看电视墙'
      that.initPluginTvWall()
      setTimeout(function() {
        for (let j = 0; j < cameraCodes.length; j++) {
          getHaiKangVideoServer({ cameraCode: cameraCodes[j] }).then(newResponse => {
            if (newResponse.code == 200) {
              that.playhk(newResponse.data.channelCode)
            }
          })
        }
      }, 3000)
    },
    cancelEventLocationShow() {
      if (this.oWebControl != null) {
        this.oWebControl.JS_HideWnd()   // 先让窗口隐藏，规避可能的插件窗口滞后于浏览器消失问题
        this.oWebControl.JS_Disconnect().then(function() {  // 断开与插件服务连接成功
          },
          function() {  // 断开与插件服务连接失败
          })
      }
      this.cameraIndexCodePlayBack = ''
    },
    /** 回放预览按钮操作 */
    // playBack(row) {
    //   let that = this;
    //   let cameraCode = row.cameraCode;
    //   getHaiKangVideoServer({cameraCode: cameraCode}).then(newResponse => {
    //     if (newResponse.code == 200) {
    //       that.cameraVisiblePlayBack = true
    //       that.cameraTitlePlayBack = '摄像头-回放-' + newResponse.data.cameraName
    //       that.initPluginPlayBack()
    //       this.cameraIndexCodePlayBack = newResponse.data.channelCode
    //     }
    //   })
    // },
    startPlayback() {
      //录像回放功能
      var cameraIndexCode = this.cameraIndexCodePlayBack         //获取输入的监控点编号值，必填
      var startTimeStamp = new Date(this.startTimeStamp).getTime()    //回放开始时间戳，必填
      var endTimeStamp = new Date(this.endTimeStamp).getTime()        //回放结束时间戳，必填
      var recordLocation = 0                                     //录像存储位置：0-中心存储，1-设备存储
      var transMode = 1                                          //传输协议：0-UDP，1-TCP
      var gpuMode = 0                                            //是否启用GPU硬解，0-不启用，1-启用
      var wndId = -1                                             //播放窗口序号（在2x2以上布局下可指定播放窗口）

      this.oWebControl.JS_RequestInterface({
        funcName: 'startPlayback',
        argument: JSON.stringify({
          cameraIndexCode: cameraIndexCode,                   //监控点编号
          startTimeStamp: Math.floor(startTimeStamp / 1000).toString(),  //录像查询开始时间戳，单位：秒
          endTimeStamp: Math.floor(endTimeStamp / 1000).toString(),      //录像结束开始时间戳，单位：秒
          recordLocation: recordLocation,                     //录像存储类型：0-中心存储，1-设备存储
          transMode: transMode,                               //传输协议：0-UDP，1-TCP
          gpuMode: gpuMode,                                   //是否启用GPU硬解，0-不启用，1-启用
          wndId: wndId                                         //可指定播放窗口
        })
      })
    },
    stopAllPlayback() {
      //录像回放停止
      this.oWebControl.JS_RequestInterface({
        funcName: 'stopAllPlayback'
      })
    },
    // 创建播放实例--回放
    initPluginPlayBack() {
      let that = this
      that.oWebControl = new WebControl({
        szPluginContainer: 'playWndPlayBack',                       // 指定容器id
        iServicePortStart: 15900,                           // 指定起止端口号，建议使用该值
        iServicePortEnd: 15909,
        szClassId: '23BF3B0A-2C56-4D97-9C03-0CB103AA8F11',   // 用于IE10使用ActiveX的clsid
        cbConnectSuccess: function() {                     // 创建WebControl实例成功
          that.oWebControl.JS_StartService('window', {         // WebControl实例创建成功后需要启动服务
            dllPath: './VideoPluginConnect.dll'         // 值"./VideoPluginConnect.dll"写死
          }).then(function() {                           // 启动插件服务成功
            that.oWebControl.JS_SetWindowControlCallback({   // 设置消息回调
              cbIntegrationCallBack: cbIntegrationCallBack
            })
            that.oWebControl.JS_CreateWnd('playWndPlayBack', 1020, 600).then(function() { //JS_CreateWnd创建视频播放窗口，宽高可设定
              that.initPlayBack()  // 创建播放实例成功后初始化
            })
          }, function() { // 启动插件服务失败
          })
        },
        cbConnectError: function() { // 创建WebControl实例失败
          that.oWebControl = null
          $('#playWndPlayBack').html('插件未启动，正在尝试启动，请稍候...')
          WebControl.JS_WakeUp('VideoWebPlugin://') // 程序未启动时执行error函数，采用wakeup来启动程序
          initCount++
          if (initCount < 3) {
            setTimeout(function() {
              that.initPluginPlayBack()
            }, 3000)
          } else {
            $('#playWndPlayBack').html('插件启动失败，请检查插件是否安装！')
          }
        },
        cbConnectClose: function(bNormalClose) {
          // 异常断开：bNormalClose = false
          // JS_Disconnect正常断开：bNormalClose = true
          console.log('cbConnectClose')
          that.oWebControl = null
        }
      })
    },
    // 创建播放实例电视墙
    initPluginTvWall() {
      let that = this
      that.oWebControl = new WebControl({
        szPluginContainer: 'playWnd',                       // 指定容器id
        iServicePortStart: 15900,                           // 指定起止端口号，建议使用该值
        iServicePortEnd: 15909,
        szClassId: '23BF3B0A-2C56-4D97-9C03-0CB103AA8F11',   // 用于IE10使用ActiveX的clsid
        cbConnectSuccess: function() {                     // 创建WebControl实例成功
          that.oWebControl.JS_StartService('window', {         // WebControl实例创建成功后需要启动服务
            dllPath: './VideoPluginConnect.dll'         // 值"./VideoPluginConnect.dll"写死
          }).then(function() {                           // 启动插件服务成功
            that.oWebControl.JS_SetWindowControlCallback({   // 设置消息回调
              cbIntegrationCallBack: cbIntegrationCallBack
            })

            that.oWebControl.JS_CreateWnd('playWnd', 1020, 600).then(function() { //JS_CreateWnd创建视频播放窗口，宽高可设定
              that.initTvWall()  // 创建播放实例成功后初始化
            })
          }, function() { // 启动插件服务失败
          })
        },
        cbConnectError: function() { // 创建WebControl实例失败
          that.oWebControl = null
          $('#playWnd').html('插件未启动，正在尝试启动，请稍候...')
          WebControl.JS_WakeUp('VideoWebPlugin://') // 程序未启动时执行error函数，采用wakeup来启动程序
          initCount++
          if (initCount < 3) {
            setTimeout(function() {
              that.initPluginTvWall()
            }, 3000)
          } else {
            $('#playWnd').html('插件启动失败，请检查插件是否安装！')
          }
        },
        cbConnectClose: function(bNormalClose) {
          // 异常断开：bNormalClose = false
          // JS_Disconnect正常断开：bNormalClose = true
          console.log('cbConnectClose')
          that.oWebControl = null
        }
      })
    },
    //初始化回放
    initPlayBack() {
      let that = this
      this.getPubKey(function() {
        ////////////////////////////////// 请自行修改以下变量值	////////////////////////////////////
        var appkey = '24699060'                           //综合安防管理平台提供的appkey，必填
        var secret = that.setEncrypt('tt1pMbsrlwGZUWucdAPw')   //综合安防管理平台提供的secret，必填
        var ip = '36.49.108.22'                           //综合安防管理平台IP地址，必填
        var playMode = 1                                  //初始播放模式：0-预览，1-回放
        var port = 1443                                    //综合安防管理平台端口，若启用HTTPS协议，默认443
        var snapDir = 'D:\\SnapDir'                       //抓图存储路径
        var videoDir = 'D:\\VideoDir'                     //紧急录像或录像剪辑存储路径
        var layout = '1x1'                                //playMode指定模式的布局
        var enableHTTPS = 1                               //是否启用HTTPS协议与综合安防管理平台交互，这里总是填1
        var encryptedFields = 'secret'					   //加密字段，默认加密领域为secret
        var showToolbar = 1                               //是否显示工具栏，0-不显示，非0-显示
        var showSmart = 1                                 //是否显示智能信息（如配置移动侦测后画面上的线框），0-不显示，非0-显示
        var buttonIDs = '0,16,256,257,258,259,260,512,513,514,515,516,517,768,769'  //自定义工具条按钮
        ////////////////////////////////// 请自行修改以上变量值	////////////////////////////////////

        that.oWebControl.JS_RequestInterface({
          funcName: 'init',
          argument: JSON.stringify({
            appkey: appkey,                            //API网关提供的appkey
            secret: secret,                            //API网关提供的secret
            ip: ip,                                    //API网关IP地址
            playMode: playMode,                        //播放模式（决定显示预览还是回放界面）
            port: port,                                //端口
            snapDir: snapDir,                          //抓图存储路径
            videoDir: videoDir,                        //紧急录像或录像剪辑存储路径
            layout: layout,                            //布局
            enableHTTPS: enableHTTPS,                  //是否启用HTTPS协议
            encryptedFields: encryptedFields,          //加密字段
            showToolbar: showToolbar,                  //是否显示工具栏
            showSmart: showSmart,                      //是否显示智能信息
            buttonIDs: buttonIDs                       //自定义工具条按钮
          })
        }).then(function(oData) {
          that.oWebControl.JS_Resize(1020, 600)  // 初始化后resize一次，规避firefox下首次显示窗口后插件窗口未与DIV窗口重合问题
        })
      })
    },
    //初始化电视墙
    initTvWall() {
      let that = this
      this.getPubKey(function() {
        ////////////////////////////////// 请自行修改以下变量值	////////////////////////////////////
        var appkey = '24699060'                           //综合安防管理平台提供的appkey，必填
        var secret = that.setEncrypt('tt1pMbsrlwGZUWucdAPw')   //综合安防管理平台提供的secret，必填
        var ip = '36.49.108.22'                           //综合安防管理平台IP地址，必填
        var playMode = 0                                  //初始播放模式：0-预览，1-回放
        var port = 1443                                    //综合安防管理平台端口，若启用HTTPS协议，默认443
        var snapDir = 'D:\\SnapDir'                       //抓图存储路径
        var videoDir = 'D:\\VideoDir'                     //紧急录像或录像剪辑存储路径
        var layout = '3x3'                                //playMode指定模式的布局
        var enableHTTPS = 1                               //是否启用HTTPS协议与综合安防管理平台交互，这里总是填1
        var encryptedFields = 'secret'					   //加密字段，默认加密领域为secret
        var showToolbar = 1                               //是否显示工具栏，0-不显示，非0-显示
        var showSmart = 1                                 //是否显示智能信息（如配置移动侦测后画面上的线框），0-不显示，非0-显示
        var buttonIDs = '0,16,256,257,258,259,260,512,513,514,515,516,517,768,769'  //自定义工具条按钮
        ////////////////////////////////// 请自行修改以上变量值	////////////////////////////////////

        that.oWebControl.JS_RequestInterface({
          funcName: 'init',
          argument: JSON.stringify({
            appkey: appkey,                            //API网关提供的appkey
            secret: secret,                            //API网关提供的secret
            ip: ip,                                    //API网关IP地址
            playMode: playMode,                        //播放模式（决定显示预览还是回放界面）
            port: port,                                //端口
            snapDir: snapDir,                          //抓图存储路径
            videoDir: videoDir,                        //紧急录像或录像剪辑存储路径
            layout: layout,                            //布局
            enableHTTPS: enableHTTPS,                  //是否启用HTTPS协议
            encryptedFields: encryptedFields,          //加密字段
            showToolbar: showToolbar,                  //是否显示工具栏
            showSmart: showSmart,                      //是否显示智能信息
            buttonIDs: buttonIDs                       //自定义工具条按钮
          })
        }).then(function(oData) {
          that.oWebControl.JS_Resize(1020, 600)  // 初始化后resize一次，规避firefox下首次显示窗口后插件窗口未与DIV窗口重合问题
        })
      })
    },
    // 创建播放实例
    initPlugin(newappkey, newloginIp, newsecret, newloginPort) {
      let that = this
      that.oWebControl = new WebControl({
        szPluginContainer: 'playWnd',                       // 指定容器id
        iServicePortStart: 15900,                           // 指定起止端口号，建议使用该值
        iServicePortEnd: 15909,
        szClassId: '23BF3B0A-2C56-4D97-9C03-0CB103AA8F11',   // 用于IE10使用ActiveX的clsid
        cbConnectSuccess: function() {                     // 创建WebControl实例成功
          that.oWebControl.JS_StartService('window', {         // WebControl实例创建成功后需要启动服务
            dllPath: './VideoPluginConnect.dll'         // 值"./VideoPluginConnect.dll"写死
          }).then(function() {                           // 启动插件服务成功
            that.oWebControl.JS_SetWindowControlCallback({   // 设置消息回调
              cbIntegrationCallBack: cbIntegrationCallBack
            })

            that.oWebControl.JS_CreateWnd('playWnd', 1020, 600).then(function() { //JS_CreateWnd创建视频播放窗口，宽高可设定
              that.init(newappkey, newloginIp, newsecret, newloginPort)  // 创建播放实例成功后初始化
            })
          }, function() { // 启动插件服务失败
          })
        },
        cbConnectError: function() { // 创建WebControl实例失败
          that.oWebControl = null
          $('#playWnd').html('插件未启动，正在尝试启动，请稍候...')
          WebControl.JS_WakeUp('VideoWebPlugin://') // 程序未启动时执行error函数，采用wakeup来启动程序
          initCount++
          if (initCount < 3) {
            setTimeout(function() {
              that.initPlugin(newappkey, newloginIp, newsecret, newloginPort)
            }, 3000)
          } else {
            $('#playWnd').html('插件启动失败，请检查插件是否安装！<a href="./public/hk/VideoWebPlugin.exe">点击下载插件</a>')
          }
        },
        cbConnectClose: function(bNormalClose) {
          // 异常断开：bNormalClose = false
          // JS_Disconnect正常断开：bNormalClose = true
          console.log('cbConnectClose')
          that.oWebControl = null
        }
      })
    },
    //播放海康摄像头
    playhk(channelCode) {
      var cameraIndexCode = channelCode     //获取输入的监控点编号值，必填
      var streamMode = 0                                     //主子码流标识：0-主码流，1-子码流
      var transMode = 1                                      //传输协议：0-UDP，1-TCP
      var gpuMode = 0                                        //是否启用GPU硬解，0-不启用，1-启用
      var wndId = -1                                         //播放窗口序号（在2x2以上布局下可指定播放窗口）

      cameraIndexCode = cameraIndexCode.replace(/(^\s*)/g, '')
      cameraIndexCode = cameraIndexCode.replace(/(\s*$)/g, '')

      this.oWebControl.JS_RequestInterface({
        funcName: 'startPreview',
        argument: JSON.stringify({
          cameraIndexCode: cameraIndexCode,                //监控点编号
          streamMode: streamMode,                         //主子码流标识
          transMode: transMode,                           //传输协议
          gpuMode: gpuMode,                               //是否开启GPU硬解
          wndId: wndId                                     //可指定播放窗口
        })
      })
    },
    //初始化
    init(newappkey, newloginIp, newsecret, newloginPort) {
      let that = this
      that.getPubKey(function() {
        ////////////////////////////////// 请自行修改以下变量值	////////////////////////////////////
        var appkey = newappkey                           //综合安防管理平台提供的appkey，必填
        var secret = that.setEncrypt(newsecret)   //综合安防管理平台提供的secret，必填
        var ip = newloginIp                           //综合安防管理平台IP地址，必填
        var playMode = 0                                  //初始播放模式：0-预览，1-回放
        var port = Number(newloginPort)                                    //综合安防管理平台端口，若启用HTTPS协议，默认443
        var snapDir = 'D:\\SnapDir'                       //抓图存储路径
        var videoDir = 'D:\\VideoDir'                     //紧急录像或录像剪辑存储路径
        var layout = '1x1'                                //playMode指定模式的布局
        var enableHTTPS = 1                               //是否启用HTTPS协议与综合安防管理平台交互，这里总是填1
        var encryptedFields = 'secret'					   //加密字段，默认加密领域为secret
        var showToolbar = 1                               //是否显示工具栏，0-不显示，非0-显示
        var showSmart = 1                                 //是否显示智能信息（如配置移动侦测后画面上的线框），0-不显示，非0-显示
        var buttonIDs = '0,16,256,257,258,259,260,512,513,514,515,516,517,768,769'  //自定义工具条按钮
        ////////////////////////////////// 请自行修改以上变量值	////////////////////////////////////

        that.oWebControl.JS_RequestInterface({
          funcName: 'init',
          argument: JSON.stringify({
            appkey: appkey,                            //API网关提供的appkey
            secret: secret,                            //API网关提供的secret
            ip: ip,                                    //API网关IP地址
            playMode: playMode,                        //播放模式（决定显示预览还是回放界面）
            port: port,                                //端口
            snapDir: snapDir,                          //抓图存储路径
            videoDir: videoDir,                        //紧急录像或录像剪辑存储路径
            layout: layout,                            //布局
            enableHTTPS: enableHTTPS,                  //是否启用HTTPS协议
            encryptedFields: encryptedFields,          //加密字段
            showToolbar: showToolbar,                  //是否显示工具栏
            showSmart: showSmart,                      //是否显示智能信息
            buttonIDs: buttonIDs                       //自定义工具条按钮
          })
        }).then(function(oData) {
          that.oWebControl.JS_Resize(1020, 600)  // 初始化后resize一次，规避firefox下首次显示窗口后插件窗口未与DIV窗口重合问题
        })
      })
    },
    //获取公钥
    getPubKey(callback) {
      let that = this
      that.oWebControl.JS_RequestInterface({
        funcName: 'getRSAPubKey',
        argument: JSON.stringify({
          keyLength: 1024
        })
      }).then(function(oData) {
        console.log(oData)
        if (oData.responseMsg.data) {
          that.pubKey = oData.responseMsg.data
          callback()
        }
      })
    },
//RSA加密
    setEncrypt(value) {
      var encrypt = new JSEncrypt()
      encrypt.setPublicKey(this.pubKey)
      return encrypt.encrypt(value)
    },
    hikDisconnect() {
      console.log('111')
      let that = this
      if (that.oWebControl != null) {
        that.oWebControl.JS_HideWnd()   // 先让窗口隐藏，规避可能的插件窗口滞后于浏览器消失问题
        that.oWebControl.JS_Disconnect().then(function() {
        }, function() {
        })  // 断开与插件服务连接成功 // 断开与插件服务连接失败
      }
    },
    /** ----------------------------------海康摄像头预览结束------------------------------------- */

    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          //如果后台报错：比如IP重复，需要将原来的form.list 赋值回去，否则再次点击保存时，form.list值已经改变，上面的for循环会出问题
          let old_form_list = this.form.list
          let list = []
          for (let item in this.form.list) {
            for (let items in this.cameraSystemList) {
              if (this.cameraSystemList[items].value == this.form.list[item]) {
                const yongtu = {}
                yongtu.type = this.cameraSystemList[items].value
                yongtu.typeName = this.cameraSystemList[items].label
                list.push(yongtu)
              }
            }
          }
          let that = this
          that.form.list = list
          if (that.form.id != null) {
            that.form.cameraImages = this.form.cameraImagesList ? typeof this.form.cameraImagesList == 'string' ? this.form.cameraImagesList.split(',') : this.form.cameraImagesList : []
            that.form.cameraImagesList = []
            updateCamera(that.form).then(response => {
              that.$modal.msgSuccess('修改成功')
              that.open = false
              that.getList()
            }).catch((error) => {
              //如果后台报错：比如IP重复，需要将原来的form.list 赋值回去，否则再次点击保存时，form.list值已经改变，上面的双层for循环会出问题
              that.form.list = old_form_list
            })
          } else {
            that.form.cameraImages = this.form.cameraImagesList ? typeof this.form.cameraImagesList == 'string' ? this.form.cameraImagesList.split(',') : this.form.cameraImagesList : []
            that.form.cameraImagesList = []
            addCamera(this.form).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
              this.resetForm('form')
            }).catch((error) => {
              //如果后台报错：比如IP重复，需要将原来的form.list 赋值回去，否则再次点击保存时，form.list值已经改变，上面的双层for循环会出问题
              this.form.list = old_form_list
            })
          }
        }
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('sooka-sponest-center-monitor/camera/export', {
        ...this.queryParams
      }, `camera_${new Date().getTime()}.xlsx`)
    },
    synchronizeCamera() {
      let that = this
      that.loading = true
      that.$modal.msgSuccess('开始同步')
      synchronizeOfflineCamera().then(function(res) {
        if (res.code == 200) {
          that.loading = false
          that.$modal.msgSuccess('设备状态同步成功')
          that.getList()
        } else {
          that.loading = false
          that.$modal.warn('设备状态同步失败')
        }
      })
    }
  }
}

// 推送消息
function cbIntegrationCallBack(oData) {
  console.log(JSON.stringify(oData.responseMsg))
}
</script>


<style rel="stylesheet/scss" lang="scss">
//视频摄像头预览弹层样式
.videoCustomWidth {
  width: 1070px !important;
  height: 760px !important;
}

//视频摄像头预览弹层样式
.videoCustomWidthPlayBack {
  width: 1080px !important;
  height: 780px !important;
}
</style>
