<template>
  <div @click="contentSearchShow = false">
    <el-row :gutter="20" class="elrow">
      <el-col :span="24">
        <el-card shadow="hover">
          <el-row>
            <el-col :span="colNum_6">
              <div class="grid-content grid-con-2">
                <div class="colposition">
                  <img src="../assets/img/mszssbgl.png" class="w100" alt="" />
                  <div class="grid-cont-right">
                    <div>设备总数</div>
                    <!-- <div class="grid-num">{{ sumpageTotal }}</div> -->
                    <div class="font-size-24 grid-num">
                      <NumberGrow :value="sumpageTotal" class="color-333"></NumberGrow>
                    </div>
                  </div>
                </div>
              </div>
            </el-col>
            <el-col :span="colNum_6" class="">
              <div class="grid-content grid-con-2">
                <div class="colposition">
                  <img src="../assets/img/mszssbgl.png" class="w100" alt="" />
                  <div class="grid-cont-right">
                    <div>绑定数量</div>
                    <!-- <div class="grid-num">{{ analysisData.bingSite }}</div> -->
                    <div class="font-size-24 grid-num">
                      <NumberGrow :value="analysisData.bingSite" class="color-333"></NumberGrow>
                    </div>
                  </div>
                </div>
              </div>
            </el-col>
            <el-col :span="colNum_6" class="">
              <div class="grid-content grid-con-2">
                <div class="colposition">
                  <img src="../assets/img/mszssbgl.png" class="w100" alt="" />
                  <div class="grid-cont-right">
                    <div>常开数量</div>
                    <!-- <div class="grid-num">{{ analysisData.isAlwaysOpen }}</div> -->
                    <div class="font-size-24 grid-num">
                      <NumberGrow :value="analysisData.isAlwaysOpen" class="color-333"></NumberGrow>
                    </div>
                  </div>
                </div>
              </div>
            </el-col>
            <el-col :span="colNum_6" class="">
              <div class="grid-content grid-con-2">
                <div class="colposition">
                  <img src="../assets/img/mszssbgl.png" class="w100" alt="" />
                  <div class="grid-cont-right">
                    <div>报警数量</div>
                    <div class="grid-num">0</div>
                  </div>
                </div>
              </div>
            </el-col>
            <el-col :span="colNum_6" class="">
              <div class="grid-content grid-con-2">
                <div class="colposition">
                  <img src="../assets/img/mszssbgl.png" class="w100" alt="" />
                  <div class="grid-cont-right">
                    <div>到期数量</div>
                    <div class="grid-num">0</div>
                  </div>
                </div>
              </div>
            </el-col>
            <el-col :span="colNum_6" class="">
              <div class="grid-content grid-con-2">
                <div class="colposition">
                  <img src="../assets/img/mszssbgl.png" class="w100" alt="" />
                  <div class="grid-cont-right">
                    <div>低电数量</div>
                    <!-- <div class="grid-num">{{ lowBattery }}</div> -->
                    <div class="font-size-24 grid-num">
                      <NumberGrow :value="lowBattery" class="color-333"></NumberGrow>
                    </div>
                  </div>
                </div>
              </div>
            </el-col>
            <el-col :span="colNum_6" class="">
              <div class="grid-content grid-con-2">
                <div class="colposition">
                  <img src="../assets/img/wifisbgl.png" class="w100" alt="" />
                  <div class="grid-cont-right">
                    <div>在线状态</div>
                    <!-- <div class="grid-num">{{ online }}</div> -->
                    <div class="font-size-24 grid-num">
                      <NumberGrow :value="online" class="color-333"></NumberGrow>
                    </div>
                  </div>
                </div>
              </div>
            </el-col>
            <el-col :span="colNum_6" class="">
              <div class="grid-content grid-con-2">
                <div class="colposition">
                  <img src="../assets/img/wifisbgl1.png" class="w100" alt="" />
                  <div class="grid-cont-right">
                    <div>异常状态</div>
                    <!-- <div class="grid-num">{{ abnormal }}</div> -->
                    <div class="font-size-24 grid-num">
                      <NumberGrow :value="abnormal" class="color-333"></NumberGrow>
                    </div>
                  </div>
                </div>
              </div>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
    </el-row>
    <div class="container">
      <div class="handle-box">
        <selectoption></selectoption>
        <el-cascader :options="options" size="small" :props="{ checkStrictly: true }" v-model="searchRoom"
          @change="checkNode" :clearable="true">
        </el-cascader>
        <el-input v-model="search.roomname" size="small" placeholder="房间名称" :clearable="true" @input="changesr($event)"
          class="handle-input mr10 width100">
        </el-input>
        <el-select v-model="search.isOnline" size="small" placeholder="设备状态" class="handle-select mr10" :clearable="true">
          <el-option key="1" label="离线" value="0"></el-option>
          <el-option key="2" label="在线" value="1"></el-option>
          <el-option key="3" label="异常" value="2"></el-option>
        </el-select>
        <el-button type="primary" size="small" class="mr10 my-2" icon="el-icon-search" @click="handleSearch"
          style="background: #FA8E00; border: none;">搜索</el-button>
        <el-button type="primary" size="small" class="mr10 my-2" @click="restSearch"
          style="background: #FA8E00; border: none;">重置搜索</el-button>
        <div class="position-father" @click.stop="contentSearchShow = true">
          <div class="el-button mountClickObject el-button--primary mr10 el-button--small"
            @click.stop="contentSearchShow = !contentSearchShow" style="background: #FA8E00; border: none;">
            高级查询</div>
          <div class="contentSearch" v-if="contentSearchShow" id="contentSearch" @click.stop="contentSearchShow = true">
            <el-input v-model="search.deviceNum" size="small" placeholder="设备名称" :clearable="true"
              @input="changesr($event)" class="handle-input width100">
            </el-input>
            <el-input v-model="search.imei" size="small" placeholder="IMEI" :clearable="true" @input="changesr($event)"
              class="handle-input width100">
            </el-input>
            <el-select v-model="search.isUsed" size="small" placeholder="请选择" :clearable="true" class="width100">
              <el-option key="" label="全部" value="">
              </el-option>
              <el-option key="0" label="未初始化" value="0">
              </el-option>
              <el-option key="1" label="初始化" value="1">
              </el-option>
            </el-select>
            <el-select v-model="search.unBind" size="small" placeholder="绑定状态" class="handle-select width100"
              :clearable="true">
              <el-option key="0" label="已绑定" value="0"></el-option>
              <el-option key="1" label="未绑定" value="1"></el-option>
            </el-select>
            <el-input v-model="search.iccid" size="small" placeholder="ICCID" :clearable="true" @input="changesr($event)"
              class="handle-input width100">
            </el-input>
            <el-input v-model="search.firmwareVersion" size="small" placeholder="版本号" :clearable="true"
              @input="changesr($event)" class="handle-input width100">
            </el-input>
            <el-date-picker v-model="search.createStart" class="width100" size="small" type="datetime"
              placeholder="选设备上线开始时间" default-time="00:00:00">
            </el-date-picker>
            <el-date-picker v-model="search.createEnd" class="width100" size="small" type="datetime" placeholder="选择结束时间"
              default-time="00:00:00">
            </el-date-picker>
            <div class="quantity width100">
              电量： <el-input placeholder="" v-model="search.startBattery" :clearable="true"
                @input="InputFun($event, 'startBattery')" class="w50" size="mini">
                <template slot="append">%</template>
              </el-input> - <el-input placeholder="" v-model="search.endBattery" :clearable="true"
                @input="InputFun($event, 'endBattery')" class="w50" size="mini">
                <template slot="append">%</template>
              </el-input>
            </div>
            <div class="quantity width100">
              信号： <el-input placeholder="" v-model="search.rssiStart" :clearable="true"
                @input="InputFun($event, 'rssiStart')" class="w50" size="mini">
                <template slot="append">%</template>
              </el-input> - <el-input placeholder="" v-model="search.rssiEnd" :clearable="true"
                @input="InputFun($event, 'rssiEnd')" class="w50" size="mini">
                <template slot="append">%</template>
              </el-input>
            </div>
            <div class="searchbutton">
              <el-button type="primary" size="small" @click.stop="handleSearch"
                style="background: #FA8E00; border: none;">高级搜索</el-button>
              <el-button type="primary" size="small" @click.stop="restSearch"
                style="background: #FA8E00; border: none;">重置搜索</el-button>
            </div>
          </div>
        </div>
        <el-button type="primary" size="small" @click="addequipment" v-if="userInfo.type == 0"
          style="background: #FA8E00; border: none;">添加设备</el-button>
        <el-button type="primary" size="small" @click="BatchAdd" v-if="userInfo.type == 0"
          style="background: #FA8E00; border: none;">批量添加</el-button>
        <el-button type="primary" size="small" @click="batchInit" v-if="userInfo.type == 0"
          style="background: #FA8E00; border: none;">批量初始化</el-button>
        <el-button type="primary" size="small" @click="exportDeviceOrderMethods"
          style="background: #FA8E00; border: none;">导出列表</el-button>
        <!--        <el-button type="primary" size="small" @click="batchRemoteUnlocking" v-show="userInfo.type == 0">批量远程开锁-->
        <!--        </el-button>-->
        <el-button type="primary" size="small" @click="batchSetOpenMethods"
          style="background: #FA8E00; border: none;">批量设置常开
        </el-button>
        <el-button type="primary" size="small" @click="refreshFun" v-show="userInfo.type == 0"
          style="background: #FA8E00; border: none;">同步设备信息</el-button>
        <!-- <el-button type="primary" size="small" @click="syncCommands" v-show="userInfo.type == 0">同步有效凭证</el-button> -->
      </div>
      <div class="switchiconfont">
        <i class="iconfont httpicon-liebiao1" :class="activeiconfont ? 'active' : ''" @click="activeiconfun(true)"
          title="切换方块展示"></i>
        <i class="iconfont httpicon-liebiao" :class="activeiconfont ? '' : 'active'" @click="activeiconfun(false)"
          title="切换表格展示"></i>
      </div>
      <div class="roomcontent" v-if="activeiconfont">
        <div class="roomconli" v-for="(item, index) in tableData" :key="index">
          <deviceLi :data="item" :src="deviceImg"></deviceLi>
          <div class="button-list">
            <div @click="unbindsave(index, item)" v-if="item.roomId ? true : false">
              解绑房间
            </div>
            <div @click="bindRoom(index, item)" v-else>绑定房间</div>
            <div @click="detailsFun(index, item)">门锁操作</div>
            <div @click="AddAdministrator(index, item)" v-if="item.manufactureId == 101">初始化</div>
            <div @click="getEmergence(index, item)" v-if="item.manufactureId == 201 || item.manufactureId == 221">临时密码
            </div>
            <div @click="deleteLock(index, item)" v-show="userInfo.type == 0">删除</div>
            <div @click="RemoteUnlocking(index, item)" v-if="item.manufactureId == 101">远程开锁</div>
            <div @click="Reset(index, item)">重置门锁</div>
          </div>
        </div>
      </div>
      <el-table :data="tableData" border stripe class="table" ref="multipleTable" header-cell-class-name="table-header"
        @selection-change="handleSelectionChange" empty-text="无" v-else height="450">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="deviceNum" label="设备号" width="200"></el-table-column>
        <el-table-column prop="accessPlatformText" label="锁平台"></el-table-column>
        <el-table-column prop="manufactureIdText" label="设备类型" width="100"></el-table-column>
        <el-table-column prop="imei" label="IMEI" width="150">
          <template slot-scope="scope">
            <span class="" v-if="scope.row.imei">{{ scope.row.imei }}</span>
            <span class="" v-else>空</span>
          </template>
        </el-table-column>
        <el-table-column prop="imsi" label="IMSI" width="150">
          <template slot-scope="scope">
            <span class="" v-if="scope.row.imsi">{{ scope.row.imsi }}</span>
            <span class="" v-else>空</span>
          </template>
        </el-table-column>
        <el-table-column prop="iccid" label="ICCID" width="180">
          <template slot-scope="scope">
            <span class="" v-if="scope.row.iccid">{{ scope.row.iccid }}</span>
            <span class="" v-else>空</span>
          </template>
        </el-table-column>
        <el-table-column prop="" label="信号强度" width="150">
          <template slot-scope="scope">
            <i class="iconfont httpicon-xinhao38 red" v-if="scope.row.rssi <= 10"></i>
            <i class="iconfont httpicon-xinhao38 orange" v-else-if="10 < scope.row.rssi && scope.row.rssi < 20"></i>
            <i class="iconfont httpicon-xinhao38 green" v-else-if="20 <= scope.row.rssi && scope.row.rssi <= 100"></i>
            <i class="iconfont httpicon-wuxinhao red" v-else></i><span class="spanli dling">
              {{ scope.row.rssi || 0 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="电量">
          <template slot-scope="scope">
            <i class="iconfont httpicon-dianchi-didianliang red" v-if="scope.row.battery <= 15"></i>
            <i class="iconfont httpicon-icon-test orange"
              v-else-if="15 < scope.row.battery && scope.row.battery < 60"></i>
            <i class="iconfont httpicon-icon-test green"
              v-else-if="60 <= scope.row.battery && scope.row.battery <= 100"></i>
            <i class="iconfont httpicon-icon-test red" v-else></i><span class="spanli dling"> {{ scope.row.battery || 0
            }}%</span>
          </template>
        </el-table-column>
        <el-table-column label="在线状态" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.isOnline == '1'
              ? 'success'
              : scope.row.isOnline == '0'
                ? 'danger'
                : ''
              "><span v-if="scope.row.isOnline == 1">在线</span>
              <span v-else>离线</span>
            </el-tag>
          </template>
        </el-table-column>
        <!-- <el-table-column label="门的状态">
          <template slot-scope="scope">
            <i class="iconfont httpicon-men" v-if="scope.row.lockStatus == 0"></i>
            <i class="iconfont httpicon-mendoor13" v-if="scope.row.lockStatus == 1"></i>
            <i class="iconfont httpicon-men" style="color: red" v-if="scope.row.lockStatus == 2"></i>
          </template>
        </el-table-column> -->
        <el-table-column label="绑定房间" width="200">
          <template slot-scope="scope">
            <span class="blue" v-if="scope.row.roomName">{{
              scope.row.roomName
            }}</span>
            <span class="" v-else>空</span>
          </template>
        </el-table-column>
        <el-table-column prop="firmwareVersion" label="版本" width="160"></el-table-column>
        <el-table-column prop="createAt" label="注册时间" width="160"></el-table-column>
        <el-table-column prop="lastReportAt" label="上线时间" width="160"></el-table-column>
        <el-table-column label="操作" width="500" align="center">
          <template #default="scope">
            <el-button type="text" @click="unbindsave(scope.$index, scope.row)" v-if="scope.row.roomId" class="red">解绑房间
            </el-button>
            <el-button type="text" v-else @click="bindRoom(scope.$index, scope.row)">绑定房间</el-button>
            <el-button type="text" @click="detailsFun(scope.$index, scope.row)">门锁操作</el-button>
            <el-button type="text" @click="AddAdministrator(scope.$index, scope.row)"
              v-if="scope.row.manufactureId == 101 && userInfo.type == 0">初始化
            </el-button>
            <el-button type="text" class="red" @click="deleteLock(scope.$index, scope.row)" v-show="userInfo.type == 0">
              删除</el-button>
            <el-button type="text" class="red" @click="getEmergence(scope.$index, scope.row)">临时密码
            </el-button>
            <el-button type="text" @click="RemoteUnlocking(scope.$index, scope.row)"
              v-if="scope.row.manufactureId == 101">远程开锁 </el-button>
            <el-button type="text" @click="Reset(scope.$index, scope.row)">重置门锁</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination @size-change="handleSizeChange" @current-change="handlePageChange"
          :current-page="normallyPageNum" :page-sizes="[10, 20, 100]" :page-size="pageSize"
          :layout="paginationConfig" :total="pageTotal">
        </el-pagination>
      </div>
    </div>
    <!-- 绑定房间 -->
    <el-dialog title="绑定房间" :visible.sync="roomVisible" width="30%">
      <div class="ztree">
        <el-tree :data="zNodes" show-checkbox node-key="id" ref="tree" @check-change="handleCheckChange"
          :props="defaultProps"></el-tree>

      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="roomVisible = false">取 消</el-button>
          <el-button type="primary" @click="bindsave">确 定</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 远程开锁输入密码 -->
    <el-dialog title="远程开锁密码" :visible.sync="Unlocking" width="30%">
      <div>
        <el-form ref="locking" :model="lockingform" label-width="100px">
          <el-form-item label="管理员密码">
            <el-input v-model="lockingform.password" show-password :clearable="true"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="Unlocking = false" size="middle">取 消</el-button>
          <el-button type="primary" @click="Unlockingsave" size="middle">确 定</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 编辑弹出框 -->
    <el-dialog title="编辑" :visible.sync="editVisible" width="30%">
      <el-form ref="form" :model="form" label-width="100px">
        <el-form-item label="型号">
          <el-select v-model="form.manufacturer" size="middle" placeholder="请选择">
            <el-option v-for="item in manufacturerList" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <div v-if="form.manufacturer == 101 || form.manufacturer == 1201 || form.manufacturer == 1241">
          <el-form-item label="设备号">
            <el-input v-model="form.deviceNum" size="middle" :clearable="true"></el-input>
          </el-form-item>
          <el-form-item label="IMEI">
            <el-input v-model="form.imei" size="middle" :clearable="true"></el-input>
          </el-form-item>
          <el-form-item label="超管ID">
            <el-input v-model="form.lockerSuperAdminId" size="middle" :clearable="true"></el-input>
          </el-form-item>
          <el-form-item label="MAC">
            <el-input v-model="form.lockMac" size="middle" :clearable="true"></el-input>
          </el-form-item>
          <el-form-item label="运营商">
            <el-select v-model="form.platformId" size="middle" placeholder="请选择">
              <el-option v-for="item in accessPlatform.select" :key="item.code" :label="item.desc" :value="item.code">
              </el-option>
            </el-select>
          </el-form-item>
        </div>
        <div v-else-if="form.manufacturer == 201 || form.manufacturer == 221">
          <el-form-item label="设备号">
            <el-input v-model="form.lockerId" size="middle" :clearable="true"></el-input>
          </el-form-item>
          <el-form-item label="IMEI">
            <el-input v-model="form.imei" size="middle" :clearable="true"></el-input>
          </el-form-item>
          <el-form-item label="超管名称">
            <el-input v-model="form.lockerSuperAdminId" size="middle" :clearable="true"></el-input>
          </el-form-item>
          <el-form-item label="超管密码">
            <el-input v-model="form.authKey" size="middle" :clearable="true"></el-input>
          </el-form-item>
          <el-form-item label="客户码">
            <el-input v-model="form.customerCode" size="middle" :clearable="true"></el-input>
          </el-form-item>
          <el-form-item label="连接方式">
            <el-select v-model="form.type" placeholder="请选择" size="middle">
              <el-option key="0" label="直连" value="0"></el-option>
              <el-option key="1" label="aep" value="1"></el-option>
            </el-select>
          </el-form-item>
        </div>
        <el-form-item label="选择房间">
          <el-cascader :options="options" size="middle" :props="{ checkStrictly: true }" @change="checkNodeOne"
            v-model="checkNodeId1" clearable>
          </el-cascader>
        </el-form-item>
        <div
          v-if="form.manufacturer == 701 || form.manufacturer == 702 || form.manufacturer == 703 || form.manufacturer == 704 || form.manufacturer == 705 || form.manufacturer == 706 || form.manufacturer == 707">
          <el-form-item label="设备号">
            <el-input v-model="form.deviceNum" size="middle" :clearable="true"></el-input>
          </el-form-item>
          <el-form-item label="设备验证码">
            <el-input v-model="form.validateCode" size="small" :clearable="true"></el-input>
          </el-form-item>
        </div>
        <div v-else-if="form.manufacturer == 1241">
          <el-form-item label="设备号">
            <el-input v-model="form.deviceNum" size="middle" :clearable="true"></el-input>
          </el-form-item>
        </div>
        <!-- <el-form-item label="选择房间">
          <el-cascader :options="options" size="middle" :props="{ checkStrictly: true }" @change="checkNodeOne"
            v-model="checkNodeId1" clearable>
          </el-cascader>
        </el-form-item> -->
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editVisible = false" size="small">取 消</el-button>
          <el-button type="primary" @click="initialization" size="small">确 定</el-button>
        </span>
      </template>
    </el-dialog>
    <el-drawer title="" :visible.sync="drawer" custom-class="operationclass position-relative" :show-close="false"
      :size="drawerSize" :before-close="handleClose">
      <div class="position-absolute left-15 top-10 color-666" style="width: 40px;cursor: pointer;" @click="handleClose">
        <img src="../assets/img/leftjt.svg" alt="" class="width-percentage-100">
      </div>
      <div class="rltable">
        <el-tabs v-model="activeName" border @tab-click="handleClick">
          <el-tab-pane label="门锁详情" name="0">
            <el-form :inline="true" :model="formInline" class="demo-form-inline">
              <el-form-item label="设备号:">
                <span class="half">{{ formInline.deviceNum }}</span>
              </el-form-item>
              <el-form-item label="IMEI:">
                <span class="half">{{ formInline.imei }}</span>
              </el-form-item>
              <el-form-item label="IMSI:">
                <span class="half">{{ formInline.imsi }}</span>
              </el-form-item>
              <el-form-item label="ICCID:">
                <span class="half">{{ formInline.iccid }}</span>
              </el-form-item>
              <el-form-item label="信号强度:">
                <span class="half">{{ formInline.rssi }}</span>
              </el-form-item>
              <el-form-item label="电池电量:">
                <span class="half">{{ formInline.battery }}</span>
              </el-form-item>
              <el-form-item label="在线状态:">
                <span class="half" v-if="formInline.isOnline == 1">在线</span>
                <span class="half" v-else>离线</span>
              </el-form-item>
              <!--  <el-form-item label="门的状态:">
                <span class="half" v-if="formInline.lockStatus == 0">关闭</span>
                <span class="half" v-if="formInline.lockStatus == 1">打开</span>
                <span class="half" v-if="formInline.lockStatus == 2">异常</span>
              </el-form-item> -->
              <el-form-item label="绑定房间:">
                <span class="half">{{ formInline.roomName }}</span>
              </el-form-item>
              <el-form-item label="注册时间:">
                <span class="half">{{ formInline.createAt }}</span>
              </el-form-item>
              <el-form-item label="上线时间:">
                <span class="half">{{ formInline.lastReportAt }}</span>
              </el-form-item>
              <el-form-item label="音量:">
                <el-radio-group v-model="formInline.volumeLevel" @input="stepFun" size="mini"
                  v-if="formInline.manufactureId == 101">
                  <el-radio-button label="0">静音</el-radio-button>
                  <el-radio-button label="1">低音</el-radio-button>
                  <el-radio-button label="2">高音</el-radio-button>
                </el-radio-group>
                <el-radio-group v-model="formInline.volumeLevel" disabled size="mini"
                  v-if="formInline.manufactureId == 201 || formInline.manufactureId == 221">
                  <el-radio-button label="0">静音</el-radio-button>
                  <el-radio-button label="1">低音</el-radio-button>
                  <el-radio-button label="2">高音</el-radio-button>
                </el-radio-group>
              </el-form-item>
              <!--              <el-form-item label="常开设置:" v-if="formInline.manufactureId==101">-->
              <!--                <el-switch v-model="formInline.isAlwaysOpenStatus" :inactive-text="switchtext" @change="switchFun">-->
              <!--                </el-switch>-->
              <!--              </el-form-item>-->
              <!--              <el-form-item label="常开状态:" v-if="formInline.manufactureId==201">-->
              <!--                <el-switch v-model="formInline.isAlwaysOpenStatus" :inactive-text="switchtext" disabled>-->
              <!--                </el-switch>-->
              <!--              </el-form-item>-->
              <el-form-item label="数据同步:">
                <!-- <el-input size="mini" placeholder="请填写需要同步数据过来的锁号" v-model="synchroLockNumber" style="display: inline-block;width: 200px;"></el-input> -->
                <el-button type="text" size="mini" @click="dataSynchronization(1, formInline)">数据同步</el-button>
              </el-form-item>
            </el-form>
            <!--            <el-form :mode="formInline" class="">-->
            <!--              <el-form-item label="常开设置:" v-if="formInline.manufactureId==201">-->
            <!--                &lt;!&ndash; <el-switch v-model="value1" :inactive-text="switchtext" @change="switchFun">-->
            <!--                </el-switch> &ndash;&gt;-->
            <!--                <el-date-picker v-model="opendTime" type="daterange" range-separator="至" class="w-250"-->
            <!--                  start-placeholder="开始日期" end-placeholder="结束日期" size="mini">-->
            <!--                </el-date-picker>-->
            <!--                <el-select v-model="startHour" size="mini" placeholder="选择开始时间段">-->
            <!--                  <el-option v-for="item in optionsTime" :key="item.value" :label="item.label" :value="item.value">-->
            <!--                  </el-option>-->
            <!--                </el-select>-->
            <!--                <el-select v-model="endHour" size="mini" placeholder="选择结束时间段">-->
            <!--                  <el-option v-for="item in optionsTime" :key="item.value" :label="item.label" :value="item.value">-->
            <!--                  </el-option>-->
            <!--                </el-select>-->
            <!--                <el-button type="primary" size="mini" @click="setNormallyOpenMethods">确认设置</el-button>-->
            <!--                <el-button type="primary" size="mini" @click="UnsetMethods(1)">取消设置</el-button>-->
            <!--              </el-form-item>-->
            <!--            </el-form>-->
            <div class="date-form">
              <el-date-picker v-model="dateTime" type="monthrange" size="small" align="right" unlink-panels class="w-250"
                @change="getElectricity" range-separator="至" start-placeholder="开始月份" end-placeholder="结束月份"
                :picker-options="pickerOptions">
              </el-date-picker>
              <div class="discount">
                <div ref="main" id="myLine" style="width: 100%; height: 400px"></div>
              </div>
              <el-date-picker v-model="dateTimeOne" type="monthrange" size="small" align="right" unlink-panels
                class="w-250" @change="getSignal" range-separator="至" start-placeholder="开始月份" end-placeholder="结束月份"
                :picker-options="pickerOptions">
              </el-date-picker>
              <div class="discount">
                <div ref="main1" id="myLineOne" style="width: 100%; height: 400px"></div>
              </div>
            </div>
          </el-tab-pane>
          <el-tab-pane label="开锁记录" name="1">
            <UnlockRecord :roomId="sendroomId" v-if="sendStatus"></UnlockRecord>
          </el-tab-pane>
          <el-tab-pane label="警告日志" name="2">
            <warningLog :deviceNum="sendDevice" v-if="sendStatus"></warningLog>
          </el-tab-pane>
          <el-tab-pane label="设备反馈日志" name="3">
            <DeviceFeedbackLog :deviceNum="senddeviceNum" v-if="sendStatus">
            </DeviceFeedbackLog>
          </el-tab-pane>
          <el-tab-pane label="凭证记录" name="4">
            <voucherCom :deviceNum="senddeviceNum" v-if="sendStatus">
            </voucherCom>
          </el-tab-pane>
          <!--          <el-tab-pane label="常开记录" name="5">-->
          <!--            <el-table :data="normallyOpenRecordList" stripe style="width: 100%" height="400">-->
          <!--              <el-table-column prop="operateName" label="设置人员" width="180">-->
          <!--              </el-table-column>-->
          <!--              <el-table-column prop="operate" label="设置状态" width="180" v-if="formInline.manufactureId==101">-->
          <!--                <template slot-scope="scope">-->
          <!--                  <span v-if="scope.row.operate==1">打开</span>-->
          <!--                  <span v-if="scope.row.operate==0">关闭</span>-->
          <!--                </template>-->
          <!--              </el-table-column>-->
          <!--              <el-table-column prop="operate" label="设置状态" width="180" v-if="formInline.manufactureId==201">-->
          <!--                <template slot-scope="scope">-->
          <!--                  <span v-if="scope.row.opendDoorType==1">打开</span>-->
          <!--                  <span v-if="scope.row.opendDoorType==0">关闭</span>-->
          <!--                </template>-->
          <!--              </el-table-column>-->
          <!--              <el-table-column prop="createTime" label="设置时间">-->
          <!--                <template slot-scope="scope">-->
          <!--                  <span v-if="scope.row.startTime">日期范围：{{scope.row.startTime}} - {{scope.row.endTime}},时间段：{{scope.row.startHour}}:00 - {{scope.row.endHour}}:00</span>-->
          <!--                  <span v-else>{{scope.row.createTime}}</span>-->
          <!--                </template>-->
          <!--              </el-table-column>-->
          <!--              <el-table-column prop="updateTime" label="生效时间">-->
          <!--              </el-table-column>-->
          <!--            </el-table>-->
          <!--            <div class="text-center mt-4">-->
          <!--              <el-pagination @size-change="normallyHandleSizeChange" @current-change="normallyHandleCurrentChange"-->
          <!--                :current-page="normallyPageNum" :page-sizes="[20,100, 200, 300, 400]" :page-size="normallyPageSzie"-->
          <!--                layout="total, sizes, prev, pager, next, jumper" :total="normallyTotal">-->
          <!--              </el-pagination>-->
          <!--            </div>-->
          <!--          </el-tab-pane>-->
        </el-tabs>
      </div>
    </el-drawer>
    <el-dialog title="批量设置常开" :visible.sync="setopenStatus" width="70%">
      <el-form :mode="formInline" class="">
        <el-form-item label="常开设置:">
          <el-date-picker v-model="opendTime" type="daterange" range-separator="至" start-placeholder="开始日期"
            end-placeholder="结束日期" size="mini">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="开始时间段:">
          <el-select v-model="startHour" size="mini" placeholder="选择开始时间段">
            <el-option v-for="item in optionsTime" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="结束时间段:">
          <el-select v-model="endHour" size="mini" placeholder="选择结束时间段">
            <el-option v-for="item in optionsTime" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="">
          <el-button type="primary" size="mini" @click="setNormallyOpenMethodsAll">确认设置</el-button>
          <el-button type="primary" size="mini" @click="UnsetMethods(2)">取消设置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog title="批量上传" :visible.sync="uploadkj" width="70%">
      <input class="input-file" type="file" @change="exportData"
        accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" />
      <el-button type="primary" @click="btnClick" size="mini">导入EXCEL</el-button>
      <el-button type="primary" @click="exportBtn" size="mini">下载模板</el-button>
      <el-select v-model="batchAccess" placeholder="请选择" size="mini">
        <el-option v-for="item in accessPlatform.select" :key="item.code" :label="item.desc" :value="item.code">
        </el-option>
      </el-select>
      <el-select v-model="manufacturer" placeholder="请选择" size="mini">
        <el-option v-for="item in manufacturerList" :key="item.value" :label="item.label" :value="item.value">
        </el-option>
      </el-select>
      <el-table :data="userlist2" v-if="userlist1statu" border class="table" ref="multipleTable1" height="200"
        header-cell-class-name="table-header" @selection-change="handleSelectionChange1">
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column prop="deviceNum" label="设备号" align="center"></el-table-column>
        <el-table-column prop="mac" label="mac地址" align="center"></el-table-column>
        <el-table-column prop="sn" label="sn" align="center"></el-table-column>
        <el-table-column prop="imei" label="imei" align="center"></el-table-column>
        <el-table-column prop="app" label="app绑定号" align="center"></el-table-column>
        <el-table-column prop="write" label="生产写入号" align="center"></el-table-column>
      </el-table>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="uploadkj = false" size="small">取 消</el-button>
          <el-button type="primary" @click="batchUploadfun" size="small">确 定</el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog title="紧急密码，每天仅能用一次" :visible.sync="getEmergenceStatus" width="30%">
      <el-form ref="Emergence" :model="Emergence" label-width="80px">
        <el-form-item label="临时密码">
          <el-input v-model="Emergence.password" placeholder="" disabled class="handle-input mr10"></el-input>
        </el-form-item>
        <el-form-item label="电话">
          <el-input v-model="Emergence.EmerPhone" type="number" maxlength="11" placeholder="请输入手机号" :clearable="true"
            class="handle-input mr10">
          </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="getEmergenceStatus = false" size="small">取 消</el-button>
        <el-button type="primary" @click="sendEmergence" size="small">发 送</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import NumberGrow from "../components/visualizcomponent/NumberGrow.vue";
import {
  httpGet,
  httpPost,
  download, downloadPost
} from "../api";
import zTree from "../components/zTree1.vue";
import deviceLi from "../components/deviceLi.vue";
import UnlockRecord from "../components/UnlockRecord.vue"
import DeviceFeedbackLog from "../components/DeviceFeedbackLog.vue"
import warningLog from "../components/warningLog.vue"
import voucherCom from "../components/voucherCom.vue"
import {
  uniqueArray,
  ztreeToElementTree,
  uniqueArray1,
  getcurrentTime1
} from "../utils/index";
import XLSX from "xlsx";
import utils from "../utils/util.js";
import ICINLocker from "../utils/equipment.js"
import moment from 'moment'
import RequestSet from "../api/allFun.js"
let nowDate = new Date()
var currentTime = nowDate
var endcurrentTime = getcurrentTime1(1)
export default {
  inject: ['reload'],
  name: "doorLock",
  data() {
    return {
      lowBattery: 0, // 低电量
      normallyOpenRecordList: [],
      normallyTotal: 0,
      normallyPageNum: 1,
      normallyPageSzie: 20,
      optionsTime: [{
        value: 1,
        label: '1:00',
      },
      {
        value: 2,
        label: '2:00',
      },
      {
        value: 3,
        label: '3:00',
      },
      {
        value: 4,
        label: '4:00',
      },
      {
        value: 5,
        label: '5:00',
      },
      {
        value: 6,
        label: '6:00',
      },
      {
        value: 7,
        label: '7:00',
      },
      {
        value: 8,
        label: '8:00',
      },
      {
        value: 9,
        label: '9:00',
      },
      {
        value: 10,
        label: '10:00',
      },
      {
        value: 11,
        label: '11:00',
      },
      {
        value: 12,
        label: '12:00',
      },
      {
        value: 13,
        label: '13:00',
      },
      {
        value: 14,
        label: '14:00',
      },
      {
        value: 15,
        label: '15:00',
      },
      {
        value: 16,
        label: '16:00',
      },
      {
        value: 17,
        label: '17:00',
      },
      {
        value: 18,
        label: '18:00',
      },
      {
        value: 19,
        label: '19:00',
      },
      {
        value: 20,
        label: '20:00',
      },
      {
        value: 21,
        label: '21:00',
      },
      {
        value: 22,
        label: '22:00',
      },
      {
        value: 23,
        label: '23:00',
      },
      {
        value: 24,
        label: '24:00',
      }
      ],
      setopenStatus: false,
      opendTime: [currentTime, endcurrentTime],
      startHour: 1,
      endHour: 24,
      synchroLockNumber: "",
      contentSearchShow: false,
      myLine_option_one: {
        title: {
          text: "信号曲线",
          x: "0",
          y: "20",
          color: "#333"
        },
        tooltip: {
          trigger: "axis"
        },
        legend: {
          orient: "horizontal",
          x: "right",
          y: "top",
          data: ["门锁近期信号曲线"],
        },
        dataZoom: [{
          type: 'inside', //内置滑动，随鼠标滚轮展示
          xAxisIndex: [0],
          start: 0, //初始化时，滑动条宽度开始标度
          end: 100 //初始化时，滑动条宽度结束标度
        }],
        grid: {
          top: "16%",
          left: "0%",
          right: "0%",
          bottom: "0%",
          containLabel: true,
        },
        xAxis: {
          name: "时间",
          type: "category",
          data: [],
        },
        yAxis: {},
        series: [{
          name: "门锁信号",
          type: "line",
          smooth: true,
          data: [],
          itemStyle: {
            normal: {
              color: "#FFAE00",
              lineStyle: {
                color: "#397FFF",
              },
            },
          },
          areaStyle: {
            normal: {
              color: {
                type: "linear", //设置线性渐变
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [{
                  offset: 0,
                  color: "rgba(57,127,255,.1)", // 0% 处的颜色
                },
                {
                  offset: 1,
                  color: "#fff", // 100% 处的颜色
                },
                ],
                globalCoord: false, // 缺省为 false
              },
            },
          },
        },],
      },
      myLine_option_three: {
        title: {
          text: "信号曲线",
          x: "0",
          y: "20",
          color: "#333"
        },
        tooltip: {
          trigger: "axis"
        },
        legend: {
          orient: "horizontal",
          x: "right",
          y: "top",
          data: ["门锁近期信号曲线"],
        },
        dataZoom: [{
          type: 'inside', //内置滑动，随鼠标滚轮展示
          xAxisIndex: [0],
          start: 0, //初始化时，滑动条宽度开始标度
          end: 100 //初始化时，滑动条宽度结束标度
        }],
        grid: {
          top: "16%",
          left: "0%",
          right: "0%",
          bottom: "0%",
          containLabel: true,
        },
        xAxis: {
          name: "时间",
          type: "category",
          data: [],
        },
        yAxis: {},
        series: [{
          name: "门锁信号",
          type: "line",
          smooth: true,
          data: [],
          itemStyle: {
            normal: {
              color: "#FFAE00",
              lineStyle: {
                color: "#397FFF",
              },
            },
          },
          areaStyle: {
            normal: {
              color: {
                type: "linear", //设置线性渐变
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [{
                  offset: 0,
                  color: "rgba(57,127,255,.1)", // 0% 处的颜色
                },
                {
                  offset: 1,
                  color: "#fff", // 100% 处的颜色
                },
                ],
                globalCoord: false, // 缺省为 false
              },
            },
          },
        },],
      },
      myLine_option: {
        title: {
          text: "电量曲线",
          x: "0",
          y: "20"
        },
        tooltip: {
          trigger: "axis"
        },
        legend: {
          orient: "horizontal",
          x: "right",
          y: "top",
          data: ["门锁近期电量曲线"],
        },
        dataZoom: [{
          type: 'inside', //内置滑动，随鼠标滚轮展示
          xAxisIndex: [0],
          start: 0, //初始化时，滑动条宽度开始标度
          end: 100 //初始化时，滑动条宽度结束标度
        }],
        grid: {
          top: "16%",
          left: "0%",
          right: "0%",
          bottom: "0%",
          containLabel: true,
        },
        xAxis: {
          name: "时间",
          type: "category",
          data: [],
        },
        yAxis: {},
        series: [{
          name: "门锁电量",
          type: "line",
          smooth: true,
          data: [],
          itemStyle: {
            normal: {
              color: "#FFAE00",
              lineStyle: {
                color: "#397FFF",
              },
            },
          },
          areaStyle: {
            /*normal: { origin: 'start', color: 'rgba(57,127,255,.1)', opacity: 1 },*/
            normal: {
              color: {
                type: "linear", //设置线性渐变
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [{
                  offset: 0,
                  color: "rgba(57,127,255,.1)", // 0% 处的颜色
                },
                {
                  offset: 1,
                  color: "#fff", // 100% 处的颜色
                },
                ],
                globalCoord: false, // 缺省为 false
              },
            },
          },
        },],
      },
      pickerOptions: {
        shortcuts: [{
          text: '今天',
          onClick(picker) {
            const end = new Date();
            picker.$emit('pick', [moment().startOf('day').format("YYYY-MM-DD 00:00:00"), end]);
          }
        }, {
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '本月',
          onClick(picker) {
            const end = new Date();
            picker.$emit('pick', [moment().startOf('month').format("YYYY-MM-DD 00:00:00"), end]);
          }
        }, {
          text: '今年至今',
          onClick(picker) {
            const end = new Date();
            const start = new Date(new Date().getFullYear(), 0);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近六个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setMonth(start.getMonth() - 6);
            picker.$emit('pick', [start, end]);
          }
        },]
      },
      dateTime: [moment().subtract(3, 'months').format("YYYY-MM-DD 00:00:00"), moment().format(
        "YYYY-MM-DD HH:mm:ss")],
      dateTimeOne: [moment().subtract(3, 'months').format("YYYY-MM-DD 00:00:00"), moment().format(
        "YYYY-MM-DD HH:mm:ss")],
      endDate: moment().format("YYYY-MM-DD HH:mm:ss"),
      startDate: moment().subtract(3, 'months').format("YYYY-MM-DD 00:00:00"),
      endDateOne: moment().format("YYYY-MM-DD HH:mm:ss"),
      startDateOne: moment().subtract(3, 'months').format("YYYY-MM-DD 00:00:00"),
      searchRoom: '',
      deviceImg: require("../assets/img/lock.2451264a.png"),
      selectoption: [],
      selectoptionValue: '',
      senddeviceNum: '',
      sendDevice: {
        deviceNum: ''
      },
      sendroomId: '',
      commpontentStatus: true,
      Emergence: {
        EmerPhone: '',
        password: '',
        device: '',
        name: ''
      },
      defaultProps: {
        children: "children",
        label: "name",
      },
      options: [],
      drawer: false,
      value1: false,
      value2: 0,
      marks: {
        0: "关",
        50: "中",
        100: "高",
      },
      switchtext: "关",
      activeName: "0",
      formInline: {},
      platlist: [{
        label: "电信",
        value: 1
      }, {
        label: "移动",
        value: 2
      }, {
        label: "联通",
        value: 3
      },],
      manufacturerList: [],
      setting: {
        edit: {
          enable: true,
          drag: {
            isMove: true,
          },
          showRemoveBtn: false,
          showRenameBtn: false,
        },
        check: {
          enable: false,
        },
        data: {
          simpleData: {
            enable: true,
            pIdKey: "pid",
          },
        },
        view: {
          showIcon: true,
          addHoverDom: this.addHoverDom,
          removeHoverDom: this.removeHoverDom,
        },
      },
      zNodes: [],
      bromm: {},
      query: {
        address: "",
        name: "",
        pageIndex: 1,
        pageSize: 20,
        options: [],
      },
      search: {
        name: "",
        deviceNum: "",
        roomname: '',
        imei: "",
        isOnline: "",
        startBattery: '',
        endBattery: '',
        firmwareVersion: '',
        operationStatus: '',
        isUsed: '',
        iccid: '',
        rssiStart: '',
        rssiEnd: '',
        createStart: '',
        createEnd: '',
        isAppBind: ''
      },
      tableData: [],
      multipleSelection: [],
      delList: [],
      editVisible: false,
      roomVisible: false,
      pageTotal: 0,
      sumpageTotal: 0,
      currentPage4: 1,
      form: {
        lockerId: '',
        manufacturer: "",
        platformId: '',
        imei: '',
        deviceNum: '',
        authKey: '',
        validateCode: '',
        lockerSuperAdminId: '',
        customerCode: '',
        type: ''
      },
      manufacturer: '',
      idx: -1,
      id: -1,
      abnormal: 0,
      online: 0,
      treedata: [],
      unonline: 0,
      Unlocking: false,
      Unlockingrow: {},
      lockingform: {
        password: ""
      },
      activeiconfont: true,
      info: [],
      uploadkj: false,
      userlist1statu: true,
      userlist2: [],
      multipleSelection1: [],
      batchAccess: "",
      getEmergenceStatus: false,
      getEmergenceNum: '',
      checkNodeId: '',
      pageSize: 10,
      pageNum: 1,
      sendStatus: true,
      userInfo: {
        type: ''
      },
      checkNodeId1: '',
      accessPlatform: {},
      paginationConfig: 'total, sizes, prev, pager, next, jumper',
      colNum_6: 6,
      drawerSize: '90%',
      analysisData: { isAlwaysOpen: 0, notAlwaysOpen: 0, bingSite: 0 },
    };
  },
  components: {
    zTree,
    deviceLi,
    UnlockRecord,
    warningLog,
    DeviceFeedbackLog,
    voucherCom,
    NumberGrow
  },
  beforeCreate() {
    // var tenantId = JSON.parse(localStorage.getItem('tenantId'))
    // if (tenantId == 400) {
    //   this.$store.commit('defaultsettenantid')
    // }
  },
  created() {
    if (this.$route.params.isOnline) {
      this.search.isOnline = this.$route.params.isOnline
    }
    if (this.$route.params.endBattery) {
      this.search.startBattery = '0'
      this.search.endBattery = 20
    }
    this.manufacturerList = this.$MANUFACTURER.MANUFACTURER.lock
    this.accessPlatform = this.$MANUFACTURER.accessPlatform
    this.userInfo = JSON.parse(localStorage.getItem('info'))
    if (this.$route.params.isUsed) {
      this.search.isUsed = this.$route.params.isUsed
    }
    if (document.documentElement.clientWidth < 1080) {
      this.paginationConfig = 'total, prev, pager, next'
      this.colNum_6 = 12
      this.drawerSize = '100%'
    } else {
      this.paginationConfig = 'total, sizes, prev, pager, next, jumper'
      this.colNum_6 = 6
      this.drawerSize = '90%'
    }
  },
  mounted() {
    this.getdevice();
    // this.getalllist();
    this.$store.commit("increment", 1);
    this.getcard()
    this.getallTree()
    document.addEventListener('keydown', this.keyDown)
  },
  methods: {
    // 设备筛选导出结果
    exportDeviceOrderMethods() {
      var deviceNum = this.search.deviceNum.replace(/\s*/g, "");
      var imei = this.search.imei.replace(/\s*/g, "");
      if (this.search.isOnline == 2) {
        this.search.isAppBind = 1
      } else {
        this.search.isAppBind = ''
      }
      var q = {
        deviceNum: deviceNum,
        imei: imei,
        isOnline: this.search.isOnline,
        roomName: this.search.roomname,
        roomIds: this.checkNodeId,
        startBattery: this.search.startBattery,
        endBattery: this.search.endBattery,
        lockType: 1,
        unBind: this.search.unBind,
        firmwareVersion: this.search.firmwareVersion,
        isUsed: this.search.isUsed,
        iccid: this.search.iccid,
        rssiStart: this.search.rssiStart,
        rssiEnd: this.search.rssiEnd,
        createStart: this.search.createStart,
        createEnd: this.search.createEnd,
        isAppBind: this.search.isAppBind
      };
      if (q.isOnline == 2) {
        delete q.isOnline
      }
      var qObject = utils.validObject(q)
      var data = {
        orderBy: "open_time desc",
        q: JSON.stringify(qObject)
      }
      httpPost(data, this.$api.getDeviceItems).then(res => {
        console.log(res)
        if (res.code == 200) {
          let exportData = []
          //导出数据结构构造
          res.data.list.forEach(item => {
            var accessPlatform = this.accessPlatform.show.filter(lt => lt.code == item.accessPlatform)[0]
            if (accessPlatform) {
              item['accessPlatformText'] = accessPlatform.desc
            } else {
              item['accessPlatformText'] = ''
            }
            exportData.push({
              roomName: item.roomName,
              deviceNum: item.deviceNum,
              imei: item.imei,
              imsi: item.imsi,
              isOnline: item.isOnline == 1 ? '在线' : item.isOnline == 2 ? '异常' : '离线',
              battery: item.battery,
              rssi: item.rssi,
              Operator: item.accessPlatformText,
              createAt: moment(item.createAt).format("YYYY-MM-DD HH:mm:ss"),
              lastReportAt: moment(item.lastReportAt).format("YYYY-MM-DD HH:mm:ss"),
            })
          })
          //导出表头设计
          let head = {
            roomName: '房间名称',
            deviceNum: '设备号',
            imei: 'IMEI',
            imsi: 'IMSI',
            isOnline: '状态',
            battery: '电量',
            rssi: '信号',
            Operator: "运营商",
            createAt: '注册时间',
            lastReportAt: '上线时间',
          }
          //表头数据切换
          const list = exportData.map(item => {
            const obj = {}
            for (const k in item) {
              if (head[k]) {
                obj[head[k]] = item[k]
              }
            }
            return obj
          })
          // 创建工作表
          const data = XLSX.utils.json_to_sheet(list)
          // 创建工作簿
          const wb = XLSX.utils.book_new()
          // 将工作表放入工作簿中
          XLSX.utils.book_append_sheet(wb, data, 'data')
          // 生成文件并下载
          XLSX.writeFile(wb, '门锁列表.xlsx')
        } else {
          this.$message.error(res.message)
        }
      })
      // downloadPost(data, this.$api.exportDeviceOrder).then((res) => {
      //   const link = document.createElement("a");
      //   let blob = new Blob([res], {
      //     type: "application/vnd.ms-excel"
      //   });
      //   var objectUrl = URL.createObjectURL(blob);
      //   link.href = objectUrl;
      //   link.download = "门锁列表.xlsx";
      //   link.click();
      //   URL.revokeObjectURL(objectUrl);
      // });
    },
    // 获取常开记录
    getAlwaysOpens() {
      var data = {
        pageNum: this.normallyPageNum,
        pageSize: this.normallyPageSzie,
        orderType: "desc",
        orderBy: "createTime",
        q: JSON.stringify({
          deviceNum: this.formInline.deviceNum
        })
      }
      httpPost(data, this.$api.getAlwaysOpensApi).then(res => {
        if (res.success) {
          res.data.list.map(li => {
            li.createTime = moment(li.createTime).format("YYYY-MM-DD HH:mm:ss")
            var content = JSON.parse(li.content)
            if (content.operate) {
              li.operate = content.operate
            } else {
              li.operate = ''
            }
            if (content.endTime) {
              li.endTime = content.endTime
              li.startTime = content.startTime
              li.startHour = content.openDoorSegmentList[0].startHour
              li.endHour = content.openDoorSegmentList[0].endHour
              li.opendDoorType = content.opendDoorType
            }
            if (li.updateTime) {
              li.updateTime = moment(li.updateTime).format("YYYY-MM-DD HH:mm:ss")
            }
          })
          this.normallyOpenRecordList = res.data.list
          this.normallyTotal = res.data.total
        } else {
          this.$message.error(res.message)
        }
      })
    },
    // 常开记录分页
    normallyHandleSizeChange(val) {
      this.normallyPageSzie = val
      this.getAlwaysOpens()
    },
    normallyHandleCurrentChange(val) {
      this.normallyPageNum = val
      this.getAlwaysOpens()
    },
    // 电量图表初始化
    initChart() {
      var myLine = this.$echarts.init(document.getElementById("myLine"));
      myLine.setOption(this.myLine_option);
    },
    initChartOne() {
      var myLine = this.$echarts.init(document.getElementById("myLineOne"));
      myLine.setOption(this.myLine_option_one);
    },
    initChartThree() {
      var myLine = this.$echarts.init(document.getElementById("myLineThree"));
      myLine.setOption(this.myLine_option_three);
    },
    getElectricity(e) {
      this.endDate = moment(this.dateTime[1]).format("YYYY-MM-DD HH:mm:ss")
      this.startDate = moment(this.dateTime[0]).format("YYYY-MM-DD HH:mm:ss")
      this.quantityFun()
      this.dateTimeOne = [this.dateTime[0], this.dateTime[1]]
      this.endDateOne = moment(this.dateTime[1]).format("YYYY-MM-DD HH:mm:ss")
      this.startDateOne = moment(this.dateTime[0]).format("YYYY-MM-DD HH:mm:ss")
      this.quantityFunOne()
    },
    getSignal(e) {
      this.endDateOne = moment(this.dateTimeOne[1]).format("YYYY-MM-DD HH:mm:ss")
      this.startDateOne = moment(this.dateTimeOne[0]).format("YYYY-MM-DD HH:mm:ss")
      this.quantityFunOne()
    },
    // 电量图表显示
    quantityFun() {
      var endDate = this.endDate;
      var startDate = this.startDate;
      var data = {
        code: "logHeartbeat/batteryList",
        data: {
          pageNum: 1,
          pageSize: 100000,
          para: {
            deviceNum: this.senddeviceNum,
            startDate: startDate,
            endDate: endDate,
          }
        },
      };
      httpPost(data, this.$api.sendCommand).then((res) => {
        if (res.success) {
          var optiondata = [],
            seriesdata = [];
          res.data.list.map((li, index) => {
            li.createAt = moment(li.createAt).format("YYYY-MM-DD HH:mm:ss")
          });
          var array = this.factorial(res.data.list, 0);
          array.map((li) => {
            optiondata.push(li.createAt);
            seriesdata.push(li.battery);
          });
          this.myLine_option.xAxis.data = optiondata;
          this.myLine_option.series[0].data = seriesdata;
          this.$nextTick(() => {
            this.initChart();
          });
        } else {
          this.$message.error("数据错误");
        }
      });
    },
    factorial(time, index) {
      if (time.length - 1 > index) {
        var date = new Date(time[index + 1].createAt).getTime();
        var date1 = new Date(time[index].createAt).getTime();
        // console.log(parseInt(date),index,parseInt(date1),(parseInt(date)-parseInt(date1)))
        if (parseInt(date) - parseInt(date1) > 8640000) {
          return this.factorial(time, index + 1);
        } else {
          time.splice(index, 1);
          return this.factorial(time, index);
        }
      } else {
        return time;
      }
    },
    // 信号图表显示
    quantityFunOne() {
      var endDate = this.endDateOne;
      var startDate = this.startDateOne;
      var data = {
        code: "logHeartbeat/rssiList",
        data: {
          pageNum: 1,
          pageSize: 100000,
          para: {
            deviceNum: this.senddeviceNum,
            startDate: startDate,
            endDate: endDate,
          }
        },
      };
      httpPost(data, this.$api.sendCommand).then((res) => {
        if (res.success) {
          var optiondata = [],
            seriesdata = [];
          res.data.list.map((li, index) => {
            li.createAt = moment(li.createAt).format("YYYY-MM-DD HH:mm:ss")
          });
          var array = this.factorial(res.data.list, 0);
          array.map((li) => {
            optiondata.push(li.createAt);
            seriesdata.push(li.rssi);
          });
          this.myLine_option_one.xAxis.data = optiondata;
          this.myLine_option_one.series[0].data = seriesdata;
          this.$nextTick(() => {
            this.initChartOne();
          });
        } else {
          this.$message.error("数据错误");
        }
      });
    },
    getTimeDate(n) {
      var currentDate = new Date()
      var preDate = new Date(currentDate.getTime() + n * 24 * 3600 * 1000)
      let year = currentDate.getFullYear()
      let mon = currentDate.getMonth() + 1
      let day = currentDate.getDay()
      let s = year + '-' + (mon < 10 ? ('0' + mon) : mon) + '-' + (day < 10 ? ('0' + day) : day)
      return s
    },
    // 信号图表显示
    quantityFunThree() {
      var data = {
        code: "lockOnlineBattery/selectOnline",
        data: {
          deviceNum: this.senddeviceNum
        },
      };
      httpPost(data, this.$api.sendCommand).then((res) => {
        if (res.success) {
          var optiondata = [],
            seriesdata = [];
          for (var i = 0; i < res.data.length; i++) {
            var date = this.getTimeDate(i)
            optiondata.push(date)
            seriesdata.push(res.data.online[i])
          }
          this.myLine_option_one.xAxis.data = optiondata;
          this.myLine_option_one.series[0].data = seriesdata;
          this.$nextTick(() => {
            this.initChartThree();
          });
        } else {
          this.$message.error("数据错误");
        }
      });
    },
    keyDown(e) {
      //如果是回车则执行登录方法
      if (e.keyCode == 13) {
        if (this.$route.name == 'doorLock') {
          this.handleSearch();
        }
      }
    },
    // 解冻
    thawMethods(index, row) {
      this.$confirm("是否解冻该门锁?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        RequestSet.freeManageMethods(0, row, (callback) => {
          if (callback.code == 200) {
            this.$message.success("解冻指令下发成功")
          } else {
            this.$message.error("解冻失败")
          }
        })
      })
    },
    // 冻结门锁
    frozenMethods(index, row) {
      RequestSet.freeManageMethods(1, row, (callback) => {
        if (callback.code == 200) {
          this.$message.success("冻结指令下发成功")
        } else {
          this.$message.error("冻结失败")
        }
      })
    },
    InputFun(e, name) {
      if (name == 'startBattery' || name == 'endBattery') {
        if (Number(e) < 0) {
          e = 0
        }
        if (Number(e) > 100) {
          e = 100
        }
      }
      this.search[name] = e
    },
    selectTenantId(e) {
      localStorage.setItem('tenantId', e)
      this.reload()
    },
    // 重置初始化
    resetInitialization(row, callback) {
      if (row.manufactureId == 201 || row.manufactureId == 221) {
        var data3 = {
          code: "zg/deleteAllUsers",
          data: {
            lockerId: row.deviceNum,
            imei: row.imei,
            order: 6501,
          },
        };
        httpPost(data3, this.$api.sendCommand).then((res) => {
          if (res.success) {
            this.$message.success("重置成功");
            callback(true)
          } else {
            callback(false)
          }
        });
      } else if (row.manufactureId == 101) {
        var data2 = {
          code: "isp/restoreSetting",
          data: {
            order: 6501,
            imei: row.imei,
            deviceNum: row.deviceNum,
            managerTelephone: "18270949468",
            managerPassword: "202108",
          },
        };
        httpPost(data2, this.$api.sendCommand).then((res2) => {
          if (res2.success) {
            this.$message.success("重置成功");
            var str = {
              deviceNum: row.deviceNum,
              imei: row.imei,
              order: 6101,
            };
            httpPost(str, this.$api.getDeviceRegisterManager).then((res1) => {
              var str1 = {
                imei: row.imei, //row.imsi,
                deviceNum: row.deviceNum, //row.deviceNum,
                operateMode: 7,
                is: true,
                order: 6207,
                passwordStartTime: "20210813010101",
                passwordEndTime: "20680813010101",
              };
              httpPost(str1, this.$api.getDeviceOperateUserInfo).then((res2) => { });
              var str2 = {
                imei: row.imei, //row.imsi,
                deviceNum: row.deviceNum, //row.deviceNum,
                operateMode: 4,
                is: true,
                order: 6204,
                passwordStartTime: "20210813010101",
                passwordEndTime: "20680813010101",
              };
              httpPost(str2, this.$api.getDeviceOperateUserInfo).then((res3) => {
                if (res3.success) {
                  this.$message.success("初始化成功");
                  callback(true)
                }
              });
            });
          } else {
            this.$message.error(res2.msg);
            callback(false)
          }
        });
      }
    },
    getPersonCallback(person, alllist, callback) {
      var personlist = []
      person.map(li => {
        var obj = {
          person: li,
          data: alllist.filter((item) => {
            if (item.deviceNum && item.cardId == li.cardId) {
              return item
            }
          })
        }
        personlist.push(obj)
      })
      callback(personlist)
    },
    setReset(row) {
      if (row.manufactureId == 201 || row.manufactureId == 221) {
        var data3 = {
          code: "zg/deleteAllUsers",
          data: {
            lockerId: row.deviceNum,
            imei: row.imei,
            order: 6501,
            cardName: this.userInfo.username,
            roomName: row.roomName
          },
        };
        httpPost(data3, this.$api.sendCommand).then((res) => {
          if (res.success) {
            this.$message.success("重置成功");
            var q = {
              id: row.roomId,
            };
            var tenant = {
              q: JSON.stringify(q),
            };
            httpGet(tenant, this.$api.getSiteTenant).then((res) => {
              Promise.all(
                res.data.list.map((element) => {
                  return new Promise(function (resolve, reject) {
                    resolve(element.cardId);
                  });
                })
              ).then((allId) => {
                allId.map((li) => {
                  var str = [{
                    siteId: row.roomId,
                    cardId: li,
                  },];
                  httpPost(str, this.$api.unbindCard).then((res) => { });
                });
              })
            })
          } else {
            this.$message.success(res.msg);
          }
        });
      } else if (row.manufactureId == 101) {
        var data2 = {
          code: "isp/restoreSetting",
          data: {
            order: 6501,
            imei: row.imei,
            deviceNum: row.deviceNum,
            managerTelephone: "18270949468",
            managerPassword: "202108",
            cardName: this.userInfo.username,
            roomName: row.roomName
          },
        };
        httpPost(data2, this.$api.sendCommand).then((res2) => {
          if (res2.success) {
            this.$message.success("重置成功");
            var q = {
              id: row.roomId,
            };
            var tenant = {
              q: JSON.stringify(q),
            };
            httpGet(tenant, this.$api.getSiteTenant).then((res) => {
              Promise.all(
                res.data.list.map((element) => {
                  return new Promise(function (resolve, reject) {
                    resolve(element.cardId);
                  });
                })
              ).then((allId) => {
                var str = {
                  deviceNum: row.deviceNum,
                  imei: row.imei,
                  order: 6101,
                };
                httpPost(str, this.$api.getDeviceRegisterManager).then((res1) => {
                  var str1 = {
                    imei: row.imei, //row.imsi,
                    deviceNum: row.deviceNum, //row.deviceNum,
                    operateMode: 7,
                    is: true,
                    order: 6207,
                    passwordStartTime: "20210813010101",
                    passwordEndTime: "20680813010101",
                  };
                  httpPost(str1, this.$api.getDeviceOperateUserInfo).then((res2) => { });
                  var str2 = {
                    imei: row.imei, //row.imsi,
                    deviceNum: row.deviceNum, //row.deviceNum,
                    operateMode: 4,
                    is: true,
                    order: 6204,
                    passwordStartTime: "20210813010101",
                    passwordEndTime: "20680813010101",
                  };
                  httpPost(str2, this.$api.getDeviceOperateUserInfo).then((res3) => {
                    if (res3.success) {
                      this.$message.success("初始化成功");
                    }
                  });
                });
                allId.map((li) => {
                  var str = [{
                    siteId: row.roomId,
                    cardId: li,
                  },];
                  httpPost(str, this.$api.unbindCard).then((res) => { });
                });
              })
            })
          } else {
            this.$message.error(res2.msg);
          }
        });
      }
    },
    // 数据同步
    dataSynchronization(index, row) {
      console.log(row)
      this.$confirm("是否确认数据同步?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.orderDeviceData(row)
      })
    },
    sendPersonCerf(row, setPersonList, alllist) {
      setPersonList.forEach(li => {
        this.getPersonInfo(li, (callback) => {
          if (callback.code == 200) {
            if (callback.data.list.length > 0) {
              var personli = callback.data.list[0]
              if (row.manufactureId == 101) {
                var alllistAll = alllist.filter(item => item.cardId == li)
                var endTime = alllistAll[0].endTime * 1000
                var startTime = alllistAll[0].startTime * 1000
                var passwordEndTime = moment(endTime).format("YYYYMMDDHHmmss");
                var passwordStartTime = moment(startTime).format("YYYYMMDDHHmmss");
                var userTelephone = JSON.parse(personli.info).userTelephone;
                var userPassword = JSON.parse(personli.info).userPassword;
                var data = {
                  deviceNum: row.deviceNum,
                  imei: row.imei,
                  userTelephone: userTelephone,
                  userPassword: userPassword,
                  password: userPassword,
                  operateMode: 26,
                  order: 6226,
                  passwordStartTime: passwordStartTime,
                  passwordEndTime: passwordEndTime,
                  cardName: personli.name,
                  roomName: row.roomName
                }
                ICINLocker.LDAddUser(data.deviceNum, data.imei, data.userTelephone, data.userPassword, data
                  .password, passwordStartTime, passwordEndTime, data.operateMode, data.order, data
                  .cardName, data.roomName, false, (callback) => {
                    alllistAll.map(ll => {
                      utils.putCarfidAdd(row, ll)
                    })
                  })
              } else if (row.manufactureId == 201 || row.manufactureId == 221) {
                var alllistAll = alllist.filter(item => item.cardId == li)
                var endTime = alllistAll[0].endTime * 1000
                var startTime = alllistAll[0].startTime * 1000
                var passwordEndTime = moment(endTime).format("YYYYMMDDHHmmss");
                var passwordStartTime = moment(startTime).format("YYYYMMDDHHmmss");
                var userTelephone = JSON.parse(personli.info).userTelephone;
                var userPassword = JSON.parse(personli.info).userPassword;
                var data = {
                  lockerId: row.deviceNum,
                  imei: row.imei,
                  lockerUserId: userPassword,
                  keyId: userPassword,
                  role: 0,
                  action: 1,
                  order: 6226,
                  cardName: personli.name,
                  roomName: row.roomName
                };
                ICINLocker.addUserToLock(data.lockerId, data.imei, data
                  .lockerUserId, data.role, data.action, data.order, data.cardName, data
                  .roomName, (callback) => {
                    console.log(callback, 'callback')
                    if (callback.success) {
                      alllistAll.map(ll => {
                        utils.putCarfidzgAdd(row, ll)
                      })
                    }
                  })
              }
            }
          }
        })
      })
    },
    getPersonInfo(li, callback) {
      var q = {
        id: li,
      };
      var data = {
        pageNum: 1,
        pageSize: 10,
        orderBy: "create_time desc",
        q: JSON.stringify(q),
      };
      httpPost(data, this.$api.getlistNum).then((res1) => {
        callback(res1)
      })
    },
    // 获取指定锁所有非703凭证数据
    orderDeviceData(row) {
      var _this = this
      if (row.roomId) {
        var data1 = {
          pageNum: 0,
          pageSize: 0,
          q: {
            id: row.roomId
          }
        }
        httpGet(data1, this.$api.getSiteTenant).then(res => {
          if (res.success) {
            var person = res.data.list
            var data = {
              pageNum: 0,
              pageSize: 0,
              orderBy: "create_at desc",
              q: {
                deviceNum: row.deviceNum,
                types: "0,1,2,3,4",
                inStatus: "0,1",
              }
            }
            httpGet(data, this.$api.getCertificates).then(res1 => {
              if (res1.success) {
                var alllist = utils.zlib_unzip(res1.data)
                this.getPersonCallback(person, alllist, (callback) => {
                  console.log(person, alllist, callback)
                  var personlist = callback
                  _this.resetInitialization(row, (callback1) => {
                    console.log(callback1, row)
                    if (row.manufactureId == 101) {
                      personlist.map(lt => {
                        var endTime = new Date(lt.person.endTime).getTime()
                        var startTime = new Date(lt.person.startTime).getTime()
                        var passwordEndTime = moment(endTime).format("YYYYMMDDHHmmss");
                        var passwordStartTime = moment(startTime).format("YYYYMMDDHHmmss");
                        var userTelephone = JSON.parse(lt.person.info).userTelephone;
                        var userPassword = JSON.parse(lt.person.info).userPassword;
                        var data = {
                          deviceNum: row.deviceNum,
                          imei: row.imei,
                          userTelephone: userTelephone,
                          userPassword: userPassword,
                          password: userPassword,
                          operateMode: 26,
                          order: 6226,
                          passwordStartTime: passwordStartTime,
                          passwordEndTime: passwordEndTime,
                          cardName: lt.person.name,
                          roomName: row.roomName
                        }
                        ICINLocker.LDAddUser(data.deviceNum, data.imei, data.userTelephone, data
                          .userPassword,
                          data
                            .password, passwordStartTime, passwordEndTime, data.operateMode, data
                          .order,
                          data
                            .cardName,
                          data.roomName, false, (callback) => {
                            lt.data.map(ll => {
                              utils.putCarfidAdd(row, ll)
                            })
                          })
                      })
                    } else if (row.manufactureId == 201 || row.manufactureId == 221) {
                      personlist.map(lt => {
                        var endTime = new Date(lt.person.endTime).getTime()
                        var startTime = new Date(lt.person.startTime).getTime()
                        var passwordEndTime = moment(endTime).format("YYYYMMDDHHmmss");
                        var passwordStartTime = moment(startTime).format("YYYYMMDDHHmmss");
                        var userTelephone = JSON.parse(lt.person.info).userTelephone;
                        var userPassword = JSON.parse(lt.person.info).userPassword;
                        var data = {
                          lockerId: row.deviceNum,
                          imei: row.imei,
                          lockerUserId: userPassword,
                          keyId: userPassword,
                          role: 0,
                          action: 1,
                          order: 6226,
                          cardName: lt.person.name,
                          roomName: row.roomName
                        };
                        ICINLocker.addUserToLock(data.lockerId, data.imei, data
                          .lockerUserId, data.role, data.action, data.order, data.cardName, data
                          .roomName, (
                            callback2) => {
                          if (callback2.success) {
                            lt.data.map(ll => {
                              utils.putCarfidzgAdd(row, ll)
                            })
                          }
                        })
                      })
                    }
                  })
                })
              } else {
                this.$message.error(res1.msg)
              }
            })

          } else {
            this.$message.error(res.msg)
          }
        })
      } else {
        this.$message.error("暂无数据")
      }
    },
    // 从paas同步能对应得上的有效凭证
    syncCommands() {
      httpGet('', this.$api.syncCommands).then(res => { })
    },
    // 同步刷新
    refreshFun() {
      httpGet("", this.$api.lockDeviceInfoList).then((res) => {
        this.handleSearch()
      });
    },
    // 选择房源
    checkNode(e) {
      this.checkNodeId = e
      var options = this.options
      var arr = this.getId(options, e[e.length - 1])
      console.log(arr)
      var listarr = [arr[0]]
      var obj = this.getNodeId(listarr)
      this.checkNodeId = obj
    },
    checkNodeOne(e) {
      this.checkNodeId1 = e[e.length - 1]
      this.checkRoomDevice(e[e.length - 1])
    },
    checkRoomDevice(id) {
      var q = {
        roomIds: [id],
        lockType: 1
      };
      var data = {
        q: JSON.stringify(q),
        pageNum: 1,
        pageSize: this.pageSize,
      };
      httpPost(data, this.$api.getDeviceItems).then((res) => {
        if (res.data.list.length > 0) {
          this.$message.error("该房间已绑定锁，请重新选择")
          this.checkNodeId1 = ''
        }
      });
    },
    getParentId(list, id) {
      for (let i in list) {
        if (list[i].id == id) {
          return [list[i]]
        }
        if (list[i].children) {
          let node = this.getParentId(list[i].children, id);
          if (node !== undefined) {
            return node.concat(list[i])
          }
        }
      }
    },
    getId(list, id) {
      for (let i in list) {
        if (list[i].id == id) {
          return [list[i]]
        }
        if (list[i].children) {
          let node = this.getParentId(list[i].children, id);
          if (node !== undefined) {
            return node;
          }
        }
      }
    },
    getNodeId(list, newNodeId = []) {
      for (let i in list) {
        newNodeId.push(list[i].id)
        if (list[i].children) {
          this.getNodeId(list[i].children, newNodeId);
        }
      }
      return newNodeId;
    },
    getallTree() {
      var data = {};
      httpGet(data, this.$api.getTree).then((res) => {
        var userlist = [];
        var temp = {},
          arr = [];
        res.data.forEach((item, index) => {
          if (!temp[item.id]) {
            arr.push(item);
            temp[item.id] = true;
          }
        });
        arr.map((li) => {
          if (li.expand) {
            if (JSON.parse(li.expand).type == "0") {
              userlist.push(li);
            }
          }
        });
        var list = res.data.sort((pre, cur) => pre.id - cur.id)
        var arrdata = uniqueArray1(list, "id")
        this.options = ztreeToElementTree(arrdata, {});
        this.zNodes = this.options
      });
    },
    // 获取门卡概况
    getcard() {
      RequestSet.getAnalysis("", 1, (callback) => {
        this.analysisData = callback
        this.sumpageTotal = callback.total
        this.online = callback.onlineTotal
        this.unonline = callback.offlineTotal
        this.abnormal = callback.isAppBind
        this.lowBattery = callback.batteryLevel1
      })
    },
    // 发送离线密码
    sendEmergence() {
      var re = /^1\d{10}$/
      if (re.test(this.Emergence.EmerPhone)) {
        var data = {
          code: this.Emergence.password,
          phone: this.Emergence.EmerPhone,
          device: this.Emergence.device,
          name: this.Emergence.name
        }
        httpPost(data, this.$api.sendEmergence).then(res => {
          if (res.success) {
            this.$message.success('发送成功')
          } else {
            this.$message.error('发送失败')
          }
        })
        this.getEmergenceStatus = false
      } else {
        this.$message.error('请填写正确手机号')
      }
    },
    handleCheckChange(data, checked, node) {
      if (checked) {
        this.treedata = data
      } else {
        if (this.checkedId == data.id) {
          this.$refs.tree.setCheckedKeys([data.id]);
        }
      }
    },
    // 临时密码
    getEmergence(index, row) {
      var data = {
        code: "zg/getEmergence",
        data: {
          lockerId: row.deviceNum
        },
      }
      httpPost(data, this.$api.sendCommand).then(res => {
        if (res.success) {
          this.$message.success("获取成功")
          this.Emergence.password = res.data.data
          this.Emergence.device = row.deviceNum
          this.Emergence.name = row.roomName
          this.getEmergenceStatus = true
        } else {
          this.$message.error("获取失败")
        }
      })
    },
    // input视图刷新
    changesr(e) {
      this.$forceUpdate();
    },
    handleSelectionChange1(val) {
      this.multipleSelection1 = val;
    },
    BatchAdd() {
      this.uploadkj = true;
    },
    //批量添加确认
    batchUploadfun() {
      if (this.batchAccess == "") {
        this.$message.error("请选择运营商");
      } else if (this.multipleSelection1.length == 0) {
        this.$message.error("请勾选要批量添加的设备");
      } else {
        this.multipleSelection1.map((li, index) => {
          var str = {
            deviceNum: li.deviceNum,
            imei: li.imei,
            imsi: li.imei, //row.imsi,
            order: 5101,
            platformId: this.batchAccess,
            enterpriseId: this.userInfo.enterpriseId,
            manufactureId: this.manufacturer
          };
          RequestSet.RegisterDevice(str, (callback) => {
            if (callback.success) {
              this.$message.success("添加成功")
              this.editVisible = false;
              this.getdevice();
            } else {
              this.$message.error(callback.message)
            }
          })
        })
      }
    },
    //音量设置
    stepFun(val) {
      var operate = "00";
      if (val == '0') {
        operate = "00";
      } else if (val == 1) {
        operate = "01";
      } else if (val == 2) {
        operate = "02";
      }
      var data = {
        code: "isp/volumnSetting",
        data: {
          imei: this.formInline.imei,
          deviceNum: this.formInline.deviceNum,
          operate: operate,
          order: 61001
        },
      };
      httpPost(data, this.$api.sendCommand).then((res2) => {
        if (res2.data.success) {
          this.$message.success("设置成功");
        } else {
          this.$message.error(res.msg);
        }
      });
    },
    batchSetOpenMethods() {
      this.setopenStatus = true
    },
    // 取消常开设置
    UnsetMethods(e) {
      if (this.startHour > 24 || this.startHour < 0) {
        this.$message.error('请选择正确的开始时间段');
        return
      } else if (this.endHour > 24 || this.endHour < 0) {
        this.$message.error('请选择正确的结束时间段');
        return
      }
      if (e == 1) {
        var multipleSelection = []
        multipleSelection.push(this.formInline)
        multipleSelection.map(li => {
          var data = {
            code: "zg/longopen/operation",
            data: {
              order: 61101,
              roomName: li.roomName,
              opendDoorType: 0,
              imei: li.imei,
              lockerId: li.deviceNum,
              lockerUserId: li.iotId,
              startTime: moment(this.opendTime[0]).format('YYYY-MM-DD HH:mm:ss'),
              endTime: moment(this.opendTime[1]).format('YYYY-MM-DD HH:mm:ss'),
              openDoorSegmentList: [{
                startHour: this.startHour,
                endHour: this.endHour
              },
                // {
                //   startHour: 23,
                //   endHour: 24
                // },
              ]
            }
          }
          httpPost(data, this.$api.sendCommand).then((res2) => {
            if (res2.success) {
              this.$message.success("取消设置成功");
            } else {
              this.$message.error(res2.msg);
            }
          });
        })
      } else if (e == 2) {
        var multipleSelection = this.multipleSelection
        multipleSelection.map(li => {
          var data = {
            code: "zg/longopen/operation",
            data: {
              order: 61101,
              roomName: li.roomName,
              opendDoorType: 0,
              lockerId: li.deviceNum,
              lockerUserId: li.iotId,
              startTime: moment(this.opendTime[0]).format('YYYY-MM-DD HH:mm:ss'),
              endTime: moment(this.opendTime[1]).format('YYYY-MM-DD HH:mm:ss'),
              openDoorSegmentList: [{
                startHour: this.startHour,
                endHour: this.endHour
              },
                // {
                //   startHour: 23,
                //   endHour: 24
                // },
              ]
            }
          }
          httpPost(data, this.$api.sendCommand).then((res2) => {
            if (res2.success) {
              this.$message.success("取消设置成功");
            } else {
              this.$message.error(res2.msg);
            }
          });
        })
      }
    },
    setNormallyOpenMethodsAll() {
      if (this.startHour > 24 || this.startHour < 0) {
        this.$message.error('请选择正确的开始时间段');
        return
      } else if (this.endHour > 24 || this.endHour < 0) {
        this.$message.error('请选择正确的结束时间段');
        return
      }
      if (this.opendTime[0] == '') {
        this.$message.error('请选择开始日期');
        return
      }
      if (this.opendTime[1] == '') {
        this.$message.error('请选择结束日期');
        return
      }
      if (this.startHour != '' && this.endHour == '') {
        this.$message.error('请选择结束时间段');
        return
      }
      if (this.startHour == '' && this.endHour != '') {
        this.$message.error('请选择开始时间段');
        return
      }

      this.multipleSelection.map(li => {
        if (li.manufactureId == 201 || li.manufactureId == 221) {
          if (li.iotId) {
            var data = {
              code: "zg/longopen/operation",
              data: {
                order: 61101,
                roomName: li.roomName,
                opendDoorType: 1,
                lockerId: li.deviceNum,
                imei: li.imei,
                lockerUserId: li.iotId,
                startTime: moment(this.opendTime[0]).format('YYYY-MM-DD HH:mm:ss'),
                endTime: moment(this.opendTime[1]).format('YYYY-MM-DD HH:mm:ss'),
                openDoorSegmentList: [{
                  startHour: this.startHour,
                  endHour: this.endHour
                },
                ]
              }
            }
            if (this.startHour == '' && this.endHour == '') {
              data.data.openDoorSegmentList = []
            }
            httpPost(data, this.$api.sendCommand).then((res2) => {
              if (res2.success) {
                this.$message.success("设置成功");
                this.getAlwaysOpens()
              } else {
                this.$message.error(res2.msg);
              }
            });
          } else {
            this.$message.error('需要超管才可设置常开')
          }
        } else {
          this.$message.error('该类型锁不支持此设置！');
        }
      })
      setTimeout(() => {
        this.setopenStatus = false
      }, 2000)
    },
    // ZH常开
    setNormallyOpenMethods() {
      if (this.startHour > 24 || this.startHour < 0) {
        this.$message.error('请选择正确的开始时间段');
        return
      } else if (this.endHour > 24 || this.endHour < 0) {
        this.$message.error('请选择正确的结束时间段');
        return
      }
      if (this.formInline.manufactureId == 201 || this.formInline.manufactureId == 221) {
        if (this.opendTime[0] == '') {
          this.$message.error('请选择开始日期');
          return
        }
        if (this.opendTime[1] == '') {
          this.$message.error('请选择结束日期');
          return
        }
        if (this.startHour != '' && this.endHour == '') {
          this.$message.error('请选择结束时间段');
          return
        }
        if (this.startHour == '' && this.endHour != '') {
          this.$message.error('请选择开始时间段');
          return
        }
        var data = {
          code: "zg/longopen/operation",
          data: {
            order: 61101,
            opendDoorType: 1,
            roomName: this.formInline.roomName,
            lockerUserId: this.formInline.iotId,
            lockerId: this.formInline.deviceNum,
            startTime: moment(this.opendTime[0]).format('YYYY-MM-DD HH:mm:ss'),
            endTime: moment(this.opendTime[1]).format('YYYY-MM-DD HH:mm:ss'),
            openDoorSegmentList: [{
              startHour: this.startHour,
              endHour: this.endHour
            },
              // {
              //     startHour: 23,
              //     endHour: 24
              // },
            ]
          }
        }
        console.log(data)
        if (this.startHour == '' && this.endHour == '') {
          data.data.openDoorSegmentList = []
        }
        httpPost(data, this.$api.sendCommand).then((res2) => {
          if (res2.success) {
            this.$message.success("设置成功");
            this.getAlwaysOpens()
          } else {
            this.$message.error(res2.msg);
          }
        });
      } else {
        this.$message.error('该类型锁不支持此设置！');
      }
    },
    // 常开设置
    switchFun(e) {
      if (this.formInline.manufactureId == 101) {
        var data = {};
        this.formInline.isAlwaysOpenStatus = e
        if (e) {
          this.switchtext = "开";
          data = {
            code: "isp/alwaysOpenSetting",
            data: {
              imei: this.formInline.imei,
              deviceNum: this.formInline.deviceNum,
              operate: 1,
              roomName: this.formInline.roomName,
              order: 61101
            },
          };
        } else {
          this.switchtext = "关";
          data = {
            code: "isp/alwaysOpenSetting",
            data: {
              imei: this.formInline.imei,
              deviceNum: this.formInline.deviceNum,
              operate: 0,
              roomName: this.formInline.roomName,
              order: 61101
            },
          };
        }
        httpPost(data, this.$api.sendCommand).then((res2) => {
          if (res2.success) {
            this.$message.success("设置成功");
            this.getAlwaysOpens()
          } else {
            this.$message.error(res2.msg);
          }
        });
      } else if (this.formInline.manufactureId == 201 || this.formInline.manufactureId == 221) {
        // this.$message.success("该类型锁请通过蓝牙设置声音");
      }
    },
    // 关闭侧边栏
    handleClose() {
      this.drawer = false;
    },
    // tabs标签页切换
    handleClick(tab, event) {
      this.commpontentStatus = true
    },
    //查看门锁详情
    detailsFun(index, row) {
      this.drawer = true;
      if (row.isAlwaysOpen == 0) {
        row.isAlwaysOpenStatus = false
      } else if (row.isAlwaysOpen == 1) {
        row.isAlwaysOpenStatus = true
      }
      this.formInline = row;
      this.sendStatus = false
      this.$nextTick(function () {
        this.sendroomId = row.deviceNum
        this.senddeviceNum = row.deviceNum
        this.sendDevice = row
        this.sendStatus = true
        this.quantityFun()
        this.quantityFunOne()
        this.getAlwaysOpens()
        // this.quantityFunThree()
      })
    },
    Reset1(index, row) {
      var data2 = {
        code: "isp/restoreSetting",
        data: {
          order: 6501,
          imei: row.imei,
          deviceNum: row.deviceNum,
          managerTelephone: "18270949468",
          managerPassword: "202108",
        },
      };
      httpPost(data2, this.$api.sendCommand).then((res2) => {
        // if (res2.data.success) {
        //   this.$message.success("重置成功");
        // } else {
        //   this.$message.error(res.msg);
        // }
      });
    },
    // 重置门锁
    Reset(index, row) {
      this.$confirm("是否确认重置门锁?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        if (row.manufactureId == 201 || row.manufactureId == 221) {
          var data3 = {
            code: "zg/deleteAllUsers",
            data: {
              lockerId: row.deviceNum,
              imei: row.imei,
              order: 6501,
              cardName: this.userInfo.username,
              roomName: row.roomName
            },
          };
          httpPost(data3, this.$api.sendCommand).then((res) => {
            if (res.success) {
              this.$message.success("重置成功");
              var q = {
                id: row.roomId,
              };
              var tenant = {
                q: JSON.stringify(q),
              };
              httpGet(tenant, this.$api.getSiteTenant).then((res) => {
                Promise.all(
                  res.data.list.map((element) => {
                    return new Promise(function (resolve, reject) {
                      resolve(element.cardId);
                    });
                  })
                ).then((allId) => {
                  allId.map((li) => {
                    var str = [{
                      siteId: row.roomId,
                      cardId: li,
                    },];
                    httpPost(str, this.$api.unbindCard).then((res) => { });
                  });
                })
              })
            } else {
              this.$message.success(res.msg);
            }
          });
        } else if (row.manufactureId == 101) {
          var data2 = {
            code: "isp/restoreSetting",
            data: {
              order: 6501,
              imei: row.imei,
              deviceNum: row.deviceNum,
              managerTelephone: "18270949468",
              managerPassword: "202108",
              cardName: this.userInfo.username,
              roomName: row.roomName
            },
          };
          httpPost(data2, this.$api.sendCommand).then((res2) => {
            if (res2.success) {
              this.$message.success("重置成功");
              var q = {
                id: row.roomId,
              };
              var tenant = {
                q: JSON.stringify(q),
              };
              httpGet(tenant, this.$api.getSiteTenant).then((res) => {
                Promise.all(
                  res.data.list.map((element) => {
                    return new Promise(function (resolve, reject) {
                      resolve(element.cardId);
                    });
                  })
                ).then((allId) => {
                  allId.map((li) => {
                    var str = [{
                      siteId: row.roomId,
                      cardId: li,
                    },];
                    httpPost(str, this.$api.unbindCard).then((res) => { });
                  });
                })
              })
            } else {
              this.$message.error(res2.msg);
            }
          });
        }
      });
    },
    activeiconfun(t) {
      this.activeiconfont = t;
    },
    // 查询设备电量和信号
    getresult() {
      var data = {};
    },
    // 输入远程开锁密码确认
    Unlockingsave() { },
    // 远程开锁
    RemoteUnlocking(index, row) {
      var str2 = {
        imei: row.imei,
        openLockType: 2,
        is: true,
        roomName: row.roomName,
        roomId: row.roomId,
        cardName: this.userInfo.username
      };
      httpPost(str2, this.$api.openLock).then((res3) => {
        if (res3.success) {
          this.$message.success("开锁成功！");
          this.Unlocking = false;
        } else {
          this.$message.error("开锁失败！");
        }
      });
    },
    // 批量初始化
    batchInit() {
      if (this.multipleSelection.length == 0) {
        this.$message.error("请选择初始化设备");
        return;
      }
      this.$confirm("确定要批量初始化吗？", "提示", {
        type: "warning",
      })
        .then(() => {
          this.multipleSelection.map(row => {
            if (row.manufactureId == 101) {
              var str = {
                deviceNum: row.deviceNum,
                imei: row.imei,
                order: 6101,
              };
              httpPost(str, this.$api.getDeviceRegisterManager).then((res1) => {
                if (res1.data.success) {
                  var str1 = {
                    imei: row.imei, //row.imsi,
                    deviceNum: row.deviceNum, //row.deviceNum,
                    operateMode: 7,
                    is: true,
                    order: 6207,
                    pass: false,
                    passwordStartTime: "20210813010101",
                    passwordEndTime: "20680813010101",
                  };
                  httpPost(str1, this.$api.getDeviceOperateUserInfo).then((res2) => { });
                  var str2 = {
                    imei: row.imei, //row.imsi,
                    deviceNum: row.deviceNum, //row.deviceNum,
                    operateMode: 4,
                    is: true,
                    order: 6204,
                    pass: false,
                    passwordStartTime: "20210813010101",
                    passwordEndTime: "20680813010101",
                  };
                  httpPost(str2, this.$api.getDeviceOperateUserInfo).then((res3) => {
                    if (res3.success) {
                      this.$message.success("初始化成功");
                    }
                  });
                } else {
                  this.$message.error(res1.data.msg)
                }
              });
            }
          })
        })
    },
    // 重置添加管理员
    AddAdministrator(index, row) {
      this.$confirm("确定要初始化吗？", "提示", {
        type: "warning",
      })
        .then(() => {
          var str = {
            deviceNum: row.deviceNum,
            imei: row.imei,
            order: 6101,
          };
          httpPost(str, this.$api.getDeviceRegisterManager).then((res1) => {
            if (res1.data.success) {
              var str1 = {
                imei: row.imei, //row.imsi,
                deviceNum: row.deviceNum, //row.deviceNum,
                operateMode: 7,
                is: true,
                order: 6207,
                pass: false,
                passwordStartTime: "20210813010101",
                passwordEndTime: "20680813010101",
              };
              httpPost(str1, this.$api.getDeviceOperateUserInfo).then((res2) => { });
              var str2 = {
                imei: row.imei, //row.imsi,
                deviceNum: row.deviceNum, //row.deviceNum,
                operateMode: 4,
                is: true,
                order: 6204,
                pass: false,
                passwordStartTime: "20210813010101",
                passwordEndTime: "20680813010101",
              };
              httpPost(str2, this.$api.getDeviceOperateUserInfo).then((res3) => {
                if (res3.success) {
                  this.$message.success("初始化成功");
                }
              });
            } else {
              this.$message.error(res1.data.msg)
            }
          });
        })
    },
    // 添加设备
    initialization() {
      if (this.checkNodeId1 == '') {
        this.$message.error("请选择房间");
      } else {
        if (this.form.manufacturer == 101 || this.form.manufacturer == 1201 || this.form.manufacturer == 1241) {
          if (
            this.form.deviceNum == "" ||
            this.form.v == "" ||
            this.form.platformId == ""
          ) {
            this.$message.error("请填写完整信息");
          } else {
            var data = {}
            var data = {
              deviceNum: this.form.deviceNum,
              imei: this.form.imei,
              imsi: this.form.imei, //row.imsi,
              order: 5101,
              enterpriseId: this.userInfo.enterpriseId,
              platformId: this.form.platformId,
              manufactureId: this.form.manufacturer,
            };
            RequestSet.RegisterDevice(data, (callback) => {
              if (callback.data.success && callback.success) {
                var data = [{
                  siteId: this.checkNodeId1,
                  deviceId: callback.data.id,
                }];
                httpPost(data, this.$api.bindDeviceSite).then((res) => {
                  if (res.success) {
                    this.$message.success("绑定成功");
                    this.editVisible = false
                    if (this.form.manufacturer == 1241) {
                      let data3 = {
                        code: "lwj/registerSupperAdmin",
                        data:{
                          lockerId: this.form.deviceNum,
                          lockerSuperAdminId: this.form.TockerSuperAdminId,
                          bluetoothMac: this.form.LockMac
                        }
                      }
                      httpPost(data3, this.$api.sendCommand).then(res => {
                        console.log(res);
                        if(res.success) {
                          this.$message.success('注册成功')
                        }else{
                          this.$message.error('注册失败，请稍后再试')
                        }
                      })
                    }
                  }
                  this.getdevice();
                }).catch((error) => {
                  this.$message.error(`绑定失败`);
                });
            this.$message.success(res.data.msg);
            this.editVisible = false;
            this.getdevice();
          } else {
          this.$message.error(callback.data.msg)
        }
      })
    }
  } else if(this.form.manufacturer == 201 || this.form.manufacturer == 221) {
  var data = {
    lockerId: this.form.lockerId,
    imei: this.form.imei,
    customerCode: this.form.customerCode,
    lockerSuperAdminId: this.form.lockerSuperAdminId,
    authKey: this.form.authKey,
    type: this.form.type,
    manufactureId: this.form.manufacturer,
    enterpriseId: this.userInfo.enterpriseId,
    order: 5101,
  };
  RequestSet.RegisterDevice(data, (callback) => {
    if (callback.data.success && callback.success) {
      var data = [{
        siteId: this.checkNodeId1,
        deviceId: callback.data.id,
      }];
      httpPost(data, this.$api.bindDeviceSite)
        .then((res) => {
          if (res.success) {
            this.$message.success("绑定成功");

            this.editVisible = falsethis.editVisible = false
            this.getdevice();
          }
        })
        .catch((error) => {
          this.$message.error(`绑定失败`);
        });
      this.$message.success("添加成功");
      this.editVisible = false;
      this.getdevice();
    } else {
      this.$message.error(callback.data.msg);
    }
  })
} else if (this.form.manufacturer == 701) {
  var data = {
    deviceNum: this.form.deviceNum,
    validateCode: this.form.validateCode,
    manufactureId: this.form.manufacturer,
    enterpriseId: this.userInfo.enterpriseId,
  }
  RequestSet.RegisterDevice(data, (callback) => {
    if (callback.data.success && callback.success) {
      var data = [{
        siteId: this.checkNodeId1,
        deviceId: callback.data.id,
      }];
      httpPost(data, this.$api.bindDeviceSite)
        .then((res) => {
          if (res.success) {
            this.$message.success("绑定成功");
            this.editVisible = false
            this.getdevice();
          }
        })
        .catch((error) => {
          this.$message.error(`绑定失败`);
        });
      this.$message.success("添加成功");
      this.editVisible = false;
      this.getdevice();
    } else {
      this.$message.error(callback.data.msg);
    }
  })
} else if (this.form.manufacturer == 1241) {
  if (this.form.deviceNum == "") {
    this.$message.error("请填写完整信息")
  } else {
    var data = {
      deviceNum: this.form.deviceNum,
      imei: "",
      imsi: "",
      platformId: 9,
      manufactureId: 1241
    }
    RequestSet.RegisterDevice(data, (callback) => {
      if (callback.data.success && callback.success) {
        console.log(callback);
        var data = [{
          siteId: this.checkNodeId1,
          deviceId: callback.data.id
        }]
        httpPost(data, this.$api.bindDeviceSite).then(res => {
          console.log(res);
          if (res.success) {
            this.$message.success("绑定成功")
            this.editVisible = false
            this.getdevice()
          }
        }).catch(error => {
          this.$message.error("绑定失败", error)
        })
        // this.$message.success(res.data.msg)
        // this.editVisible = false
        // this.getdevice();
      } else {
        this.$message.error(callback.data.msg)
      }
    })
  }
}
      }
    },
// 选择绑定房间
onClick: function (evt, treeId, treeNode) {
  // 点击事件
  this.treedata = treeNode;
},
// 获取绑定所有房间
getalllist() {
  var data = {};
  httpGet(data, this.$api.getTree).then((res) => {
    var array = uniqueArray(res.data, "id");
    this.zNodes = ztreeToElementTree(array, {});
  });
},
// 获取设备
getdevice() {
  var q = {
    isOnline: this.search.isOnline,
    roomName: this.search.roomname,
    roomIds: this.checkNodeId,
    startBattery: this.search.startBattery,
    endBattery: this.search.endBattery,
    lockType: 1,
    unBind: this.search.unBind,
    firmwareVersion: this.search.firmwareVersion,
    isUsed: this.search.isUsed,
    iccid: this.search.iccid,
    rssiStart: this.search.rssiStart,
    rssiEnd: this.search.rssiEnd,
    createStart: this.search.createStart,
    createEnd: this.search.createEnd,
    isAppBind: this.search.isAppBind
  };
  if (q.isOnline == 2) {
    delete q.isOnline
  }
  let qObject = utils.validObject(q)
  var data = {
    q: JSON.stringify(qObject),
    pageNum: 1,
    pageSize: 10
  };
  httpPost(data, this.$api.getDeviceItems).then((res) => {
    var online = 0,
      unonline = 0,
      devIds = "";
    res.data.list.map((li) => {
      if (li.isOnline == 1) {
        online++;
      } else if (li.isOnline == 0) {
        unonline++;
      }
      let accessPlatform = this.accessPlatform.show.filter(item => item.code == li.accessPlatform)[0]
      if (accessPlatform) {
        li['accessPlatformText'] = accessPlatform.desc
      } else {
        li['accessPlatformText'] = ''
      }
      let deviceType = this.accessPlatform.deviceType.filter(item => item.code == li.manufactureId)[0]
      if (deviceType) {
        li['manufactureIdText'] = deviceType.desc
      } else {
        li['manufactureIdText'] = ''
      }
      li.createAt = moment(li.createAt).format("YYYY-MM-DD HH:mm:ss");
      if (li.lastReportAt) {
        li.lastReportAt = moment(li.lastReportAt).format("YYYY-MM-DD HH:mm:ss");
      } else {
        li['lastReportAt'] = ''
      }
      devIds += li.deviceNum + ",";
    });
    var newArr = uniqueArray(res.data.list, "id");
    this.tableData = newArr;
    this.currentPage4 = 1;
    this.pageTotal = res.data.total;
  });
},
timestampToTime(cjsj) {
  var date = new Date(cjsj); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
  var Y = date.getFullYear() + "-";
  var M =
    (date.getMonth() + 1 < 10 ?
      "0" + (date.getMonth() + 1) :
      date.getMonth() + 1) + "-";
  var D = date.getDate() + " ";
  var h = date.getHours() + ":";
  var m = date.getMinutes() + ":";
  var s = date.getSeconds();
  return Y + M + D + h + m + s;
},
handleChange(value) {
  console.log(value);
},
restSearch() {
  this.search = {
    name: "",
    deviceNum: "",
    roomname: '',
    imei: "",
    isOnline: "",
    unBind: '',
    startBattery: '',
    endBattery: '',
    firmwareVersion: '',
    operationStatus: ''
  }
  this.checkNodeId = ''
  this.searchRoom = ''
  this.normallyPageNum = 1
  this.pageSize = 10
  this.handleSearch()
},
// 设备状态统计筛选
screenStatisticsItemsMethods(data) {
  httpPost(data, this.$api.screenStatisticsItems).then(res => {
    console.log(res);
    if (res.code == 200) {
      var sumpageTotal = 0, online = 0, unonline = 0, abnormal = 0
      res.data.map(li => {
        if (li.isAppBind == 1) {
          abnormal++
        }
        if (li.isOnline == '0') {
          unonline++
        }
        if (li.isOnline == '1') {
          online++
        }
      })
      this.sumpageTotal = res.data.length
      this.online = online
      this.unonline = unonline
      this.abnormal = abnormal
    }
  })
},
// 触发搜索按钮
handleSearch() {
  this.normallyPageNum = 1
  var deviceNum = this.search.deviceNum.replace(/\s*/g, "");
  var imei = this.search.imei.replace(/\s*/g, "");
  if (this.search.isOnline == 2) {
    this.search.isAppBind = 1
  } else {
    this.search.isAppBind = ''
  }
  var q = {
    deviceNum: deviceNum,
    imei: imei,
    isOnline: this.search.isOnline,
    roomName: this.search.roomname,
    roomIds: this.checkNodeId,
    startBattery: this.search.startBattery,
    endBattery: this.search.endBattery,
    lockType: 1,
    unBind: this.search.unBind,
    firmwareVersion: this.search.firmwareVersion,
    isUsed: this.search.isUsed,
    iccid: this.search.iccid,
    rssiStart: this.search.rssiStart,
    rssiEnd: this.search.rssiEnd,
    createStart: this.search.createStart,
    createEnd: this.search.createEnd,
    isAppBind: this.search.isAppBind
  };
  if (q.isOnline == 2) {
    delete q.isOnline
  }
  let qObject = utils.validObject(q)
  let data = {
    q: JSON.stringify(qObject),
    pageNum: 1,
    pageSize: this.pageSize,
  };
  this.screenStatisticsItemsMethods(data)
  httpPost(data, this.$api.getDeviceItems).then((res) => {
    if (res.data.list.length > 0) {
      res.data.list.map((li) => {
        var accessPlatform = this.accessPlatform.show.filter(item => item.code == li.accessPlatform)[0]
        if (accessPlatform) {
          li['accessPlatformText'] = accessPlatform.desc
        } else {
          li['accessPlatformText'] = ''
        }
        let deviceType = this.accessPlatform.deviceType.filter(item => item.code == li.manufactureId)[0]
        if (deviceType) {
          li['manufactureIdText'] = deviceType.desc
        } else {
          li['manufactureIdText'] = ''
        }
        li.createAt = moment(li.createAt).format("YYYY-MM-DD HH:mm:ss");
        if (li.lastReportAt) {
          li.lastReportAt = moment(li.lastReportAt).format("YYYY-MM-DD HH:mm:ss");
        } else {
          li['lastReportAt'] = ''
        }
      });
      var newArr = uniqueArray(res.data.list, "id");
      this.pageTotal = res.data.total
      this.tableData = newArr;
    } else {
      this.tableData = [];
      this.pageTotal = 0
    }
    this.currentPage4 = 1;
    this.$store.commit("increment", 1);
  });
  // this.$set(this.query, "pageIndex", 1);
},
// 删除操作
handleDelete(index) {
  // 二次确认删除
  this.$confirm("确定要删除吗？", "提示", {
    type: "warning",
  })
    .then(() => {
      this.$message.success("删除成功");
      this.tableData.splice(index, 1);
    })
    .catch(() => { });
},
// 多选操作
handleSelectionChange(val) {
  this.multipleSelection = val;
},
// 批量远程开锁
batchRemoteUnlocking() {
  this.$confirm("确定要批量远程开锁吗？", "提示", {
    type: "warning",
  })
    .then(() => {
      this.multipleSelection.map(li => {
        if (li.manufactureId == 101) {
          var str2 = {
            imei: li.imei,
            openLockType: 2,
            is: true,
            roomName: li.roomName,
            roomId: li.roomId,
            cardName: this.userInfo.username
          };
          httpPost(str2, this.$api.openLock).then((res3) => {
            if (res3.success) {
              this.$message.success("开锁成功！");
            } else {
              this.$message.error("开锁失败！");
            }
          });
        }
      })
    })
},
delAllSelection() {
  const length = this.multipleSelection.length;
  let str = "";
  this.delList = this.delList.concat(this.multipleSelection);
  for (let i = 0; i < length; i++) {
    str += this.multipleSelection[i].name + " ";
  }
  this.$message.error(`删除了${str}`);
  this.multipleSelection = [];
},
// 删除设备
deleteLock(index, row) {
  this.$confirm("确定要删除吗？", "提示", {
    type: "warning",
  })
    .then(() => {
      // if (row.manufactureId == 101) {
      if (row.roomId) {
        var q = {
          id: row.roomId,
        };
        var tenant = {
          q: JSON.stringify(q),
        };
        httpGet(tenant, this.$api.getSiteTenant).then((res) => {
          Promise.all(
            res.data.list.map((element) => {
              return new Promise(function (resolve, reject) {
                resolve(element.cardId);
              });
            })
          ).then((allId) => {
            var str = []
            allId.map((li) => {
              var obj = {
                siteId: row.roomId,
                cardId: li,
              }
              str.push(obj)
            });
            if (str.length > 0) {
              httpPost(str, this.$api.unbindCard).then((res) => { });
            }
            var data1 = [{
              siteId: row.roomId,
              deviceId: row.id,
            }];
            httpPost(data1, this.$api.unbindDeviceSite).then((res) => {
              if (res.success) {
                this.$message.success("解绑成功");
                var data = {
                  deviceNum: row.deviceNum,
                  imei: row.imei,
                  order: 5102
                }
                RequestSet.DeleteDevic(data, row.manufactureId, (callback => {
                  if (callback.success) {
                    this.getdevice();
                    this.$message.success('删除成功');
                  } else {
                    this.getdevice();
                    this.$message.error(callback.msg);
                  }
                }))
              } else {
                this.getdevice();
                this.$message.error(`解绑失败`);
              }
            });
          })
        })
      } else {
        var data = {
          deviceNum: row.deviceNum,
          imei: row.imei,
          order: 5102,
        };
        RequestSet.DeleteDevic(data, row.manufactureId, (callback) => {
          if (callback.success) {
            this.$message.success("删除成功");
            this.getdevice();
          } else {
            this.getdevice();
            this.$message.error(callback.msg);
          }
        })
      }
    }).catch((err) => {
      this.getdevice();
      this.$message.error(err.msg);
    });
},
// 绑定房间
bindRoom(index, row) {
  this.bromm = row;
  this.roomVisible = true;
  this.$refs.tree.setCheckedKeys([]);
},
// 确定绑定
bindsave() {
  var treedata = this.treedata;
  this.roomVisible = false;
  var data = [{
    siteId: treedata.id,
    deviceId: this.bromm.id,
  },];
  httpPost(data, this.$api.bindDeviceSite)
    .then((res) => {
      if (res.success) {
        this.$message.success("绑定成功");
        this.getdevice();
      }
    })
    .catch((error) => {
      this.$message.error(`绑定失败`);
    });
},
unbindsave(index, row) {
  var data = [{
    siteId: row.roomId,
    deviceId: row.id,
  },];
  var q = {
    id: row.roomId,
  };
  var tenant = {
    q: JSON.stringify(q),
  };
  // 二次确认解绑
  this.$confirm("确定要解绑吗？", "提示", {
    type: "warning",
  })
    .then(() => {
      // this.Reset(index, row)
      httpGet(tenant, this.$api.getSiteTenant).then((res) => {
        Promise.all(
          res.data.list.map((element) => {
            return new Promise(function (resolve, reject) {
              resolve(element.cardId);
            });
          })
        ).then((allId) => {
          allId.map((li) => {
            var str = [{
              siteId: row.roomId,
              cardId: li,
            },];
            httpPost(str, this.$api.unbindCard).then((res) => { });
          });
          httpPost(data, this.$api.unbindDeviceSite).then((res) => {
            if (res.success) {
              this.$message.success("解绑成功");
              this.getdevice();
            } else {
              this.$message.error(`解绑失败`);
            }
          });
        });
      });
    })
    .catch(() => { });
},
addequipment() {
  this.form.customerCode = this.$store.state.customerCode;
  this.editVisible = true;
},
// 编辑操作
handleEdit(index, row) {
  this.idx = index;
  this.form = row;
  this.editVisible = true;
},
// 保存编辑
saveEdit() {
  this.editVisible = false;
},
handleSizeChange(val) {
  this.normallyPageNum = 1
  this.$router.replace({
    path: this.$route.path,
    query: {
      page: this.$route.query.page ? this.$route.query.page : 1,
      pageSize: val,
    },
  });
  this.pageSize = val
  // this.getlistNum(1, val);
  this.handleSearch()
},
getlistNum(val, size) {
  var deviceNum = this.search.deviceNum.replace(/\s*/g, "");
  var imei = this.search.imei.replace(/\s*/g, "");
  var q = {
    deviceNum: deviceNum,
    imei: imei,
    isOnline: this.search.isOnline,
    roomName: this.search.roomname,
    roomIds: this.checkNodeId,
    startBattery: this.search.startBattery,
    endBattery: this.search.endBattery,
    lockType: 1,
    unBind: this.search.unBind,
    firmwareVersion: this.search.firmwareVersion,
    isUsed: this.search.isUsed,
    iccid: this.search.iccid,
    rssiStart: this.search.rssiStart,
    rssiEnd: this.search.rssiEnd,
    createStart: this.search.createStart,
    createEnd: this.search.createEnd,
    isAppBind: this.search.isAppBind
  };
  if (q.isOnline == 2) {
    delete q.isOnline
  }
  var qObject = utils.validObject(q)
  var data = {
    q: JSON.stringify(qObject),
    pageNum: val,
    pageSize: size,
  };
  httpPost(data, this.$api.getDeviceItems).then((res) => {
    res.data.list.map((li) => {
      var accessPlatform = this.accessPlatform.show.filter(item => item.code == li.accessPlatform)[0]
      if (accessPlatform) {
        li['accessPlatformText'] = accessPlatform.desc
      } else {
        li['accessPlatformText'] = ''
      }
      let deviceType = this.accessPlatform.deviceType.filter(item => item.code == li.manufactureId)[0]
      if (deviceType) {
        li['manufactureIdText'] = deviceType.desc
      } else {
        li['manufactureIdText'] = ''
      }
      li.createAt = moment(li.createAt).format("YYYY-MM-DD HH:mm:ss");
      if (li.lastReportAt) {
        li.lastReportAt = moment(li.lastReportAt).format("YYYY-MM-DD HH:mm:ss");
      } else {
        li['lastReportAt'] = ''
      }
    });
    var newArr = uniqueArray(res.data.list, "id");
    this.tableData = newArr;
    this.pageTotal = res.data.total;
  });
},
// 分页导航
handlePageChange(val) {
  // this.$router.replace({
  //   path: this.$route.path,
  //   query: {
  //     page: this.$route.query.page ? this.$route.query.page : 1,
  //     pageSize: val,
  //   },
  // });
  this.pageNum = val
  this.normallyPageNum = val
  this.$store.commit("increment", val);
  var q = {
    deviceNum: this.search.deviceNum,
    imei: this.search.imei,
    isOnline: this.search.isOnline,
    roomName: this.search.roomname,
    roomIds: this.checkNodeId,
    startBattery: this.search.startBattery,
    endBattery: this.search.endBattery,
    lockType: 1,
    unBind: this.search.unBind,
    firmwareVersion: this.search.firmwareVersion,
    isUsed: this.search.isUsed,
    iccid: this.search.iccid,
    rssiStart: this.search.rssiStart,
    rssiEnd: this.search.rssiEnd,
    createStart: this.search.createStart,
    createEnd: this.search.createEnd,
    isAppBind: this.search.isAppBind
  };
  if (q.isOnline == 2) {
    delete q.isOnline
  }
  var qObject = utils.validObject(q)
  var data = {
    q: JSON.stringify(qObject),
    pageNum: val,
    pageSize: this.pageSize,
  };
  httpPost(data, this.$api.getDeviceItems).then((res) => {
    res.data.list.map((li) => {
      var accessPlatform = this.accessPlatform.show.filter(item => item.code == li.accessPlatform)[0]
      if (accessPlatform) {
        li['accessPlatformText'] = accessPlatform.desc
      } else {
        li['accessPlatformText'] = ''
      }
      let deviceType = this.accessPlatform.deviceType.filter(item => item.code == li.manufactureId)[0]
      if (deviceType) {
        li['manufactureIdText'] = deviceType.desc
      } else {
        li['manufactureIdText'] = ''
      }
      li.createAt = moment(li.createAt).format("YYYY-MM-DD HH:mm:ss");
      if (li.createAt) { }
      if (li.lastReportAt) {
        li.lastReportAt = moment(li.lastReportAt).format("YYYY-MM-DD HH:mm:ss");
      } else {
        li['lastReportAt'] = ''
      }
    });
    var newArr = uniqueArray(res.data.list, "id");
    this.tableData = newArr;
    this.pageTotal = res.data.total;
  });
},
btnClick() {
  document.querySelector(".input-file").click();
},
exportBtn() {
  this.exportExcel()
},
exportExcel() {
  let sheet1data = [
    ['设备号', 'mac地址', 'sn', 'imei', 'app绑定号', '生产写入号']
  ]
  var sheet1 = XLSX.utils.json_to_sheet(sheet1data, {
    skipHeader: true,
  })
  // 创建一个新的空的workbook
  var wb = XLSX.utils.book_new()
  XLSX.utils.book_append_sheet(wb, sheet1, '设备导入模板')
  // XLSX.utils.book_append_sheet(wb, sheet2, '行政部')
  // XLSX.utils.book_append_sheet(wb, sheet3, '前端部')
  const workbookBlob = this.workbook2blob(wb)
  this.openDownloadDialog(workbookBlob, '设备导入模板.xlsx')
},
// 下载模板
workbook2blob(workbook) {
  // 生成excel的配置项
  var wopts = {
    // 要生成的文件类型
    bookType: 'xlsx',
    // // 是否生成Shared String Table，官方解释是，如果开启生成速度会下降，但在低版本IOS设备上有更好的兼容性
    bookSST: false,
    type: 'binary'
  }
  var wbout = XLSX.write(workbook, wopts)
  // 将字符串转ArrayBuffer
  function s2ab(s) {
    var buf = new ArrayBuffer(s.length)
    var view = new Uint8Array(buf)
    for (var i = 0; i !== s.length; ++i) view[i] = s.charCodeAt(i) & 0xff
    return buf
  }
  let buf = s2ab(wbout)
  var blob = new Blob([buf], {
    type: 'application/octet-stream'
  })
  return blob
},
// 将blob对象 创建bloburl,然后用a标签实现弹出下载框
openDownloadDialog(blob, fileName) {
  if (typeof blob === 'object' && blob instanceof Blob) {
    blob = URL.createObjectURL(blob) // 创建blob地址
  }
  var aLink = document.createElement('a')
  aLink.href = blob
  // HTML5新增的属性，指定保存文件名，可以不要后缀，注意，有时候 file:///模式下不会生效
  aLink.download = fileName || ''
  var event
  if (window.MouseEvent) event = new MouseEvent('click')
  //   移动端
  else {
    event = document.createEvent('MouseEvents')
    event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null)
  }
  aLink.dispatchEvent(event)
},
exportData(event) {
  if (!event.currentTarget.files.length) {
    return;
  }
  const that = this;
  // 拿取文件对象
  var f = event.currentTarget.files[0];
  // 用FileReader来读取
  var reader = new FileReader();
  // 重写FileReader上的readAsBinaryString方法
  FileReader.prototype.readAsBinaryString = function (f) {
    var binary = "";
    var wb; // 读取完成的数据
    var outdata; // 你需要的数据
    var reader = new FileReader();
    reader.onload = function (e) {
      // 读取成Uint8Array，再转换为Unicode编码（Unicode占两个字节）
      var bytes = new Uint8Array(reader.result);
      var length = bytes.byteLength;
      for (var i = 0; i < length; i++) {
        binary += String.fromCharCode(bytes[i]);
      }
      // 接下来就是xlsx了，具体可看api
      wb = XLSX.read(binary, {
        type: "binary",
      });
      outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]);
      // 自定义方法向父组件传递数据
      let arr1 = [];
      outdata.map((li, index) => {
        var str = {};
        str.deviceNum = li["设备号"];
        str.mac = li["mac地址"];
        str.imei = li["imei"];
        str.app = li["app绑定号"];
        str.write = li["生产写入号"];
        arr1.push(str);
      });
      //   this.tableData=arr
      that.userlist1statu = false;
      that.$nextTick(() => {
        that.userlist2 = arr1;
        that.userlist1statu = true;
      });
    };
    reader.readAsArrayBuffer(f);
  };
  reader.readAsBinaryString(f);
},
  },
};
</script>

<style scoped>
.handle-box {
  position: relative;
  margin-bottom: 20px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 300px;
  display: inline-block;
}

.table {
  width: 100%;
  font-size: 14px;
}

.red {
  color: #ff0000;
}

.mr10 {
  margin-right: 10px;
}

.mright {
  margin-right: 10px;
  display: inline-block;
}

.table-td-thumb {
  display: block;
  margin: auto;
  width: 40px;
  height: 40px;
}

.elrow {
  margin-bottom: 20px;
}

.grid-content {
  position: relative;
  z-index: 99;
  display: flex;
  align-items: center;
  overflow: hidden;
  justify-content: space-around;
  -webkit-box-align: center;
}

/* 加的 */

.colposition {
  display: flex;
  align-items: center;
  position: relative;
  box-sizing: border-box;
  border: 2px solid hsla(0, 0%, 100%, 0.2);
  /* width: 100%; */
}

.grid-cont-right {
  flex: 1;
  text-align: left;
  padding-left: 20px;
  box-sizing: border-box;
  font-size: 16px;
  color: #666;
  font-size: 14px;
  line-height: 32px;
}

.grid-num {
  font-size: 24px;
}

.grid-con-icon {
  font-size: 50px;
  width: 100px;
  height: 100px;
  text-align: center;
  line-height: 100px;
  color: #fff;
}

.grid-con-1 {
  position: relative;
}

.grid-con-1::before {
  position: absolute;
  content: "";
  top: 50%;
  right: 0;
  width: 1px;
  transform: translateY(-50%);
  height: 70px;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  border-left: 1px dashed #666;
}

.grid-con-1 .grid-con-icon {
  background: rgb(45, 140, 240);
}

.grid-con-1 .grid-num {
  /* color: rgb(45, 140, 240); */
  color: #333;
}

.grid-con-2 .grid-con-icon {
  background: rgb(100, 213, 114);
}

.grid-con-2 .grid-num {
  /* color: rgb(45, 140, 240); */
  color: #333;
}

.grid-con-3 .grid-con-icon {
  background: rgb(242, 94, 67);
}

.grid-con-3 .grid-num {
  color: rgb(242, 94, 67);
}

.container {
  position: relative;
}

.container .el-table th>.cell {
  text-align: center;
  font-size: 14px;
}

.container>>>.el-table .cell {
  text-align: center;
  font-size: 14px;
}

.container>>>.el-table .el-table__row .el-table__cell {
  padding: 10px 0;
}

.table .iconfont {
  font-size: 24px;
  vertical-align: middle;
}

.red {
  color: red;
}

.green {
  color: #49ce6c;
}

.orange {
  color: #ff9602;
}

.blue {
  color: #4a90e2;
}

.dling {
  min-width: 32px;
  display: inline-block;
}

.sapnli {
  vertical-align: middle;
}

.spanbg {
  padding: 4px 10px;
  background: #4a90e2;
  color: #fff;
  width: 80px;
  display: inline-block;
  font-size: 12px;
  box-sizing: border-box;
  border-radius: 4px;
}

.pagelist {
  margin-top: 20px;
  text-align: right;
}

.ztree {
  height: 300px;
  overflow-y: auto;
}

.roomcontent {
  margin-top: 50px;
  height: 450px;
  overflow: auto;
}

.roomcontent .roomconli {
  display: inline-block;
  cursor: pointer;
  position: relative;
}

.taball {
  width: 100%;
  margin-top: 50px;
}

.button-list {
  position: absolute;
  width: 300px;
  height: 200px;
  background: rgba(0, 0, 0, 0.5);
  top: 0;
  left: 0;
  border-radius: 10px;
  -ms-flex-wrap: wrap;
  flex-wrap: wrap;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  padding: 0 10px;
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -ms-flex-line-pack: center;
  align-content: center;
  -webkit-box-align: center;
  -ms-flex-align: center;
  align-items: center;
  -webkit-box-pack: center;
  -ms-flex-pack: center;
  justify-content: center;
  display: none;
}

.button-list div {
  /* width: 55px; */
  padding: 0 14px;
  height: 25px;
  background: rgba(0, 0, 0, 0.4);
  border-radius: 13px;
  margin: 0 5px 10px;
  font-size: 14px;
  font-family: Microsoft YaHei;
  font-weight: 700;
  color: #dedede;
  cursor: pointer;
  text-align: center;
  line-height: 25px;
}

.roomcontent .roomconli:hover .button-list {
  display: flex;
}

.roomcontentheight {
  height: 640px;
  overflow-y: auto;
}

.switchiconfont {
  position: absolute;
  top: 4px;
  right: 4px;
  background: #fff;
  color: #333;
  display: flex;
}

.switchiconfont .iconfont {
  font-size: 16px;
  padding: 4px 6px;
  border: 1px solid #dcdfe6;
  cursor: pointer;
}

.switchiconfont .active {
  color: #fff;
  cursor: pointer;
  background: #FA8E00;
  border: 1px solid #FA8E00;
}

.rltable {
  box-sizing: border-box;
  margin: 0 20px;
}

.demo-form-inline .el-form-item {
  width: 46%;
}

.demo-form-inline>>>.el-form-item .el-form-item__label {
  width: 22%;
}

.demo-form-inline>>>.el-form-item .el-form-item__content {
  width: 78%;
}

.input-file {
  display: none;
}

.width100 {
  width: 8vw;
  margin-bottom: 10px;
}

.quantity {
  display: inline-block;
}

.quantity .w50 {
  width: 1.5rem;
}

.position-father {
  position: relative;
  display: inline-block;
}

.contentSearch {
  position: absolute;
  padding: .25rem;
  left: 50%;
  transform: translateX(-50%);
  top: .5rem;
  z-index: 999;
  border: 1px solid #ebeef5;
  box-shadow: 0 2px 12px 0 rgb(0 0 0 / 40%);
  border-radius: 10px;
  background: #fff;
  width: 8rem;
  cursor: pointer;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}

.contentSearch .width100 {
  width: 49%;
  margin-bottom: .25rem;
}

.contentSearch .w80 {
  width: 2rem;
  margin-bottom: .25rem;
}

.contentSearch .searchbutton {
  width: 100%;
  display: flex;
  flex-wrap: nowrap;
  justify-content: space-around;
}

.contentSearch .searchbutton button {
  width: 49%;
}

.contentSearch button {
  width: 100%;
}

.quantity>>>.el-input-group__append {
  padding: 0 10px;
}

.date-form #myLine {
  margin-bottom: 20px;
}

.w-250 {
  width: 250px;
}

.w-250>>>.el-range-separator {
  width: 10%;
}

.adddbtn .el-button+.el-button,
.adddbtn .el-checkbox.is-bordered+.el-checkbox.is-bordered {
  margin-left: 0;
}

@media only screen and (max-width: 1024px) {
  .demo-form-inline .el-form-item {
    width: 100%;
  }
}</style>
