<template>
  <div ref="main" class="page-content">
    <back-box>
      <template slot="title">
        <span>设备管理</span>
      </template>
      <template slot="btns">
        <template v-if="tableData.length">
          <el-tooltip effect="dark" content="设备导出" placement="bottom">
            <el-button
              type="primary"
              icon="fa fa-cloud-download"
              size="mini"
              plain
              circle
              @click="downExl"
            ></el-button>
          </el-tooltip>
        </template>
        <template v-if="role == 'ROLE_XUEXIAO' && type == 1">
          <el-tooltip effect="dark" content="设备导入" placement="bottom">
            <el-button
              type="primary"
              icon="el-icon-upload2"
              size="mini"
              plain
              circle
              @click="diaUp = true"
            ></el-button>
          </el-tooltip>
          <el-tooltip effect="dark" content="添加基站" placement="bottom">
            <el-button
              type="primary"
              icon="el-icon-receiving"
              size="mini"
              plain
              circle
              @click="addDev"
            ></el-button> </el-tooltip
        ></template>
      </template>
    </back-box>
    <div>
      <div class="tab-box">
        <el-radio-group v-model="type">
          <el-radio-button :label="1">基站管理</el-radio-button>
          <el-radio-button :label="2">答题器管理</el-radio-button>
          <el-radio-button :label="3">授课端管理</el-radio-button>
        </el-radio-group>
      </div>
      <p
        v-show="(type == 1 && stationCount) || (type == 2 && clickerCount)"
        class="error-tips"
      >
        有{{
          type == 1 ? stationCount : clickerCount
        }}条设备异常信息，<router-link
          :to="{ path: '/deviceError', query: { type: type } }"
          >点击查看&gt;&gt;</router-link
        >
      </p>
      <div class="content">
        <div v-show="type == 1">
          <div class="chart-box" v-if="count">
            <div class="device-num">
              <p class="p1">{{ count }}</p>
              <p class="p2">基站数量</p>
            </div>
            <div class="chart">
              <pie-chart
                id="pieChart"
                :params="chartData"
                @clickPieChart="clickPieChart"
              ></pie-chart>
            </div>
          </div>
          <div class="table-box">
            <div class="answer-header">
              <div class="sel-box">
                <el-cascader
                  size="small"
                  class="sel sel2"
                  clearable
                  placeholder="选择班级"
                  v-model="query.classId"
                  :options="gradeList"
                  :props="props"
                  collapse-tags
                  :show-all-levels="false"
                ></el-cascader>
                <el-select
                  class="sel"
                  v-model="query.onlineStatus"
                  placeholder="选择状态"
                  @change="_QueryData(true)"
                >
                  <el-option
                    v-for="item in statusList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
                <el-input
                  placeholder="请输入设备编码"
                  v-model="query.sn"
                  class="input-with-select"
                  clearable
                  @keyup.enter.native="_QueryData(true)"
                >
                  <el-button
                    slot="append"
                    icon="el-icon-search"
                    @click="_QueryData(true)"
                  ></el-button>
                </el-input>
                <el-button class="serach-box" round @click="_QueryData(true)"
                  >筛选</el-button
                >
              </div>
            </div>
            <p class="loading" v-if="!tableData.length && loading">
              加载中<i class="el-icon-loading"></i>
            </p>
            <el-table v-else :data="tableData" border style="width: 100%">
              <el-table-column
                prop="sn"
                label="设备编码"
                align="center"
              ></el-table-column>
              <el-table-column
                prop="frequency"
                label="频点"
                align="center"
                width="60"
              ></el-table-column>
              <el-table-column
                prop="pairingCode"
                label="配对码"
                align="center"
              ></el-table-column>
              <el-table-column
                v-if="role == 'ROLE_JITUAN'"
                prop="schoolName"
                label="学校"
                align="center"
              ></el-table-column>
              <el-table-column prop="gradeName" label="年级" align="center"
                ><template slot-scope="scoped">
                  <p v-for="(item, index) in scoped.row.classList" :key="index">
                    {{ item.gradeName }}
                  </p>
                </template></el-table-column
              >
              <el-table-column
                prop="roomName"
                label="所在教室"
                align="center"
              ></el-table-column>
              <el-table-column label="关联班级" align="center">
                <template slot-scope="scoped">
                  <p v-for="(item, index) in scoped.row.classList" :key="index">
                    {{ item.className }}
                  </p>
                </template>
              </el-table-column>
              <el-table-column
                prop="otaVersionName"
                label="固件版本号"
                align="center"
              ></el-table-column>
              <el-table-column
                prop="onlineTime"
                label="最近上报"
                align="center"
                width="160"
              ></el-table-column>
              <el-table-column
                prop="createdTime"
                label="创建时间"
                align="center"
                width="160"
              ></el-table-column>
              <el-table-column label="状态" align="center" width="60"
                ><template slot-scope="scope">
                  {{
                    scope.row.onlineStatus == 1
                      ? "在线"
                      : scope.row.onlineStatus == 2
                      ? "异常"
                      : "离线"
                  }}
                </template></el-table-column
              >
              <el-table-column label="操作" align="center" width="130"
                ><template slot-scope="scoped">
                  <el-tooltip
                    effect="dark"
                    v-if="role != 'ROLE_JITUAN'"
                    content="修改基站"
                    placement="top"
                  >
                    <el-button
                      type="primary"
                      circle
                      size="mini"
                      icon="fa fa-edit"
                      @click="edit(scoped.row)"
                    ></el-button>
                  </el-tooltip>
                  <el-tooltip effect="dark" content="日志" placement="top">
                    <el-button
                      type="warning"
                      circle
                      size="mini"
                      icon="fa fa-eye"
                      @click="linkTo(scoped.row, 1)"
                    ></el-button>
                  </el-tooltip>
                  <el-popconfirm
                    title="确定删除吗？"
                    @confirm="_delStation($event, scoped.row)"
                  >
                    <el-button
                      class="del"
                      slot="reference"
                      type="danger"
                      circle
                      size="mini"
                      icon="fa fa-trash-o"
                    ></el-button>
                  </el-popconfirm> </template
              ></el-table-column>
            </el-table>
          </div>
        </div>
        <div v-show="type == 2">
          <div class="chart-box" v-if="count">
            <div class="device-num">
              <p class="p1">{{ count }}</p>
              <p class="p2">答题器数量</p>
            </div>
            <div class="chart">
              <scatter-chart
                id="scatterChart"
                :params="chartData2"
                @clickScatterChart="clickScatterChart"
              ></scatter-chart>
            </div>
          </div>
          <div class="table-box">
            <div class="answer-header">
              <div class="sel-box">
                <el-cascader
                  size="small"
                  class="sel sel2"
                  clearable
                  placeholder="选择班级"
                  v-model="query.classId"
                  :options="gradeList"
                  :props="props"
                  collapse-tags
                  :show-all-levels="false"
                ></el-cascader>
                <el-select
                  class="sel"
                  v-model="query.type"
                  placeholder="选择状态"
                  @change="_QueryData(true)"
                >
                  <el-option
                    v-for="item in typeList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
                <el-input
                  placeholder="请输入设备编码"
                  v-model="query.sn"
                  class="input-with-select"
                  clearable
                  @input.native="query.studentName = ''"
                  @keyup.enter.native="_QueryData(true)"
                >
                  <el-button
                    slot="append"
                    icon="el-icon-search"
                    @click="_QueryData(true)"
                  ></el-button>
                </el-input>
                <el-input
                  placeholder="学生姓名"
                  v-model="query.studentName"
                  class="input-with-select"
                  clearable
                  @input.native="query.sn = ''"
                  @keyup.enter.native="_QueryData(true)"
                >
                  <el-button
                    slot="append"
                    icon="el-icon-search"
                    @click="_QueryData(true)"
                  ></el-button>
                </el-input>
                <el-button class="serach-box" round @click="_QueryData(true)"
                  >筛选</el-button
                >
              </div>
            </div>
            <p class="loading" v-if="!tableData.length && loading">
              加载中<i class="el-icon-loading"></i>
            </p>
            <el-table v-else :data="tableData" border style="width: 100%">
              <el-table-column
                prop="sn"
                label="设备编码"
                align="center"
              ></el-table-column>
              <el-table-column label="学生信息" align="center"
                ><template slot-scope="scoped">
                  <p
                    v-for="(item, index) in scoped.row.studentList"
                    :key="index"
                  >
                    {{ item.studentName }}
                  </p>
                </template></el-table-column
              >
              <el-table-column
                v-if="role == 'ROLE_JITUAN'"
                prop="schoolName"
                label="学校"
                align="center"
              ></el-table-column>
              <el-table-column
                v-if="role == 'ROLE_JITUAN'"
                prop="gradeName"
                label="年级"
                align="center"
                width="120"
                ><template slot-scope="scoped">
                  <p v-for="(item, index) in scoped.row.classList" :key="index">
                    {{ item.gradeName }}
                  </p>
                </template></el-table-column
              >
              <el-table-column
                prop="class"
                label="关联班级"
                align="center"
                width="160"
              >
                <template slot-scope="scoped">
                  <p v-for="(item, index) in scoped.row.classList" :key="index">
                    {{ item.className }}
                  </p>
                </template></el-table-column
              >
              <el-table-column
                prop="pairingCode"
                label="配对码"
                align="center"
              ></el-table-column>
              <el-table-column
                prop="answerTimes"
                label="答题次数"
                align="center"
              ></el-table-column>
              <el-table-column
                prop="latestReportTime"
                label="最后答题时间"
                align="center"
                width="160"
              ></el-table-column>
              <el-table-column label="操作" align="center" width="80"
                ><template slot-scope="scoped">
                  <el-tooltip effect="dark" content="日志" placement="top">
                    <el-button
                      type="warning"
                      circle
                      size="mini"
                      icon="fa fa-eye"
                      @click="linkTo(scoped.row, 2)"
                    ></el-button>
                  </el-tooltip> </template
              ></el-table-column>
            </el-table>
          </div>
        </div>
        <div v-show="type == 3">
          <div class="table-box">
            <div class="answer-header">
              <div class="sel-box">
                <el-cascader
                  size="small"
                  class="sel sel2"
                  clearable
                  placeholder="选择班级"
                  v-model="query.classId"
                  :options="gradeList"
                  :props="props"
                  collapse-tags
                  :show-all-levels="false"
                  @change="_QueryData(false)"
                ></el-cascader>
                <span class="sel"
                  >共选择{{ selectionTabIds.length }}个授课端</span
                >
                <el-button plan round @click="autoUpDate(false)"
                  >开启自动更新</el-button
                >
                <el-button plan round @click="stopUpdate(false)"
                  >停止自动更新</el-button
                >
              </div>
              <p class="upgrade-all" v-if="this.role == 'ROLE_XUEXIAO'">
                <span>全校更新：</span>
                <el-switch v-model="upgradeFlag" @change="changeUpdateBySchool">
                </el-switch>
              </p>
            </div>
            <p class="loading" v-if="!tableData.length && loading">
              加载中<i class="el-icon-loading"></i>
            </p>
            <el-table
              v-else
              ref="multipleTable"
              :data="tableData"
              border
              style="width: 100%"
              @selection-change="handleSelectionChange"
            >
              <el-table-column type="selection" width="55"></el-table-column>
              <!-- <el-table-column prop="sn" label="设备编码" align="center"></el-table-column> -->
              <el-table-column
                prop="class"
                label="关联班级"
                align="center"
                width="100"
                ><template slot-scope="scoped">
                  <p v-for="(item, index) in scoped.row.classList" :key="index">
                    {{ item.className }}
                  </p>
                </template></el-table-column
              >
              <el-table-column
                v-if="role == 'ROLE_JITUAN'"
                prop="schoolName"
                label="学校"
                align="center"
              ></el-table-column>
              <el-table-column
                v-if="role == 'ROLE_JITUAN'"
                prop="gradeName"
                label="年级"
                align="center"
                width="80"
                ><template slot-scope="scoped">
                  <p v-for="(item, index) in scoped.row.classList" :key="index">
                    {{ item.gradeName }}
                  </p>
                </template></el-table-column
              >
              <el-table-column
                prop="lastUpdateTime"
                label="最近更新"
                align="center"
              ></el-table-column>
              <el-table-column
                prop="osInfo"
                label="软件系统"
                align="center"
              ></el-table-column>
              <el-table-column
                prop="hardwareInfo"
                label="硬件环境"
                align="center"
              ></el-table-column>
              <el-table-column
                prop="otaVersionName"
                label="版本号"
                align="center"
                width="80"
              ></el-table-column>
              <el-table-column label="状态" align="center" width="80"
                ><template slot-scope="scope">
                  {{
                    scope.row.onlineStatus == 1
                      ? "在线"
                      : scope.row.onlineStatus == 2
                      ? "异常"
                      : "离线"
                  }}
                </template></el-table-column
              >
              <el-table-column label="日志记录" align="center" width="80">
                <template slot-scope="scope">
                  <el-link
                    type="primary"
                    @click="openLogia(scope.row.id)"
                    download
                    >查看</el-link
                  >
                </template>
              </el-table-column>
              <el-table-column label="自动更新" align="center" width="100"
                ><template slot-scope="scoped">
                  <el-switch
                    v-model="scoped.row.upgradeFlag"
                    @change="changeUpdate($event, scoped.row, this)"
                  >
                  </el-switch> </template
              ></el-table-column>
            </el-table>
          </div>
        </div>
        <div class="pagination-box">
          <el-pagination
            small=""
            layout="total,prev, pager, next"
            :hide-on-single-page="true"
            :total="total"
            @current-change="changePage"
            :current-page="page"
            :page-size="size"
          >
          </el-pagination>
        </div>
      </div>
    </div>
    <el-dialog
      :close-on-click-modal="false"
      title="设备导入"
      :visible.sync="diaUp"
      width="400"
    >
      <upload :url="url" @upSuccess="upSuccess" fileName="设备信息">
        <p class="down-txt" slot="down">
          通过Excel名单导入设备，需要提供设备编码，点击
          <el-link type="danger" @click="downExcel">模板下载</el-link> 。
        </p>
      </upload>
      <div class="dialog-footer" slot="footer">
        <el-button @click="diaUp = false">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog
      :close-on-click-modal="false"
      :title="isAdd ? '添加基站' : '修改基站'"
      :visible.sync="diaAnswerEqu"
      width="400"
    >
      <el-form ref="forms" :model="form" :rules="formRules" label-width="140px">
        <el-form-item label="设备编码：" prop="sn">
          <el-col :span="16"
            ><el-input
              type="text"
              placeholder="输入设备编码"
              v-model.trim="form.sn"
              maxlength="30"
              size="45"
              show-word-limit
              :disabled="!isAdd"
            >
            </el-input
          ></el-col>
        </el-form-item>
        <el-form-item label="频点：" prop="frequency">
          <el-col :span="16"
            ><el-input
              type="text"
              placeholder="输入频点"
              v-model.trim="form.frequency"
              maxlength="30"
              size="45"
              show-word-limit
            >
            </el-input
          ></el-col>
        </el-form-item>
        <el-form-item label="配对码：" prop="pairingCode">
          <el-col :span="16"
            ><el-input
              type="text"
              placeholder="输入配对码"
              v-model.trim="form.pairingCode"
              maxlength="30"
              size="45"
              show-word-limit
            >
            </el-input
          ></el-col>
        </el-form-item>
        <el-form-item label="选择班级：" prop="classIds">
          <el-col :span="16">
            <el-cascader
              class="sel"
              clearable
              v-model="form.classIds"
              :options="gradeList"
              :show-all-levels="false"
            ></el-cascader>
          </el-col>
        </el-form-item>
        <el-form-item label="所在教室：">
          <el-col :span="16"
            ><el-input
              type="text"
              placeholder="输入所在教室"
              v-model.trim="form.roomName"
              maxlength="30"
              size="45"
              show-word-limit
            >
            </el-input
          ></el-col>
        </el-form-item>
      </el-form>
      <div class="dialog-footer" slot="footer">
        <el-button type="primary" @click="setAnswerEqu">确 定</el-button>
        <el-button @click="diaAnswerEqu = false">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog
      :close-on-click-modal="false"
      title="设备日志"
      :visible.sync="diaLog"
      width="400"
    >
      <div v-loading="logLoading">
        <p class="down-p" v-for="item in logList">
          {{ item.modifiedTime }} -
          <el-link type="primary" :href="item.content" download>下载</el-link>
        </p>
        <el-empty
          :image-size="100"
          v-if="!logList.length && !logLoading"
          description="暂无数据"
        ></el-empty>
        <div class="pagination-box">
          <el-pagination
            small=""
            layout="total,prev, pager, next"
            :hide-on-single-page="true"
            :total="logTotal"
            @current-change="logChangePage"
            :current-page="logPage"
            :page-size="logSize"
          >
          </el-pagination>
        </div>
      </div>
      <div class="dialog-footer" slot="footer">
        <el-button @click="diaLog = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import pieChart from "@/components/charts/pieChart";
import scatterChart from "@/components/charts/scatterChart";
import _ from "lodash";
import { downloadFile, getBlob, formatGradeNameClass } from "@/utils";
import api from "@/api/apis/apis";
export default {
  components: { pieChart, scatterChart },
  watch: {
    type: function (val) {
      this.page = 1;
      this.total = 0;
      this.count = 0;
      this.query.classId = [];
      this.query.onlineStatus = "";
      this.query.sn = "";
      this.query.studentName = "";
      this.query.type = "";
      if (val == 1) {
        this.stationReport();
      } else if (val == 2) {
        this.keyboardReport();
      }
      this._QueryData();
    },
  },
  data() {
    return {
      code: "",
      role: "",
      loading: false,
      exportLoading: false,
      isAdd: false, //添加还是修改基站
      url: "/api_html/school/manager/importStation",
      diaUp: false,
      diaAnswerEqu: false,
      gradeList: [], //年级列表
      schoolAll: [], //所有学校刘表
      school: {}, //校园账号所属学校信息
      props: {
        multiple: true,
        checkStrictly: true,
      },
      type: 1,
      query: {
        classId: [],
        onlineStatus: "",
        sn: "",
        type: "",
        studentName: "",
      },
      statusList: [
        { label: "全部", value: "" },
        { label: "离线", value: 0 },
        { label: "在线", value: 1 },
        { label: "异常", value: 2 },
      ],
      typeList: [
        { label: "全部", value: 0 },
        { label: "1日内", value: 1 },
        { label: "3日内", value: 2 },
        { label: "7日内", value: 3 },
        { label: "1月内", value: 4 },
        { label: "3月内", value: 5 },
        { label: "3月以上", value: 6 },
      ],
      form: {
        //修改/添加基站信息
        deviceId: "",
        sn: "",
        frequency: "",
        pairingCode: "",
        classIds: [],
        roomName: "",
      },
      formRules: {
        sn: [{ required: true, message: "请输入设备编码", trigger: "blur" }],
        frequency: [{ required: true, message: "请输入频点", trigger: "blur" }],
        pairingCode: [
          { required: true, message: "请输入配对码", trigger: "blur" },
        ],
        // classIds: [{ required: true, message: "请选择班级", trigger: "blur" }],
      },
      tableData: [],
      total: 0,
      count: 0,
      chartData: [],
      chartData2: [],
      selectionTabIds: [], //已选择授课段
      page: 1,
      size: 20,
      isBack: false, //是否是日志页面回来
      upgradeFlag: false,
      stationCount: 0, //异常基站数量
      clickerCount: 0, //异常答题器数量
      // 设备日志相关
      diaLog: false,
      logLoading: false,
      logList: [],
      logTotal: 0,
      logPage: 1,
      logSize: 20,
    };
  },
  created() {
    this.code = this.$store.getters.csCode;
    this.role =
      this.$store.getters.info.showRole ||
      this.$store.getters.info.permissions[0].role;
    this._QueryErrorTotal();
    if (this.role == "ROLE_JITUAN") {
      (this.props.lazy = true),
        (this.props.lazyLoad = function (node, resolve) {
          const { level } = node;
          if (level == 2) {
            api
              .tenantClassList({
                schoolId: node.data.value,
              })
              .then((res) => {
                let children = formatGradeNameClass(res.data?.list).sort(
                  (a, b) => {
                    return a.grade - b.grade;
                  }
                );
                const nodes = [...children];
                // 通过调用resolve将子节点数据返回，通知组件数据加载完成
                resolve(nodes);
              });
          } else {
            resolve(node);
          }
        });
    }
    if (this.role == "ROLE_XUEXIAO") {
      this._QueryDataSchool();
    }
    this._QueryGradeList();
    if (this.role == "ROLE_JITUAN") {
      this.showSchool();
    }
  },
  activated() {
    const that = this;
    this.isBack = this.$route.query.back ? this.$route.query.back : false;
    if (!this.isBack) {
      that.type = 1;
      that.page = 1;
      that.total = 0;
      that.count = 0;
      that.query.classId = [];
      that.query.onlineStatus = "";
      that.query.sn = "";
      that.query.type = "";
      if (this.role == "ROLE_XUEXIAO") {
        this._QueryDataSchool();
      }
      this._QueryGradeList();
      that.stationReport();
      that._QueryData();
    }
  },
  methods: {
    upSuccess(res) {
      //导入成功
      this.$message.closeAll();
      this.$message({
        showClose: true,
        message: `成功（${res.data.success}）`,
        type: "success",
        duration: 5000,
      });
      this.diaUp = false;
      this.page = 1;
      this._QueryData();
    },
    edit(obj) {
      //修改设备
      this.isAdd = false;
      for (let key in this.form) {
        if (key == "classIds") {
          this.form[key] = obj.classList.length
            ? [obj.classList[0].gradeName, obj.classList[0].classId]
            : [];
        } else {
          this.form[key] = obj[key];
        }
      }
      delete this.form.schoolId;
      this.form.deviceId = obj.id;
      this.diaAnswerEqu = true;
    },
    linkTo(obj, type) {
      this.$router.push({
        path: "/deviceLog",
        query: {
          id: obj.id,
          type: type,
        },
      });
    },
    _delStation: _.debounce(async function (event, obj) {
      const { status, info } = await this.$request.deleteStation({
        id: obj.id,
      });
      if (status === 0) {
        this._QueryData(false);
        this.$message.success(info);
      } else {
        this.$message.error(info);
      }
    }, 300),
    clickPieChart(obj) {
      this.query.onlineStatus =
        obj.name == "在线" ? 1 : obj.name == "离线" ? 0 : 2;
      this.query.sn = "";
      this.query.classId = [];
      this.page = 1;
      this._QueryData(false);
    },
    clickScatterChart(obj) {
      this.query.type =
        obj.name == "1日内"
          ? 1
          : obj.name == "3日内"
          ? 2
          : obj.name == "7日内"
          ? 3
          : obj.name == "1月内"
          ? 4
          : obj.name == "3月内"
          ? 5
          : 6;
      this.query.sn = "";
      this.query.classId = [];
      this.page = 1;
      this._QueryData(false);
    },
    handleSelectionChange(val) {
      console.log(val);
      this.selectionTabIds = val.map((item) => {
        return item.id;
      });
    },
    changeUpdateBySchool: _.debounce(function (event) {
      this._ModifyUpgradeFlagBySchool();
    }, 800),
    changeUpdate: _.debounce(function (event, obj) {
      console.log(this);
      if (event) {
        this.autoUpDate(obj.id);
      } else {
        this.stopUpdate(obj.id);
      }
    }, 800),
    changePage(page) {
      this.page = page;
      this._QueryData(false);
    },
    addDev() {
      this.form.sn = "";
      this.form.frequency = "";
      this.form.pairingCode = "";
      this.form.classIds = [];
      this.form.roomName = "";
      this.form.schoolId = this.school.id;
      delete this.form.deviceId;
      this.isAdd = true;
      this.diaAnswerEqu = true;
    },
    _ModifyUpgradeFlagBySchool() {
      let data = this.$request.modifyUpgradeFlagBySchool({
        upgradeFlag: this.upgradeFlag ? 1 : 0,
      });
      if (data && !data.code) {
        this._QueryData(false);
        this.selectionTabIds = [];
        this.$message.success(
          this.upgradeFlag ? "开启自动更新成功" : "关闭/停止自动更新成功"
        );
      } else {
        this.$message.error(data.info);
      }
    },
    async showSchool() {
      const { data, status, info } = await this.$request.schoolList();
      if (status === 0) {
        let gradeListAll = data.list?.map((item) => {
          return {
            value: item.id,
            label: item.schoolName,
          };
        });
        this.schoolAll = [
          {
            value: 0,
            label: "全部",
            children: [...gradeListAll],
          },
        ];
        this.gradeList = [...this.schoolAll, ...this.gradeList];
      } else {
        this.$message.error(info);
      }
    },
    async autoUpDate(id) {
      if (!this.selectionTabIds.length && !id) {
        this.$message.warning("请选择授课端~");
        return;
      }
      if (this.loadingUpDate) return;
      this.loadingUpDate = true;
      let data = await this.$request.modifyUpgradeFlag({
        deviceIds: id ? [id] : this.selectionTabIds,
        upgradeFlag: 1,
      });
      this.loadingUpDate = false;
      if (data && !data.code) {
        this._QueryData(false);
        this.selectionTabIds = [];
        this.$message.success("开启自动更新成功");
      } else {
        this.$message.error(data.info);
      }
    },
    async stopUpdate(id) {
      if (!this.selectionTabIds.length && !id) {
        this.$message.warning("请选择授课端~");
        return;
      }
      if (this.loadingUpDate) return;
      this.loadingUpDate = true;
      let data = await this.$request.modifyUpgradeFlag({
        deviceIds: id ? [id] : this.selectionTabIds,
        upgradeFlag: 0,
      });
      this.loadingUpDate = false;
      if (data && !data.code) {
        this.selectionTabIds = [];
        this._QueryData(false);
        this.$message.success("关闭自动更新成功");
      } else {
        this.$message.error(data.info);
      }
    },
    async downExcel() {
      let data = await this.$request.stationTemplate({
        id: this.id,
      });
      if (data) {
        let blob = new Blob([data], {
          type: "application/vnd.ms-excel;charset=utf-8",
        });
        downloadFile(`基站模版.xlsx`, blob);
      } else {
        this.$message.error("下载失败");
      }
    },
    //报表导出
    async downExl() {
      if (this.exportLoading == true) return;
      let query = this.setQuery();
      const exportDevice =
        this.role != "ROLE_JITUAN"
          ? this.$request.exportDevice
          : this.$request.tenantExportDevice;

      this.exportLoading = true;
      const data = await exportDevice({
        ...query,
        deviceType: this.type,
      });
      this.exportLoading = false;
      if (data && !data.code) {
        let blob = new Blob([data], {
          type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        });
        let txt =
          this.type == 1
            ? "基站管理报表.xlsx"
            : this.type == 2
            ? "答题器报表.xlsx"
            : "授课端报表.xlsx";
        downloadFile(txt, blob);
      } else {
        this.$message.error(data.info);
      }
    },
    //授课端日志列表
    async openLogia(id) {
      this.diaLog = true;
      this.page = 1;
      this.logLoading = true;
      const { data, info, status } = await this.$request.deviceZipLogList({
        id: id,
        page: this.logPage,
        size: this.logSize,
      });
      this.logLoading = false;
      if (status == 0) {
        this.logList = data?.list || [];
      } else {
        this.$message.error(info);
      }
    },
    async downloadLog() {
      if (this.exportLoading == true) return;
      let query = this.setQuery();
      const exportDevice =
        this.role != "ROLE_JITUAN"
          ? this.$request.exportDevice
          : this.$request.tenantExportDevice;

      this.exportLoading = true;
      const data = await exportDevice({
        ...query,
        deviceType: this.type,
      });
      this.exportLoading = false;
      if (data && !data.code) {
        let blob = new Blob([data], {
          type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        });
        let txt =
          this.type == 1
            ? "基站管理报表.xlsx"
            : this.type == 2
            ? "答题器报表.xlsx"
            : "授课端报表.xlsx";
        downloadFile(txt, blob);
      } else {
        this.$message.error(data.info);
      }
    },
    logChangePage(page) {
      this.logPage = page;
      this.downloadLog();
    },

    // 修改基站
    setAnswerEqu() {
      this.$refs.forms.validate(async (valid) => {
        if (valid) {
          if (this.loadingAnswerEqu) return;
          this.loadingAnswerEqu = true;
          let query = { ...this.form };

          query.classIds = query.classIds.length ? [query.classIds[1]] : [];
          let deviceApi = this.isAdd
            ? this.$request.addStation
            : this.$request.updateDevice;
          const { data, status, info } = await deviceApi({
            ...query,
          });
          this.loadingAnswerEqu = false;
          console.log(status);
          if (status === 0) {
            this.diaAnswerEqu = false;
            this.$message.success(info);
            this._QueryData();
            if (this.isAdd) {
              this.stationReport();
            }
          } else {
            this.$message.error(info);
          }
        } else {
          this.$message.warning("数据有误，请检查！");
        }
      });
    },
    async _QueryDataSchool() {
      const { data, status, info } = await this.$request.schoolDetail();
      if (status === 0) {
        this.school = { ...data };
      } else {
        this.$message.error(info);
      }
    },
    // 查找班级
    async _QueryGradeList() {
      this.loading = true;
      const gradeList =
        this.role != "ROLE_JITUAN"
          ? this.$request.gradeList
          : this.$request.regionList;
      const { data, status, info } = await gradeList();
      if (status === 0) {
        if (!!data.list) {
          if (this.role != "ROLE_JITUAN") {
            this.gradeList =
              data.list?.map((item) => {
                let gradeList = {
                  value: item.gradeName,
                  label: item.gradeName,
                };
                gradeList.children =
                  item.classList?.map((items) => {
                    return {
                      value: Number(items.id),
                      label: items.className,
                    };
                  }) || [];
                return gradeList;
              }) || [];
          } else {
            this.gradeList =
              data.list?.map((item) => {
                let gradeList = {
                  value: item.id,
                  label: item.regionName,
                };
                gradeList.children =
                  item.schoolList?.map((items) => {
                    return {
                      value: items.id,
                      label: items.schoolName,
                    };
                  }) || [];
                return gradeList;
              }) || [];
            this.gradeList = [...this.schoolAll, ...this.gradeList];
          }
        }
      } else {
        this.$message.error(info);
      }
    },
    // 基站统计数据
    async stationReport() {
      const stationReport =
        this.role != "ROLE_JITUAN"
          ? this.$request.stationReport
          : this.$request.tenantStationReport;
      const { data, status, info } = await stationReport();
      if (status === 0) {
        this.chartData =
          data.list?.map((item) => {
            return {
              name:
                item.onlineStatus == "1"
                  ? "在线"
                  : item.onlineStatus == 0
                  ? "离线"
                  : "异常",
              value: item.total,
              rate: item.rate,
            };
          }) || [];
        this.count = data.total || 0;
      } else {
        this.$message.error(info);
      }
    },
    // 答题器统计数据
    async keyboardReport() {
      const keyboardReport =
        this.role != "ROLE_JITUAN"
          ? this.$request.keyboardReport
          : this.$request.tenantKeyboardReport;
      const { data, status, info } = await keyboardReport();
      if (status === 0) {
        this.chartData2 =
          data.list?.map((item) => {
            return {
              name:
                item.type == 1
                  ? "1日内"
                  : item.type == 2
                  ? "3日内"
                  : item.type == 3
                  ? "7日内"
                  : item.type == 4
                  ? "1月内"
                  : item.type == 5
                  ? "3月内"
                  : "3月以上",
              count: item.total,
              value: item.rate * 100,
            };
          }) || [];
        this.count = data.total || 0;
      } else {
        this.$message.error(info);
      }
    },
    setQuery() {
      //整理传参
      let query = {};
      if (this.query.sn) {
        this.query.classId = [];
        this.query.onlineStatus = "";
        this.query.type = "";
        this.query.studentName = "";
        query.sn = this.query.sn;
      } else if (this.query.studentName) {
        this.query.classId = [];
        this.query.onlineStatus = "";
        this.query.type = "";
        this.query.sn = "";
        query.studentName = this.query.studentName;
      } else {
        if (this.type == 1) {
          this.query.onlineStatus !== ""
            ? (query.onlineStatus = this.query.onlineStatus)
            : "";
        } else if (this.type == 2) {
          this.query.type !== "" ? (query.type = this.query.type) : "";
        }
        if (this.role == "ROLE_JITUAN") {
          query.regionIds = [];
          query.schoolIds = [];
          query.gradeNames = [];
          query.classIds = [];
          this.query.classId?.map((item) => {
            if (item.length == 1) {
              if (!query.regionIds.includes(item[0])) {
                query.regionIds.push(item[0]);
              }
            } else if (item.length == 2) {
              if (!query.schoolIds.includes(item[1])) {
                query.schoolIds.push(item[1]);
              }
              query.regionIds.includes(item[0])
                ? query.regionIds.remove(item[0])
                : "";
            } else if (item.length == 3) {
              if (!query.schoolIds.includes(item[1])) {
                query.schoolIds.push(item[1]);
              }
              if (!query.gradeNames.includes(item[2])) {
                query.gradeNames.push(item[2]);
              }
              query.regionIds.includes(item[0])
                ? query.regionIds.remove(item[0])
                : "";
            } else if (item.length == 4) {
              if (!query.classIds.includes(item[3])) {
                query.classIds.push(item[3]);
              }
              query.regionIds.includes(item[0])
                ? query.regionIds.remove(item[0])
                : "";
              query.schoolIds.includes(item[1])
                ? query.schoolIds.remove(item[1])
                : "";
              query.gradeNames.includes(item[2])
                ? query.gradeNames.remove(item[2])
                : "";
            }
          });
        } else {
          query.gradeNames = [];
          query.classIds = [];
          this.query.classId?.map((item) => {
            if (item.length == 1) {
              if (!query.gradeNames.includes(item[0])) {
                query.gradeNames.push(item[0]);
              }
            } else {
              if (!query.classIds.includes(item[1])) {
                query.classIds.push(item[1]);
              }
              if (query.gradeNames.includes(item[0])) {
                query.gradeNames.remove(item[0]);
              }
            }
          });
        }
        delete query.classId;
      }
      return query;
    },
    // 设备列表信息
    async _QueryData(isRef) {
      let query = this.setQuery();
      if (isRef) {
        this.page = 1;
      }
      this.loading = true;
      const deviceList =
        this.role != "ROLE_JITUAN"
          ? this.$request.deviceList
          : this.$request.tenantDeviceList;
      this.tableData = [];
      const { data, status, info } = await deviceList({
        ...query,
        deviceType: this.type,
        page: this.page,
        size: this.size,
      });
      this.loading = false;
      if (status == 0) {
        this.tableData =
          (data?.list &&
            data?.list.map((item) => {
              item.upgradeFlag = item.upgradeFlag == 1 ? true : false;
              return item;
            })) ||
          [];

        this.total = data.count;
        this.$nextTick(function () {
          this.$refs.main.scrollTop = 0;
          if (this.query.classId.length) {
            this.selectionTabIds = this.tableData.map((item) => {
              this.$refs.multipleTable.toggleRowSelection(item);
              return item.id;
            });
          }
        });
      } else {
        this.$message.error(info);
      }
    },
    // 异常设备数量
    async _QueryErrorTotal() {
      const abnormalDeviceCount =
        this.role != "ROLE_JITUAN"
          ? this.$request.abnormalDeviceCount
          : this.$request.tenantAbnormalDeviceCount;
      this.tableData = [];
      const { data, status, info } = await abnormalDeviceCount();
      if (status == 0) {
        this.stationCount = data?.stationCount;
        this.clickerCount = data?.clickerCount;
      } else {
        this.$message.error(info);
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.page-content {
  padding: 0 20px;
  height: 100%;
  overflow-y: auto;
}

.tab-box {
  padding: 20px 0 12px;
}

.down {
  padding: 0 0 16px 20px;
}
.down-p{
  line-height:24px;
  display: flex;
}
.error-tips {
  margin-bottom: 12px;
}

.del {
  margin-left: 10px;
}

.content {
  background: #f8f8f8;
  border: 1px solid #e2e2e2;
  border-radius: 10px;
  overflow: hidden;

  :deep(.fa-edit) {
    width: 12px;
    height: 12px;

    &::before {
      margin-left: 2px;
    }
  }

  :deep(.fa) {
    width: 12px;
    height: 12px;

    &::before {
      margin-left: 1px;
    }
  }

  .chart-box {
    display: flex;
    overflow: hidden;
    height: 240px;
    border-bottom: 0.5px solid #e2e2e2;

    .device-num {
      width: 280px;
      border-right: 0.5px solid #e2e2e2;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;

      .p1 {
        font-size: 28px;
      }
    }

    .chart {
      flex: 1;
      height: 100%;
    }
  }

  .table-box {
    padding: 20px 20px 0;

    .loading {
      text-align: center;
      line-height: 36px;
      font-size: 16px;
      color: #666;
    }

    .answer-header {
      padding: 0;
      margin-bottom: 12px;

      .upgrade-all {
        display: flex;
        align-items: center;
      }
    }
  }
}

.answer-header .sel-box .input-with-select {
  margin-right: 20px;

  :deep(.el-input__suffix) {
    right: -5px;
  }

  :deep(.el-button) {
    padding: 12px 16px 12px 10px;
  }
}
</style>