<!--异常设备-->
<template>
  <div class="app-container abnormal">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="硬件类型" prop="type">
        <el-select v-model="queryParams.equipmentType" placeholder="请选择硬件类型" clearable size="small">
          <el-option
            v-for="dict in cateClassOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="学院" prop="type">
        <el-select v-model="queryParams.deptId" placeholder="请选择学院" @change="handleNodeClick">
          <el-option
            v-for="dict in deptOptions"
            :key="dict.deptId"
            :label="dict.deptName"
            :value="dict.deptId"
          ></el-option>
        </el-select>
      </el-form-item>
      <!--<el-form-item label="学院" prop="type">-->
        <!--<el-select v-model="queryParams.type" placeholder="请选择学院" clearable size="small">-->
          <!--<el-option label="请选择字典生成" value="" />-->
        <!--</el-select>-->
      <!--</el-form-item>-->
      <!--<el-form-item label="开始时间" prop="inTime" style="margin-left:10px;">-->
        <!--<el-date-picker clearable size="small"-->
                        <!--v-model="queryParams.beginTime"-->
                        <!--type="date"-->
                        <!--value-format="yyyy-MM-dd"-->
                        <!--placeholder="请选择开始时间">-->
        <!--</el-date-picker>-->
      <!--</el-form-item>-->
      <!--<el-form-item label="结束时间" prop="inTime" style="margin-left:10px;">-->
        <!--<el-date-picker clearable size="small"-->
                        <!--v-model="queryParams.endTime"-->
                        <!--type="date"-->
                        <!--value-format="yyyy-MM-dd"-->
                        <!--placeholder="请选择结束时间">-->
        <!--</el-date-picker>-->
      <!--</el-form-item>-->
      <el-form-item>
        <p class="inquire-button-one" @click="handleQuery">查询</p>
        <p class="reset-button-one" @click="resetQuery">重置</p>
      </el-form-item>
      <el-form-item style="float: right;">
        <el-dropdown @command="exportButton">
          <div class="form-dropdown-box">
            <img src="@/assets/ZDimages/personnelManagement/icon_jzgxx_sc.png">
            <p>导出</p>
            <img src="@/assets/ZDimages/personnelManagement/icon_jzggl_xljt.png">
          </div>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item style="border-bottom:1px solid #E0E0E0;margin:0 10px;color:#333;" :command="{command:1}">导出全部数据</el-dropdown-item>
            <el-dropdown-item style="margin:0 10px;color:#666;" :command="{command:2}">导出选中数据</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </el-form-item>
    </el-form>
    <!--<div class="sheet-expand-box" v-hasPermi="['laboratory:abnormal:export']">-->
      <!--<i class="el-icon-warning" style="color:#0045AF;"></i>-->
      <!--<p class="color_99">已选择 {{selectedNum}} 项</p>-->
      <!--<p class="color_one cursor_hover" @click="selectPage">全选本页</p>-->
      <!--<p class="color_warn cursor_hover" @click="clearSelection">清除选项</p>-->
      <!--<p class="color_one border-solid-color-one cursor_hover" @click="getSelected" v-hasPermi="['laboratory:record:export']">立即导出</p>-->
      <!--<p class="color_one border-solid-color-one cursor_hover" @click="handleExport" v-hasPermi="['laboratory:record:export']">导出全部</p>-->
    <!--</div>-->

    <el-table v-loading="loading" border :data="abnormalList" @selection-change="handleSelectionChange" ref="multipleTable" :row-key="getRowKeys">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="名称" align="left" prop="name" />
      <el-table-column label="类型" align="left" prop="type" >
        <template slot-scope="scope">
          <p v-for="(item,index) in cateClassOptions" :key="index" v-if="scope.row.equipmentType==item.dictValue">
          {{item.dictLabel +"-"}}{{scope.row.hardwareTypeName }}
          </p >
        </template>
      </el-table-column>
      <!--<el-table-column label="类型" align="left" prop="type" />-->
      <el-table-column label="学院" align="left" prop="deptName" />
      <el-table-column label="实验室" align="left" prop="subjectName" show-overflow-tooltip/>
      <el-table-column label="异常原因" align="left" prop="abnormalReason" show-overflow-tooltip/>
      <el-table-column label="最近异常时间" align="left" prop="lastAbnormalTime" />
      <el-table-column label="状态" align="left" prop="hardwareOperateName" width="100">
        <template slot-scope="scope"><span>{{scope.row.hardwareOperateName}}</span></template>
      </el-table-column>
      <el-table-column label="操作" align="left" class-name="small-padding fixed-width" width="160" v-if="tableButtonType">
        <template slot-scope="scope">
          <div class="table-button-box">
            <p class="table-button-null"></p>
            <p class="table-button-p"
               style="margin-right:10px;"
               @click="openOn(scope.row)"
               v-hasPermi="['laboratory:abnormal:query']"
            >查看</p>
            <p class="table-button-p"
               @click="handleDelete(scope.row)"
               v-hasPermi="['laboratory:abnormal:remove']"
            >删除</p>
            <p class="table-button-null"></p>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!--<pagination :page-sizes="[20, 30, 40, 50]"-->
      <!--v-show="total>0"-->
      <!--:total="total"-->
      <!--layout="total, prev, pager, next, sizes, jumper"-->
      <!--:page.sync="queryParams.pageNum"-->
      <!--:limit.sync="queryParams.pageSize"-->
      <!--@pagination="getList"-->
    <!--/>-->

    <div style="display: flex;height:32px;margin-top:15px;">
      <!--<p style="flex:4;"></p>-->
      <p style="text-align: left;margin:0;line-height:32px;margin-right:20px;font-size:14px;color:#999;">
        <i class="el-icon-warning" style="color:#0183FA;"></i>
        已选择 {{selectedNum}} 项
      </p>
      <div style="flex:5;">
        <pagination :page-sizes="[20, 30, 40, 50]"
          v-show="total>0"
          :total="total"
          style="margin:0;"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </div>
    </div>
    <!-- 添加或修改异常设备对话框 -->
    <el-dialog title="异常设备记录" :visible.sync="open" width="1000px" append-to-body
               :close-on-click-modal="false">
      <div class="abnormal-dialog">
        <p>出现异常次数: <span>{{this.abnormalCount}}</span></p>
        <p>最近异常时间: <span>{{this.lastAbnormalTime}}</span></p>
        <p>初次异常时间: <span>{{this.startAbnormalTime}}</span></p>
      </div>
      <div class="scrollbar-box" style="width:960px;height:500px;overflow-y: scroll;">
        <el-table v-loading="loading" border :data="dialogAbnormalList" @selection-change="dialogHandleSelectionChange">
          <el-table-column label="异常时间" align="left" prop="createTime" />
          <el-table-column label="异常原因" align="left" prop="abnormalReason" />
        </el-table>
      </div>
      <pagination :page-sizes="[20, 30, 40, 50]"
        v-show="dialogTotal>0"
        :total="dialogTotal"
        layout="total, prev, pager, next, sizes, jumper"
        :page.sync="dialogQueryParams.pageNum"
        :limit.sync="dialogQueryParams.pageSize"
        @pagination="dialogGetList"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { Message } from 'element-ui'
import { listAbnormal, getAbnormal, delAbnormal, addAbnormal, updateAbnormal,getEquipmentList,delEquipment,getAbnormalCount } from "@/api/laboratory/abnormal";
import { listDepartments } from "@/api/system/dept";
import { treeselect } from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "Abnormal",
  props:{
    abnormalCount: {},
    lastAbnormalTime: {},
    startAbnormalTime: {}
  },
  components: { Treeselect },
  data() {
    return {
      tableButtonType:this.hasPermiDom(['laboratory:abnormal:query','laboratory:abnormal:remove']),
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 异常设备表格数据
      abnormalList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      cateClassOptions: "",
      // 部门树选项
      deptOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize:20,
        name: null,
        type: null,
        abnormalReason: null,
        hardwareId: null,
        sensorId: null,
        deptId: null,
        deptName: null,
        userId: null,
        beginTime: null,
        endTime: null,
        equipmentType: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      //表格扩展选择器---需要在@selection-change绑定的方法内监控selection数组长度
      selectedNum:0,
      //弹窗相关
      dialogAbnormalList:[],
      dialogTotal:0,
      dialogQueryParams:{
        pageNum: 1,
        pageSize:20,
      },
      params:{
        pageNum: 1,
        pageSize:20,
      }
    };
  },
  created() {
    this.getList();
    this.getDeptList();
    this.getDicts("equipment_category").then(response => {
      this.cateClassOptions = response.data;
      console.log(this.cateClassOptions)
    })
  },
  methods: {
    /** 导出按钮操作 */
    exportButton(item) {
      let self = this;
      this.currentDate=this.getCurrentTime()

      if(item.command == 1){
        self.$confirm(`确认导出全部数据?`, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(async () => {
          self.download('/laboratory/abnormal/export/', {...self.queryParams}, '异常设备-'+this.currentDate+'.xlsx')
          self.msgSuccess('操作成功')
        }).catch(() => {})
      }else if(item.command == 2){
        if(self.ids.length>0) {
          self.$confirm(`确认导出选中数据?`, "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }).then(async () => {
            let ids = self.ids.join(',');
            let obj = {
              abnormalIds :ids
            }
            self.download(`/laboratory/abnormal/export/`,obj, '异常设备-'+this.currentDate+'.xlsx')
            self.msgSuccess('操作成功')
          }).catch(() => {})
        }else {
          Message({
            message: "请选择要导出的数据",
            type: 'error'
          });
        }
      }
    },
    /** 当前时间 */
    getCurrentTime () {
      const yy = new Date().getFullYear()
      const mm = new Date().getMonth() + 1
      const dd = new Date().getDate()
      const hh = new Date().getHours()
      const mf = new Date().getMinutes() < 10 ? '0' + new Date().getMinutes() : new Date().getMinutes()
      const ss = new Date().getSeconds() < 10 ? '0' + new Date().getSeconds() : new Date().getSeconds()
      return yy + '-' + mm + '-' + dd
    },
    //选中导出
    getSelected(){
      if(!this.ids[0]){
        Message({
          message: "请选择要导出的数据",
          type: 'error'
        });
        return
      }
      let obj = JSON.parse(JSON.stringify(this.queryParams))
      obj.abnormalIds = this.ids;
      this.download('laboratory/abnormal/export', {
        ...obj
      }, `异常设备.xlsx`)
    },
    /* 全部导出按钮操作 */
    handleExport() {
      let obj = JSON.parse(JSON.stringify(this.queryParams))
      obj.accessIds = "";
      obj.abnormalIds = [];
      this.download('laboratory/abnormal/export', {
        ...obj
      }, `异常设备.xlsx`)
    },
    //查看按钮
    openOn(row){
      // this.queryParams.id = row.id || this.ids
      // this.queryParams.equipmentType = row.equipmentType
      // listAbnormal(this.queryParams).then(response => {
      //   this.dialogAbnormalList = response.rows;
      //   this.dialogTotal = response.total;
      // });
      const ids = row.id || this.ids
      this.dialogQueryParams.pageNum = 1;
      this.dialogQueryParams.pageSize = 20;
      this.dialogQueryParams.id = ids;
      this.dialogQueryParams.equipmentType = row.equipmentType
      listAbnormal(this.dialogQueryParams).then(response => {
        this.dialogAbnormalList = response.rows;
        this.dialogTotal = response.total;
      });
      getAbnormalCount(this.dialogQueryParams).then(response => {
        this.abnormalCount = response.data.abnormalCount;
        this.lastAbnormalTime = response.data.lastAbnormalTime;
        this.startAbnormalTime = response.data.startAbnormalTime;
      });
      console.log(row);
      this.open = true;
    },
    // 弹窗列表接口
    dialogGetList(){
      listAbnormal(this.dialogQueryParams).then(response => {
        this.dialogAbnormalList = response.rows;
        this.dialogTotal = response.total;
      });
    },
    //弹窗多选框选中数据
    dialogHandleSelectionChange(selection) {
      this.selectedNum = selection.length;
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    //=========表格扩展选择器方法---开始=========
    //选择本页
    selectPage(){
      console.log(this.$refs.multipleTable)
      this.$refs.multipleTable.toggleAllSelection()
      // console.log(this.$refs.multipleTable.selection)
    },
    //清除选择
    clearSelection(){
      this.$refs.multipleTable.clearSelection()
    },
    /*===记录勾选数据===
      需要再el-table 添加  :row-key="getRowKeys"
      需要在selection 添加 :reserve-selection="true"
    */
    getRowKeys(row) {
      return row.id
    },
    //=========表格扩展选择器方法---结束=========
    /** 查询设备列表 */
    getList() {
      this.loading = true;
      getEquipmentList(this.queryParams).then(response => {
        this.abnormalList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询学院列表 */
    getDeptList() {
      listDepartments().then(response => {
        this.$set(this, 'deptOptions', response.data)
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.deptId = data;
      // this.getList();
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        type: null,
        abnormalReason: null,
        hardwareId: null,
        sensorId: null,
        deptId: null,
        deptName: null,
        createTime: null,
        userId: null,
        createBy: null,
        updateTime: null,
        updateBy: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {};
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.selectedNum = selection.length;
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加异常设备";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getAbnormal(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改异常设备";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateAbnormal(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addAbnormal(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$confirm('是否确认删除设备？')
        .then(_ => {
          const ids = row.id || this.ids;
          let params = {}
          params.id = ids
          params.equipmentType = row.equipmentType
          delEquipment(params).then(response => {
            this.getList();
            this.msgSuccess("删除成功");
          });
        })
        .catch(_ => {});

      // this.$confirm('是否确认删除异常设备?', "警告", {
      //     confirmButtonText: "确定",
      //     cancelButtonText: "取消",
      //     type: "warning"
      //   }).then(function() {
      //     return delAbnormal(ids);
      //   }).then(() => {
      //     this.getList();
      //     this.msgSuccess("删除成功");
      //   }).catch(() => {});
    }
    // /** 导出按钮操作 */
    // handleExport() {
    //   this.download('laboratory/abnormal/export', {
    //     ...this.queryParams
    //   }, `laboratory_abnormal.xlsx`)
    // }
  }
};
</script>
<style scoped lang="scss">
  .abnormal{
    display: flex!important;
    flex-direction: column;
    box-shadow: 0 0 8px 2px rgba(0, 0, 0, 0.1);
    padding:20px!important;

    .form-dropdown-box{
      display: flex;
      margin:0;
      padding:0 10px;
      cursor: pointer;
      height:40px;
      img:nth-child(1){
        width:16px;
        height:16px;
        margin-top:12px;
      }
      p{
        width:47px;
        text-align: center;
        font-size:14px;
        margin:0;
        line-height:40px;
      }
      img:nth-child(3){
        width:10px;
        height:6px;
        margin-top:17px;
      }
    }
    .button-box{
      width:400px;
      display: flex;
    }
    .form-box{
      display:flex;
      .null-p{
        flex:1;
      }
    }
    .sheet-expand-box{
      height:40px;
      display:flex;
      background:rgba(1,131,250,0.1);
      border-radius: 5px;
      margin-bottom:18px;
      font-size:14px;
      i{
        margin:10px 16px 0 14px;
        height:20px;
        width:20px;
        font-size:20px;
        display: block;
      }
      p{
        margin:0;
      }
      p:nth-child(2){
        width:132px;
        font-size:14px;
        height:40px;
        line-height:40px;
      }
      p:nth-child(3){
        width:60px;
        font-size:14px;
        height:40px;
        line-height:40px;
        margin-right:20px;
      }
      p:nth-child(4){
        width:60px;
        font-size:14px;
        height:40px;
        line-height:40px;
        margin-right:20px;
      }
      p:nth-child(5){
        font-size:14px;
        line-height:30px;
        width: 100px;
        height: 30px;
        border-radius: 6px;
        text-align: center;
        margin-top:5px;
        margin-right:20px;
      }
      p:nth-child(6){
        font-size:14px;
        line-height:30px;
        width: 100px;
        height: 30px;
        border-radius: 6px;
        text-align: center;
        margin-top:5px;
      }
    }
    .tableTypeColorA{
      color:#0BB627;
    }
    .tableTypeColorB{
      color:#F9800A;

    }
  }
</style>
