<template>
  <div class="main_right_height">
    <TopDes :flag="false" topDesFont="设备管理"></TopDes>
    <div>
      <!-- <el-row>
        <el-col :span="1">&nbsp;</el-col>
        <el-col :span="20" style="margin-top: 15px">
          <div style="display: flex" class="xl_input">
            <el-date-picker
              v-model="value1"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              @change="timeChange"
            >
            </el-date-picker>
            &nbsp;&nbsp;&nbsp;&nbsp;
            <el-input
              placeholder="请输入用户姓名"
              v-model="nameSearch"
              @input="searchEle"
              prefix-icon="el-icon-search"
            >
            </el-input>
          </div>
        </el-col>
      </el-row> -->
      <el-row style="margin-top: 15px">
        <el-col :span="1">&nbsp;</el-col>
        <el-col :span="22" style="text-align: left">
          <!-- <el-button
            size="small"
            @click="download(1, 1)"
            class="xl_down_button"
            :disabled="multipleSelection.length === 0 && disableFlag"
          >
            批量下载(原始数据)</el-button
          >
          <el-button
            size="small"
            :disabled="tableData.length === 0 && disableFlag"
            @click="download(1, 2)"
            class="xl_down_button"
          >
            全部下载(原始数据)</el-button
          > -->
          <!-- <el-button
            size="small"
            @click="download(2, 1)"
            class="xl_down_button"
            :disabled="multipleSelection.length === 0 && disableFlag"
          >
            批量下载</el-button
          > -->
          <el-button
            size="small"
            class="xl_down_button"
            @click="addEquipment()"
          >
            新增设备</el-button
          >
        </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="22">
          <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="Mac" align="center" label="mac">
            </el-table-column>
            <!-- <el-table-column
              prop="CreatedAt"
              align="center"
              label="创建时间"
              :formatter="dateForMa"
            ></el-table-column> -->
            <!-- <el-table-column prop="profession" label="职业"></el-table-column> -->
            <!-- <el-table-column label="查看测试记录" align="center">
              <template slot-scope="scope">
                <el-button
                  class="xl_d_button"
                  size="mini"
                  @click="removeFun(scope.$index, scope.row)"
                  >移除</el-button
                >
              </template>
            </el-table-column> -->
            <el-table-column label="操作" align="center">
              <template slot-scope="scope">
                <!-- <el-button
                  class="xl_d_button"
                  size="mini"
                  @click="singleDownload(scope.$index, scope.row)"
                  >扫描设备</el-button
                > -->
                <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="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
      title="添加设备"
      :visible.sync="centerDialogVisible"
      width="30%"
      center
    >
      <span>
        <div class="equipment_class">
          <div>选择设备:</div>
          <el-select
            v-model="type"
            style="width: 150px"
            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>设备mac:</div>
          <el-input
            style="width: 150px"
            v-model="mac"
            placeholder="请输入mac"
          ></el-input>
        </div>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="centerDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addFun()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import axios from "axios";
import jsFileDownload from "js-file-download";
export default {
  data() {
    return {
      centerDialogVisible: false,
      options: [
        {
          value: "1",
          label: "脑电",
        },
        {
          value: "2",
          label: "心电",
        },
      ],
      mac: "",
      type: "1",
      head_style: "#f5f7fa",
      value1: "",
      startDate: "",
      endDate: "",
      identifier: "",
      pageNum: 1,
      pageSize: 10,
      totolSize: 10,
      nameSearch: "",
      tableData: [],
      multipleSelection: [],
      flag: "",
      disableFlag: true,
    };
  },
  mounted() {
    this.flag = this.$route.query.flag;
    this.queryEle();
  },
  methods: {
    removeFun(val, row) {
      // debugger;
      let path = `v1/device/${row.Mac}/remove`;

      this.$http.delete(path, {}, (res) => {
        debugger;
        if (res.code == 200) {
          this.$message(res.message);
          this.queryEle();
        }
      });
    },
    typeFor(val) {
      if (val.Type == "1") {
        return "脑电";
      } else if (val.Type == "2") {
        return "心电";
      }
    },
    addFun() {
      let path = "v1/device/add";
      let data = {
        type: this.type,
        mac: this.mac,
      };
      this.$http.post(path, data, (res) => {
        debugger;
        if (res.code == 200) {
          this.centerDialogVisible = false;
          this.queryEle();
        }
      });
    },
    addEquipment() {
      this.centerDialogVisible = true;
    },
    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();
    },
    queryEle() {
      let that = this;
      that.$http.get(`/v1/device/list/1`, {}, (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();
    },
    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 {
  margin-top: 20px;
  display: flex;
  flex-direction: row;
  justify-items: center;
  align-items: center;
}
</style>