<template>
  <div class="main_right_height">
    <TopDes :flag="false" topDesFont="设备管理"></TopDes>
    <div>
      <el-row style="margin-top: 15px">
        <el-col :span="1">&nbsp;</el-col>
        <el-col :span="10" style="text-align: left">
          <el-button size="small" class="xl_down_button" @click="addEquipment()">
            新增设备</el-button
          >
          <el-button size="small" class="xl_down_button" @click="updateJizhan()">
            修改蓝牙基站MAC</el-button
          >
        </el-col>
        <el-col :span="11" style="text-align: left"> </el-col>
        <el-col :span="1">&nbsp;</el-col>
      </el-row>
    </div>
    <div style="margin-top: 16px">
      <el-row>
        <el-col :span="1"> &nbsp;</el-col>
        <el-col :span="10">
          <el-table
            :data="tableData"
            style="width: 100%"
            @selection-change="handleSelectionChange"
            :header-cell-style="{
              background: '#66B497',
              color: '#FFFFFF',
              'letter-spacing': '4px',
            }"
            :row-class-name="tableRowClassName"
          >
            <!-- <el-table-column type="selection" align="center" width="55">
            </el-table-column> -->
            <el-table-column prop="ID" align="center" label="id"> </el-table-column>
            <el-table-column prop="Type" :formatter="typeFor" align="center" label="类型">
            </el-table-column>
            <el-table-column prop="AliasName" align="center" label="名称">
            </el-table-column>
            <el-table-column prop="Mac" align="center" label="MAC"> </el-table-column>

            <el-table-column label="操作" align="center" width="100px">
              <template slot-scope="scope">
                <!-- <el-button
                  class="xl_d_button"
                  size="mini"
                  @click="singleDownload(scope.$index, scope.row)"
                  >扫描设备</el-button
                > -->
                <el-popconfirm
                  confirmButtonText="确定"
                  cancelButtonText="取消"
                  @confirm="removeFun(scope.$index, scope.row)"
                  icon="el-icon-info"
                  iconColor="red"
                  title="确定要删除该设备吗？"
                >
                  <el-button class="xl_d_button" size="mini" slot="reference"
                    >删除</el-button
                  >
                </el-popconfirm>
                <!-- <el-button
                  class="xl_d_button"
                  size="mini"
                  @click="removeFun(scope.$index, scope.row)"
                  >移除</el-button
                > -->
              </template>
            </el-table-column>
          </el-table>
        </el-col>
        <el-col :span="2">&nbsp;</el-col>
        <el-col :span="10">
          <el-table
            :data="mergeData"
            style="width: 100%"
            @selection-change="handleSelectionChange"
            :header-cell-style="{
              background: '#66B497',
              color: '#FFFFFF',
              'letter-spacing': '4px',
            }"
            :row-class-name="tableRowClassName"
          >
            <el-table-column
              prop="rssi"
              align="center"
              label="信号强度"
              :formatter="rssiFor"
            >
            </el-table-column>
            <el-table-column prop="aliasName" align="center" label="名称">
            </el-table-column>
            <el-table-column
              prop="deviceType"
              align="center"
              label="类型"
              :formatter="typeFormatter"
            >
            </el-table-column>
            <el-table-column prop="mac" align="center" label="MAC"> </el-table-column>
            <el-table-column label="操作" align="center" width="140px">
              <template slot-scope="scope" style='width:120px'>
                <div style='display:flex;flex-direction:column;justify-items: center;align-items:center'>
                  <el-button
                    :disabled="buttonLinkFlag"
                    class="xl_d_button"
                    style='width:auto'
                    size="mini"
                    slot="reference"
                    @click="linkJudge(scope.$index, scope.row, scope.row.connect)"
                  >
                    <span v-if="scope.row.connect">断开连接</span
                    ><span v-if="!scope.row.connect">连接</span>
                    <!-- <span >断开连接</span
                    > -->
                  </el-button>
                  <!-- v-show="scope.row.addFlag" -->
                  <el-button
                    style="margin-top: 10px;width:100px;margin-right:2px"
                    v-show="scope.row.addFlag"
                    
                    :disabled="buttonLinkFlag"
                    class="xl_d_button"
                    size="mini"
                    slot="reference"
                    @click="addFast(scope.row)"
                  >
                    <span>添加至列表</span>
                  </el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
        <el-col :span="1"> &nbsp;</el-col>
      </el-row>
    </div>
    <!-- <p align="center" style="margin-bottom: 40px">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageNum"
        :page-size="pageSize"
        :page-sizes="[10, , 50, 100, 200, 300, 400]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totolSize"
      >
      </el-pagination>
    </p> -->
    <el-dialog :visible.sync="centerDialogVisible" width="545px" center class="dig_equi">
      <div slot="title" class="title_di" style="width: 545px">
        <img width="545px" src="../assets/manage/bg_di.png" />
        <img
          class="equipment_bg"
          width="85px"
          height="85px"
          src="../assets/manage/bg_title.png"
        />
      </div>
      <span class="min_equi">
        <div class="equipment_class">
          <div style="margin-left: 40px; width: 120px">选择设备：&nbsp;&nbsp;</div>
          <el-select
            v-model="type"
            style="width: 100%; margin-right: 40px"
            placeholder="请选择设备"
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </div>
        <div class="equipment_class">
          <div style="margin-left: 40px; width: 150px">设备MAC：&nbsp;&nbsp;</div>
          <el-input
            style="width: 100%; margin-right: 40px"
            v-model="mac"
            placeholder="例如DC:0D:30:03:39:05"
          ></el-input>
        </div>
      </span>
      <span slot="footer" class="dialog-footer">
        <button class="cancle_add" @click="centerDialogVisible = false">取消</button>
        <button class="com_add" @click="addFun()">确定</button>
      </span>
    </el-dialog>

    <el-dialog :visible.sync="centerDialogVisible" width="545px" center class="dig_equi">
      <div slot="title" class="title_di" style="width: 545px">
        <img width="545px" src="../assets/manage/bg_di.png" />
        <div class="equipment_title">新增设备</div>
        <img
          class="equipment_bg"
          width="85px"
          height="85px"
          src="../assets/manage/bg_title.png"
        />
      </div>
      <span class="min_equi">
        <div class="equipment_class">
          <div style="margin-left: 40px; width: 120px">选择设备：&nbsp;&nbsp;</div>
          <el-select
            v-model="type"
            style="width: 100%; margin-right: 40px"
            placeholder="请选择设备"
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </div>
        <div class="equipment_class">
          <div style="margin-left: 40px; width: 125px">设备MAC：&nbsp;&nbsp;</div>
          <el-input
            style="width: 100%; margin-right: 40px"
            v-model="mac"
            placeholder="例如DC:0D:30:03:39:05"
          ></el-input>
        </div>
        <div class="equipment_class">
          <div style="margin-left: 40px; width: 120px">设备名称：&nbsp;&nbsp;</div>
          <el-input
            style="width: 100%; margin-right: 40px"
            v-model="aliasName"
            placeholder=""
          ></el-input>
        </div>
      </span>
      <span slot="footer" class="dialog-footer">
        <button class="cancle_add" @click="centerDialogVisible = false">取消</button>
        <button class="com_add" @click="addFun()">确定</button>
      </span>
    </el-dialog>

    <el-dialog :visible.sync="visibleFast" width="545px" center class="dig_equi">
      <div slot="title" class="title_di" style="width: 545px">
        <img width="545px" src="../assets/manage/bg_di.png" />
        <div class="equipment_title">设置设备名称</div>
        <img
          class="equipment_bg"
          width="85px"
          height="85px"
          src="../assets/manage/bg_title.png"
        />
      </div>
      <span class="min_equi">
        <div class="equipment_class">
          <div style="margin-left: 40px; width: 120px">设备名称：&nbsp;&nbsp;</div>
          <el-input
            style="width: 100%; margin-right: 40px"
            v-model="aliasNameFast"
            placeholder=""
          ></el-input>
        </div>
      </span>
      <span slot="footer" class="dialog-footer">
        <button class="cancle_add" @click="visibleFast = false">取消</button>
        <button class="com_add" @click="addFastFun()">确定</button>
      </span>
    </el-dialog>

    <!-- 修改mac -->
    <el-dialog :visible.sync="baseStationFlag" width="545px" center class="dig_equi">
      <div slot="title" class="title_di" style="width: 545px">
        <img width="545px" src="../assets/manage/bg_di.png" />
        <div class="equipment_title">填写蓝牙基站</div>
        <img
          class="equipment_bg"
          width="85px"
          height="85px"
          src="../assets/manage/bg_title.png"
        />
      </div>
      <p class="eweima">
        提示：蓝牙基站MAC填写，可以选择蓝牙基站上附带的二维码图片，也可以手动书写
      </p>
      <button class="sweep">
        <input
          type="file"
          ref="fileId"
          class="fileIdClass"
          @change="upload($event)"
        />从本地选择二维码
      </button>
      <span class="min_equi">
        <div class="equipment_class">
          <div style="margin-left: 40px; width: 220px">填写蓝牙基站MAC：&nbsp;&nbsp;</div>
          <el-input v-model="baseStationDes"></el-input>

          <!-- <el-select
            clearable
            v-model="baseStationDes"
            style="width: 100%; margin-right: 40px"
            placeholder="请选择蓝牙基站mac"
            filterable 
            allow-create 
            default-first-option 
          >
            <el-option
              v-for="item in baseStationOptions"
              :key="item.mac"
              :label="item.mac"
              :value="item.mac"
            >
            </el-option>
          </el-select> -->
        </div>
      </span>
      <span slot="footer" class="dialog-footer">
        <button class="cancle_add" @click="baseStationFlag = false">取消</button>
        <button class="com_add" @click="saveBaseSation">确定</button>
      </span>
    </el-dialog>

    <!-- 关闭弹框 -->
    <el-dialog :visible.sync="comFlag" width="545px" center class="dig_equi">
      <div slot="title" class="title_di" style="width: 545px">
        <img width="545px" src="../assets/manage/bg_di.png" />
        <div class="equipment_title">提示</div>
        <img
          class="equipment_bg"
          width="85px"
          height="85px"
          src="../assets/manage/bg_title.png"
        />
      </div>
      <span class="min_equi">
        <div class="equipment_class">
          <div style="margin-left: 40px; width: 240px">
            提示：关闭软件后生效,确认关闭吗？
          </div>
        </div>
      </span>
      <span slot="footer" class="dialog-footer">
        <button class="cancle_add" @click="comFlag = false">取消</button>
        <button class="com_add" @click="visiblePopFun">确定</button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import axios from "axios";
import jsFileDownload from "js-file-download";
import jsQR from "jsqr";
import Jimp from "jimp";
let ipcRenderer = require("electron").ipcRenderer;
export default {
  data() {
    return {
      lanMac: "",
      comFlag: false,
      visiblePop: false,
      centerDialogVisible: false,
      //蓝牙基站所选参数
      baseStationDes: "",
      baseStationOptions: [],

      options: [
        {
          value: "0",
          label: "脑电",
        },
        {
          value: "1",
          label: "心电",
        },
      ],
      //手动添加
      mac: "",
      aliasName: "",
      type: "1",

      //快速添加
      macFast: "",
      aliasNameFast: "",
      typeFast: "1",
      visibleFast: false,

      head_style: "#f5f7fa",
      value1: "",
      startDate: "",
      endDate: "",
      identifier: "",
      pageNum: 1,
      pageSize: 10,
      totolSize: 10,
      nameSearch: "",
      tableData: [],
      scanData: [],
      multipleSelection: [],
      flag: "",
      disableFlag: true,
      websock: null,
      linkIndex: null,

      isSelectedList: [],
      connectedData: [],
      mergeTimeFlag: null,
      listTimeFlag: null,
      mergeData: [],
      listTmp: [],
      userLink: {
        num: "",
        mac: "",
        ecgAllList: [], //心电数据部分
        ecgSectionList: [], //心电数据全部
        //开始脑电各个部分的数据
      },
      buttonLinkFlag: false,
      disabledTimeFlag: null,
      //蓝牙基站的flag
      baseStationFlag: false,
      isAnimation: false,
      timer: null,
    };
  },
  created() {
    this.initWebsocket();
  },
  mounted() {
    let that = this;
    this.disconnectDevice();
    this.flag = this.$route.query.flag;
    this.queryScan();
    this.queryEle();
    //根据扫描列表和已连接列表看看哪些是重复的//重复的就是已连接的
    that.mergeTimeFlag = setInterval(that.mergeDataFun, 1000);
    that.listTimeFlag = setInterval(that.connectList, 6000);
  },
  beforeDestroy() {
    clearTimeout(this.mergeTimeFlag);
    clearInterval(this.listTimeFlag);
    clearInterval(this.disabledTimeFlag);
    this.websock.close(1000);
    this.closeScan();
    this.disconnectDevice();
  },
  destroyed() {
    //离开之后断开websocket连接
  },
  methods: {
    cance() {
      this.isAnimation = false;
      cancelAnimationFrame(this.timer);
    },
    upload(e) {
      this.cance();
      const file = e.target.files[0];
      const createObjectURL =
        window.createObjectURL ||
        window.URL.createObjectURL ||
        window.webkitURL.createObjectUR;
      this.baseStationDes = "";
      // this.imgurl = createObjectURL(file);

      const fReader = new FileReader();
      // fReader.readAsDataURL(file); // Base64 8Bit字节码
      // fReader.readAsBinaryString(file);  // Binary 原始二进制
      fReader.readAsArrayBuffer(file); // ArrayBuffer 文件流
      fReader.onload = (e) => {
        console.log(e);
        // this.imgurl2 = e.target.result;
        e.target.result &&
          Jimp.read(e.target.result)
            .then(async (res) => {
              this.$refs.fileId.value = "";
              const { data, width, height } = res.bitmap;
              try {
                const resolve = await jsQR(data, width, height);
                this.baseStationDes = resolve.data;
              } catch (err) {
                this.$message.info("识别失败，请检查二维码是否正确");
                // this.result = "识别失败，请检查二维码是否正确！";
              } finally {
                // console.info("读取到的文件：", res);
              }
            })
            .catch((err) => {
              this.$refs.fileId.value = "";
              this.$message.info("读取文件错误");
              // console.error("文件读取错误：", err);
            });
      };
    },
    visiblePopFun() {
      this.baseStationFlag = false;
      this.visiblePop = false;
      this.comFlag = false;
      //调用关闭软件的方法
      ipcRenderer.send("window-close");
    },
    //保存蓝牙基站mac
    saveBaseSation() {
      //判断选择框是否选了mac了
      if (this.baseStationDes == "") {
        this.visiblePop = false;
        this.$message.info("尚未填写蓝牙基站MAC");
        return;
      }

      let path = `v2/gateway/set`;
      this.$http.postTmp(path, { mac: this.baseStationDes }, (res) => {
        if (res.data.code == 200) {
          this.baseStationFlag = false;
          this.comFlag = true;
          //修改成功后提示需要重启软件
          //修改成功后关掉
          // this.$message.success("添加成功");
          // this.queryEle();
        } else {
          this.$message.error(res.data.message);
        }
      });
    },
    //更新蓝牙基站mac
    updateJizhan() {
      let that = this;
      that.baseStationDes = "";
      //清空选项
      this.baseStationFlag = true;
      //调用蓝牙基站mac
      //查询接口得到返回的mac数据
      that.$http.getTmp(`v2/gateway/find`, {}, (res) => {
        if (res.code == 200) {
          that.baseStationOptions = res.data;
          // if(res.data,length>0){
          //   for(let i =0;i<res.data.length;i++){
          //     let a = res.data[i]
          //   }
          // }
        } else {
          // this.$message.error(res.message);
        }
      });
    },

    addFast(val) {
      this.macFast = val.mac;
      this.typeFast = val.type;
      this.aliasNameFast = "";
      this.visibleFast = true;
      //然选择设备的弹出框弹出来
      //弹出框弹出来
      // macFast: "",
      // aliasNameFast: "",
      // typeFast: "1",
    },
    //新增设备
    addFastFun() {
      //判断设备名称是不是空
      if (this.aliasNameFast == "") {
        this.$message.info("设备名称不能为空");
        return;
      }
      this.visibleFast = false;
      let path = "v1/device/add";
      let data = {
        type: this.typeFast,
        mac: this.macFast,
        aliasName: this.aliasNameFast,
      };
      this.$http.postTmp(path, data, (res) => {
        if (res.data.code == 200) {
          this.$message.success("添加成功");
          this.queryEle();
        } else {
          this.$message.error(res.data.message);
        }
      });
    },
    //状态切换
    linkJudge(index, val, flag) {
      if (flag) {
        //buttonLinkFlag

        this.disconnectEquipment(val);
      } else {
        this.linkFun(index, val);
      }
    },
    //断开所有设备的操作
    disconnectDevice() {
      let that = this;
      that.$http.getTmp(`v2/device/dis/connAll`, {}, (res) => {
        if (res.data.code == 200) {
        } else {
          // this.$message.error(res.message);
        }
      });
    },
    //断开连接的脑电
    disconnectEquipment(val) {
      let that = this;
      that.buttonLinkFlag = true;
      that.$http.postTmp(`v2/device/dis/conn`, { mac: val.mac }, (res) => {
        that.disableStatus();
        if (res.data.code == 200) {
        } else {
          this.$message.error(res.message);
        }
      });
    },
    typeFormatter(val) {
      if (val.type == "1") {
        return "心电";
      } else {
        return "脑电";
      }
    },
    rssiFor(val) {
      if (val.rssi == 0) {
        return "";
      } else {
        return val.rssi;
      }
    },
    nameFormatter(val) {
      if (val.Name == "BW-ECG-01") {
        return "心电";
      } else {
        return "脑电";
      }
    },
    disableStatus() {
      let that = this;
      this.disabledTimeFlag = setTimeout(() => {
        this.buttonLinkFlag = false;
      }, 8000);
    },
    linkFun(index, val) {
      let that = this;
      that.buttonLinkFlag = true;
      that.$http.postTmp(
        `/v2/device/conn`,
        {
          ai: val.ai + "",
          mac: val.mac,
          at: val.at + "",
        },
        (res) => {
          that.disableStatus();
          if (res.data.code == 200) {
            // that.linkStatus = false;
            // this.linkIndex = index;
            //如果是脑电的话直接调用打开数据接口
            //如果是心电需要先调用写入输入数据-发送指令接口
            if (val.type == "0") {
            }
            // this.$message.success("设备连接成功");
          } else {
            // this.$message.error("访问服务器失败！");
            this.$message.error(res.data.message);
          }
        }
      );
    },
    //写入数据--发送指令
    writeData(mac) {
      let that = this;
      let userName = sessionStorage.getItem("name");
      that.$http.postTmp(
        `/v2/device/write/data`,
        { mac: mac, userName: userName },
        (res) => {
          // that.openData();
          if (res.data.code == 200) {
          } else {
            this.$message.error("访问服务器失败！");
          }
        }
      );
    },
    openData() {
      let that = this;
      that.$http.getTmp(`/v1/device/open/notify`, {}, (res) => {
        if (res.code == 200) {
          // that.tableData = res.data;
          // that.totolSize = res.data.totalElements;
        } else {
          this.$message.error("访问服务器失败！");
        }
      });
    },
    initWebsocket() {
      const wsuri = "ws://127.0.0.1:8000/ws?uid=client&to_uid=server";
      // const wsuri = "ws://192.168.1.103:8000/ws?uid=client&to_uid=server";
      this.websock = new WebSocket(wsuri);
      this.websock.onmessage = this.websocketonmessage;
      this.websock.onopen = this.websocketonopen;
      this.websock.onerror = this.websocketonerror;
      this.websock.onclose = this.websocketclose;
    },
    //查询连接列表
    connectList() {
      let that = this;
      that.$http.getTmp(`v2/device/connected/list`, {}, (res) => {
        //判断当前的列表是否存在该用户已点击的列表
      });
    },
    websocketonopen() {
      //连接建立之后执行send方法发送数据
      let actions = { test: "12345" };
      this.websocketsend(JSON.stringify(actions));
    },
    websocketonerror() {
      //连接建立失败重连
      // this.initWebSocket();
    },
    websocketonmessage(e) {
      let that = this;
      //数据接收
      const redata = JSON.parse(e.data);
      // console.log(redata);
      // if(redata.content == "设备连接成功"){
      //   console.log(redata);
      // }
      // if(redata.content == "设备连接失败"){
      //   console.log(redata);
      // }
      if (
        redata.content != "开启扫描成功" &&
        redata.content != "设置过滤成功" &&
        redata.content != "Successful connection to socket service" &&
        redata.content != "关闭扫描成功" &&
        redata.content != "设置UUID成功" &&
        redata.content !== "成功"
      ) {
        if (redata.content == "设置UUID失败") {
          that.$message.error("蓝牙基站设置uuid失败,请联系管理员");
        }
        //首先判断是否redata.content是否是未定义
        if (redata.hasOwnProperty("content")) {
          if (redata.content != "") {
            let dataLin = JSON.parse(redata.content);

            if (redata.msgType == "device") {
              // let dataLin = JSON.parse(redata.content);
              
              let a = {
                mac: dataLin.m,
                name: dataLin.n,
                rssi: dataLin.rssi,
                aliasName: dataLin.aliasName,
                ai: dataLin.ai,
                at: dataLin.at,
                type: dataLin.t, //当type为1时为心电
              };
              that.changeList(a);
              //获取到很多数据，取每秒最大的包含量
            } else if (redata.msgType == "connectedList") {
              //数组储存每次返回的已选列表
              //将每次的数据进行储存，然后经过去重及为已选列表的数据
              console.log(dataLin);
              let obj = {
                mac: dataLin.m,
                name: dataLin.n,
                rssi: dataLin.rssi,
                aliasName: dataLin.aliasName,
                connect: true,
                ai: dataLin.ai,
                at: dataLin.at,
                type: dataLin.t, //当type为1时为心
              };
              that.isSelectedList.push(obj);
              // console.log(obj)
              //创建一个变量，将变量赋值根据mac进行去重
              let list = JSON.parse(JSON.stringify(that.isSelectedList));
              //然后将list进行去重

              //然后将该结果去重
              let listBarring = [];
              for (let i = 0; i < list.length; i++) {
                let flag = false;
                for (let j = 0; j < listBarring.length; j++) {
                  if (list[i].mac == listBarring[j].mac) {
                    flag = true;
                  }
                }
                if (!flag) {
                  listBarring.push(list[i]);
                }
              }
              that.isSelectedList = JSON.parse(JSON.stringify(listBarring));
              console.log(that.isSelectedList);
              that.connectedData = JSON.parse(JSON.stringify(listBarring));

              //   that.userLink.mac
              //当已连接设备列表包含当前mac是则为连接状态
              // that.linkStatus = true;
              //listBarring  将值赋值给已选列表的值
              //判断当前是脑电吗
            } else if (redata.msgType == "disConnect") {
              console.log("------------------------------------");
              console.log(dataLin);
              let mac = dataLin.m;
              let list = JSON.parse(JSON.stringify(that.connectedData));
              let list1 = [];
              for (let i = 0; i < list.length; i++) {
                if (list[i].mac != mac) {
                  list1.push(list[i]);
                }
              }
              that.connectedData = JSON.parse(JSON.stringify(list1));
              let listLin = JSON.parse(JSON.stringify(that.isSelectedList));
              let listLin1 = [];
              for (let i = 0; i < listLin.length; i++) {
                if (listLin[i].mac != mac) {
                  listLin1.push(list[i]);
                }
              }
              that.isSelectedList = JSON.parse(JSON.stringify(listLin1));
            }
          }
        }
      }
    },
    websocketsend(Data) {
      //数据发送
      this.websock.send(Data);
    },
    websocketclose(e) {
      // console.log("断开连接", e);
      if (e.code == 1005) {
        this.initWebsocket();
      } else {
        console.log("断开连接", e);
      }
      //关闭
    },
    changeList(obj) {
      // console.log(obj);
      let that = this;
      that.listTmp.push(obj);
      //让两个变量不是指向一个地址
      let arrayStr = JSON.stringify(that.listTmp);
      let array = JSON.parse(arrayStr);

      var newArr = new Array();
      var flag = false;
      for (var i = 0; i < array.length; i++) {
        for (var j = 0; j < newArr.length; j++) {
          if (array[i].mac == newArr[j].mac) {
            newArr[j] = array[i];
            flag = true;
            break;
          }
        }
        if (!flag) {
          newArr.push(array[i]);
        }
      }
      that.listTmp = JSON.parse(JSON.stringify(newArr));
      // console.log(JSON.stringify(newArr));
      //listTmp即使最大扫描列表
      that.scanData = newArr;
    },
    scanEquipment() {
      this.queryScan();
    },
    removeFun(val, row) {
      let path = `v1/device/${row.Mac}/remove`;
      this.$http.deleteTmp(path, {}, (res) => {
        if (res.data.code == 200) {
          this.$message(res.data.message);
          this.queryEle();
        }
      });
    },
    typeFor(val) {
      if (val.Type == "0") {
        return "脑电";
      } else if (val.Type == "1") {
        return "心电";
      }
    },
    addFun() {
      let path = "v1/device/add";
      let data = {
        type: this.type,
        mac: this.mac,
        aliasName: this.aliasName,
      };
      if (this.mac == "") {
        this.$message.info("设备MAC不能为空");
        return;
      }
      if (this.aliasName == "") {
        this.$message.info("设备名称不能为空");
        return;
      }
      this.$http.postTmp(path, data, (res) => {
        if (res.data.code == 200) {
          this.centerDialogVisible = false;
          this.queryEle();
        } else {
          this.$message.error(res.data.message);
        }
      });
    },
    addEquipment() {
      this.centerDialogVisible = true;
      this.mac = "";
      this.aliasName = "";
    },
    dateForMa(row) {
      let date = new Date(row.createTime);
      let formattedDate = `${date.getFullYear()}-${("0" + (date.getMonth() + 1)).slice(
        -2
      )}-${("0" + date.getDate()).slice(-2)} ${("0" + date.getHours()).slice(-2)}:${(
        "0" + date.getMinutes()
      ).slice(-2)}:${("0" + date.getSeconds()).slice(-2)}`;
      return formattedDate;
    },
    //返回上一页
    goBack() {
      this.$router.go(-1);
    },
    //批量下载
    download(val, value) {
      //获取数组集合
      let idArr = [];
      for (let i = 0; i < this.multipleSelection.length; i++) {
        idArr.push(this.multipleSelection[i].id);
      }
      this.batchDownloadOriginal(val, value, idArr);
    },
    //全部下载(原始数据)
    batchDownloadOriginalAll() {
      let that = this;
      let arr = [];
      //原始数据批量下载路径
      let path = `chat/chatRecord/AllDownload?identifier=${that.nameSearch}&beginDate=${that.startDate}&endDate=${that.endDate}`;
      // let path = `record/download`;
      let baseUrl = sessionStorage.getItem("baseUrl");
      //window.location.href = `${baseUrl}${path}?ids=${arr}`;
      let a = arr.join();
      axios({
        method: "get",
        url: `${baseUrl}${path}`,
        timeout: 600000, // 请求超时时间，数据量多后台响应慢的情况可以调大点，没生效的话可能是vue.config.js里的配置影响了
        responseType: "blob", // 返回类型为数据流
        data: {
          // ids: arr,
          // flag: that.flag,
          // startDate: that.startDate,
          // endDate: that.endDate,
          // userName: that.nameSearch,
        }, // 需要传参的话，在这传
      }).then((res) => {
        if (res && res.data) {
          // console.log(decodeURIComponent(res.headers["filename"]))
          // 调用js-file-download下载文件，第一个参数是数据流，第二个参数是文件名，我这后端返回时把文件名放到响应的header的filename字段中，所以用这种方式取出
          jsFileDownload(res.data, decodeURIComponent(res.headers["filename"]));
        }
      });
    },
    //批量下载(原始数据)
    batchDownloadOriginal(val, value, idArr) {
      let that = this;
      let arr = [];
      //原始数据批量下载路径
      let path = `v1/record/download/source`;
      if (val === 2) {
        path = `chat/chatRecord/batchDownload`;
      }
      if ((val === 1 && value === 1) || (val === 2 && value === 1)) {
        arr = idArr;
      } else {
        arr = [];
      }
      // let path = `record/download`;
      let baseUrl = sessionStorage.getItem("baseUrl");
      //window.location.href = `${baseUrl}${path}?ids=${arr}`;
      let a = arr.join();
      axios({
        method: "get",
        url: `${baseUrl}${path}?ids=${a}`,
        timeout: 600000, // 请求超时时间，数据量多后台响应慢的情况可以调大点，没生效的话可能是vue.config.js里的配置影响了
        responseType: "blob", // 返回类型为数据流
        data: {
          ids: arr,
          flag: that.flag,
          startDate: that.startDate,
          endDate: that.endDate,
          userName: that.nameSearch,
        }, // 需要传参的话，在这传
      }).then((res) => {
        if (res && res.data) {
          // console.log(decodeURIComponent(res.headers["filename"]))
          // 调用js-file-download下载文件，第一个参数是数据流，第二个参数是文件名，我这后端返回时把文件名放到响应的header的filename字段中，所以用这种方式取出
          jsFileDownload(res.data, decodeURIComponent(res.headers["filename"]));
        }
      });
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    timeChange(val) {
      if (val === null) {
        this.startDate = "";
        this.endDate = "";
      } else {
        this.startDate = this.fomatterDate(this.value1[0]);
        this.endDate = this.fomatterDate(this.value1[1]);
      }
      this.pageNum = 1;
      this.queryEle();
    },
    //格式化时间格式
    fomatterDate(val) {
      var date = new Date(val);
      let year = date.getFullYear();
      let month = this.fomatterM(date.getMonth() + 1);
      let currentDay = this.fomatterM(date.getDate());
      return year + "-" + month + "-" + currentDay;
    },
    fomatterM(val) {
      if (val < 10) {
        return "0" + val;
      } else {
        return val + "";
      }
    },
    searchEle() {
      this.pageNum = 1;
      this.queryEle();
    },
    //扫描设备
    //合并数据
    mergeDataFun() {
      let that = this;

      //先选出扫描列表
      //list为扫描列表
      let scanDataTmp = JSON.stringify(this.scanData);
      console.log(JSON.stringify('----'))
      console.log(JSON.stringify(this.scanData))
      let scanDataTmpFin = JSON.parse(scanDataTmp);

      let list = [];
      for (let i = 0; i < scanDataTmpFin.length; i++) {
        let obj = {
          rssi: "",
          aliasName: "",
          name: "",
          mac: "",
          connect: false,
          type: "",
          ai: "",
          at: "",
        };
        obj.rssi = scanDataTmpFin[i].rssi;
        obj.aliasName = scanDataTmpFin[i].aliasName;
        obj.name = scanDataTmpFin[i].name;
        obj.mac = scanDataTmpFin[i].mac;
        obj.connect = false;
        obj.type = scanDataTmpFin[i].type;
        obj.ai = scanDataTmpFin[i].ai;
        obj.at = scanDataTmpFin[i].at;
        list.push(obj);
      }
      //判断某个
      //先取出与扫描列表显示不一样的

      //循环list
      //与已选列表进行对比，如果已选列表中有重复

      //已选列表必定显示
      //如果已选列表为空

      //已连接列表中应该全部显示+扫描列表与已选列表不重复的mac的则为全部的

      //先将扫描列表与已选列表全部格式化合并为一个数组
      //先查已选列表中在扫描列表中没有的----

      //然后最后将其加入扫描列表
      //然后查询已选列表中在扫描列表中有的

      //已选列表
      let connectedDataTmp = JSON.stringify(this.connectedData);
      let connectedDataTmpFin = JSON.parse(connectedDataTmp);

      //知道了已选列表
      //在已选列表中找到与扫描列表不同的对象
      //不包含的列表
      //以下listBarring是已选列表中且与扫描列表不同的
      let listBarring = [];
      for (let i = 0; i < connectedDataTmpFin.length; i++) {
        let flag = false;
        for (let j = 0; j < list.length; j++) {
          if (connectedDataTmpFin[i].mac == list[j].mac) {
            flag = true;
          }
        }
        if (!flag) {
          listBarring.push(connectedDataTmpFin[i]);
        }
      }

      //在找出扫描列表与已选列表相同的，将已选列表的数据同步给扫描列表

      for (let i = 0; i < list.length; i++) {
        for (let j = 0; j < connectedDataTmpFin.length; j++) {
          if (list[i].mac == connectedDataTmpFin[j].mac) {
            list[i].connect = true;
            list[i].rssi = connectedDataTmpFin[j].rssi;
            list[i].aliasName = connectedDataTmpFin[j].aliasName;
          }
        }
      }
      //然后合并两个数组

      let listFin = list.concat(listBarring);
      //判断当前选择的是脑电还是心电
      let currentDeviceList = [];

      for (let i = 0; i < listFin.length; i++) {
        currentDeviceList.push(listFin[i]);
      }

      for (let k = 0; k < currentDeviceList.length; k++) {
        if (that.userLink.mac !== "" && that.userLink.mac == currentDeviceList[k].mac) {
          currentDeviceList[k].userNum = that.userLink.num;
        }
      }
      //将数组其他选项

      //将此数组与设备列表数组进行比较
      let finalData = [];
      finalData = JSON.parse(JSON.stringify(currentDeviceList));

      for (let p = 0; p < finalData.length; p++) {
        finalData[p].addFlag = true;
      }

      for (let p = 0; p < finalData.length; p++) {
        for (let m = 0; m < this.tableData.length; m++) {
          if (finalData[p].mac == this.tableData[m].Mac) {
            finalData[p].addFlag = false;
          }
        }
      }
      // console.log(finalData);
      this.mergeData = finalData;
    },
    changeList(obj) {
      console.log('<<<<<<<<')
      console.log(obj);
      let that = this;
      that.listTmp.push(obj);
      //让两个变量不是指向一个地址
      let arrayStr = JSON.stringify(that.listTmp);
      let array = JSON.parse(arrayStr);

      var newArr = new Array();
      var flag = false;
      for (var i = 0; i < array.length; i++) {
        for (var j = 0; j < newArr.length; j++) {
          if (array[i].mac == newArr[j].mac) {
            newArr[j] = array[i];
            flag = true;
            break;
          }
        }
        if (!flag) {
          newArr.push(array[i]);
        }
      }
      that.listTmp = JSON.parse(JSON.stringify(newArr));
      // console.log(JSON.stringify(newArr));
      //listTmp即使最大扫描列表
      that.scanData = newArr;
    },
    queryEle() {
      let that = this;
      that.$http.getTmp(`/v1/device/list?type=`, {}, (res) => {
        if (res.code == 200) {
          that.tableData = res.data;
          // that.totolSize = res.data.totalElements;
        } else {
          this.$message.error("访问服务器失败！");
        }
      });
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.queryEle();
    },
    handleCurrentChange(val) {
      this.pageNum = val;
      this.queryEle();
      // this.pageNum = val;
      // this.queryList();
    },
    //开启扫描扫描
    queryScan() {
      let that = this;
      that.$http.getTmp(`/v2/device/scan`, {}, (res) => {});
    },

    //关闭扫描
    closeScan() {
      this.tableVisible = false;
      let that = this;
      that.$http.getTmp(`/v2/device/stop/scan`, {}, (res) => {});
    },
    singleDownload(index, row) {
      let baseUrl = sessionStorage.getItem("baseUrl");
      let path = `/chat/chatRecord/download?id=${row.id}`;
      // let arr = [row.id];
      axios({
        method: "get",
        url: `${baseUrl}${path}`,
        timeout: 600000, // 请求超时时间，数据量多后台响应慢的情况可以调大点，没生效的话可能是vue.config.js里的配置影响了
        responseType: "blob", // 返回类型为数据流
        data: {
          // ids: arr,
        }, // 需要传参的话，在这传
      }).then((res) => {
        if (res && res.data) {
          console.log(res.headers["filename"]);
          // console.log(decodeURIComponent(res.headers["filename"]))
          // 调用js-file-download下载文件，第一个参数是数据流，第二个参数是文件名，我这后端返回时把文件名放到响应的header的filename字段中，所以用这种方式取出
          jsFileDownload(res.data, decodeURIComponent(res.headers["filename"]));
        }
      });
    },
    getAnswerQuestionPaymentSuccess(id) {
      sessionStorage.setItem("back_page", "3");
      let _this = this;

      _this.$http.post(`v1/record/find/${id}`, {}, (res) => {
        if (res.data.code == 200 && res.data.data) {
          _this.resultJsonParams = res.data.data;
          // let sleep = JSON.parse(
          //   _this.resultJsonParams.userRecordEntity.testResult
          // );
          // sleep = sleep[0].newTableContext.result[0].improvementSuggestions;
          // if (_this.scale_flag === "20210910163158") {
          //   _this.askEnd(sleep);
          //   this.inputFlag = 0;
          // }
          // if (_this.scale_flag === "20220805135201") {
          //   _this.askEnd(sleep);
          //   this.inputFlag = 0;
          // }

          // let testResult = JSON.parse(res.data.userRecordEntity.testResult)[0]
          //   .version;
          let testResult = JSON.parse(res.data.data.userRecordEntity.testResult)[0]
            .version;

          if (testResult == 2) {
            _this.$router.push({
              name: "scaleResultSCl",
              params: { tableData: _this.resultJsonParams },
            });
          } else {
            _this.$router.push({
              name: "scaleResult",
              params: { tableData: _this.resultJsonParams },
            });
          }
        }
      });
      // _this.$http.get(`/getRecordById?id=${id}`, {}, (res) => {
      //   if (res.code == 200) {
      //     _this.resultJsonParams = res.data;
      //     let testResult = JSON.parse(res.data?.userRecordEntity?.testResult)[0]
      //       .version;

      //     if (testResult == 2) {
      //       _this.$router.push({
      //         name: "scaleResultSCl",
      //         query: _this.resultJsonParams,
      //       });
      //     } else {
      //       _this.$router.push({
      //         name: "ScaleResult",
      //         query: JSON.stringify(_this.resultJsonParams),
      //       });
      //     }
      //   }

      //   console.log("请求数据的list", res);
      // });
    },
    handleDelete(index, row) {},
    tableRowClassName({ rowIndex }) {
      if (rowIndex % 2 === 0) {
        return "warning-row";
      } else if (rowIndex % 2 === 1) {
        return "success-row";
      }
      return "success-row";
    },
  },
};
</script>
<style scoped>
.main_right_height {
  height: 100vh !important;
  display: block !important;
  overflow-y: auto !important;
  background: #ffffff;
}

.el-input-group {
  line-height: normal;
  display: inline-table;
  width: 200px !important;
  border-collapse: separate;
  border-spacing: 0;
}

.equipment_class {
  width: 100%;
  margin-top: 30px;
  display: flex;
  flex-direction: row;
  justify-items: center;
  align-items: center;
}

.dig_equi >>> .el-dialog__header {
  padding: 0 !important;
}

.dig_equi >>> .el-dialog {
  border-top-left-radius: 12px;
  border-top-right-radius: 12px;
}

.dig_equi >>> .el-dialog__headerbtn .el-dialog__close {
  color: #ffffff;
}

.title_di {
  width: 545px;
  background-color: transparent;
}

.min_equi {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.cancle_add {
  cursor: pointer;
  width: 87px;
  height: 45px;
  background: #ffffff;
  border-radius: 4px;
  border: 1px solid #e5e5e5;
  margin-right: 40px;
  font-family: Alibaba PuHuiTi 2;
  font-weight: normal;
  font-size: 20px;
  color: #666666;
}

.com_add {
  cursor: pointer;
  width: 87px;
  height: 45px;
  background-color: #5e8af7;
  border-radius: 4px;
  border: 1px solid #e5e5e5;
  color: #ffffff;
  font-family: Alibaba PuHuiTi 2;
  font-weight: normal;
  font-size: 20px;
}
.equipment_bg {
  position: absolute;
  left: 10px;
  top: -10px;
}
.equipment_title {
  position: absolute;
  left: 0;
  right: 0;
  top: 14px;
  font-size: 24px;
  color: #ffffff;
}
.fileIdClass {
  cursor: pointer;
}
</style>
<style lang="less">
.sweep {
  cursor: pointer;
  position: relative;
  padding: 12px;
  width: 100%;
  font-size: 18px;
  cursor: pointer;
  color: white;
  background: #42b983;
  border: 1px solid #42b983;
  overflow: hidden;
  input {
    position: absolute;
    /* font-size: 50px; */
    margin-left: -180px;
    line-height: 50px;
    margin-top: -15px;
    width: 100%;
    opacity: 0;
  }
}
.eweima {
  font-size: 12px;
  color: #b2afaa;
  margin-bottom: 20px;
}
</style>
