<!--传感器管理-->
<template>
  <div class="app-container sensor">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" class="form-box">
      <el-form-item label="学院" prop="deptId">
        <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="subjectId">
        <el-select v-model="queryParams.subjectId" placeholder="请选择实验室">
          <el-option
            v-for="item in subjectOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="senseState">
        <el-select v-model="queryParams.senseState" placeholder="请选择状态" clearable size="small">
          <el-option label="离线" value="OFFLINE" />
          <el-option label="在线" value="TURN_ON" />
          <el-option label="异常" value="ERROR" />
        </el-select>
      </el-form-item>
      <el-form-item style="float: right;">
        <el-col :span="1.5">
          <p class="add-button-one-120"
             @click="handleAdd"
             v-hasPermi="['laboratory:sensor:add']"
          ><i class="el-icon-plus"></i>新增传感器</p>
        </el-col>
      </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>

    <el-table v-loading="loading" border :data="sensorList" @selection-change="handleSelectionChange">
      <el-table-column label="名称" align="left" prop="name" />
      <el-table-column label="网关编号" align="left" prop="gatewayId" />
      <el-table-column label="学院" align="left" prop="deptName" />
      <el-table-column label="实验室" align="left" prop="subjectName" />
      <el-table-column label="路由" align="left" prop="routeNum" />
      <el-table-column label="状态" align="left" prop="senseState">
        <template slot-scope="scope">{{scope.row.senseState==null?'-':scope.row.senseState.name}}</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="button-box">
            <p class="table-min-button"
               @click="handleUpdate(scope.row)"
               style="margin-right:20px;"
               v-hasPermiAnd="['laboratory:sensor:query','laboratory:sensor:edit']"
            >编辑</p>
            <p class="table-min-button"
               @click="handleDelete(scope.row)"
               v-hasPermi="['laboratory:sensor:remove']"
            >删除</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"
    />

    <!-- 添加或修改传感器对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="520px" append-to-body class="sensor-dialog-box">
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="传感器名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入传感器名称" maxlength="20" />
        </el-form-item>
        <el-form-item label="传感器类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择传感器类型">
            <el-option
              v-for="item in sensorAddOptions"
              :key="item.enumName"
              :label="item.name"
              :value="item.enumName">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="网关编号" >
          <el-input v-model="form.gatewayId" maxlength="20" placeholder="请输入网关编号" />
        </el-form-item>
        <el-form-item label="路由" prop="routeNum">
          <el-input-number v-model="form.routeNum" :min="0" :max="99" label="描述文字"></el-input-number>
        </el-form-item>
        <el-form-item label="传感器对应名称" prop="configName">
          <el-input v-model="form.configName" maxlength="20"  placeholder="传感器对应名称"></el-input>
        </el-form-item>
        <el-form-item label="传感器对应状态" prop="configStatus">
          <el-input v-model="form.configStatus" maxlength="20"  placeholder="传感器对应状态"></el-input>
        </el-form-item>
        <!--
        <el-form-item label="检测数据" prop="senseData">
          <el-input type="number" v-model="form.senseData" placeholder="请输入检测数据" />
        </el-form-item>
        <el-form-item label="数据上限" prop="dataUpper">
          <el-input type="number" v-model="form.dataUpper" placeholder="请输入数据上限" />
        </el-form-item>
        <el-form-item label="数据下限" prop="dataLower">
          <el-input type="number" v-model="form.dataLower" placeholder="请输入数据下限" />
        </el-form-item>
        <el-form-item label="mac地址" prop="macAdd">
          <el-input v-model="form.macAdd" placeholder="请输入mac地址" />
        </el-form-item>
        -->
        <el-form-item label="实验室" prop="subjectId">
          <el-select v-model="form.subjectId" placeholder="请选择实验室">
            <el-option
              v-for="item in subjectAddOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <!--<el-form-item label="实验室" prop="type">-->
          <!--<el-select v-model="form.type" placeholder="请选择实验室">-->
            <!--<el-option label="请选择字典生成" value="" />-->
          <!--</el-select>-->
        <!--</el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import mqtt from 'mqtt'
import { listSensor, getSensor, delSensor, addSensor, updateSensor,getSensorList } from "@/api/laboratory/sensor";
import { listDepartments } from "@/api/system/dept";
import { subjectDictList } from "@/api/laboratory/group";

import { treeselect } from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "Sensor",
  components: { Treeselect },
  data() {
    return {
      tableButtonType:this.hasPermiDom(['laboratory:sensor:query','laboratory:sensor:edit','laboratory:sensor:remove']),
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 传感器表格数据
      sensorList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 部门树选项
      deptOptions: [],
      subjectOptions: [],
      subjectAddOptions: [],
      sensorAddOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize:20,
        name: null,
        factory: null,
        type: [],
        senseData: null,
        gatewayId: null,
        dataUpper: null,
        senseState: null,
        dataLower: null,
        macAdd: null,
        subjectId: null,
        deptId: null,
        deptName: null,
        userId: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name:[
          {required: true, message: '传感器名称不能为空', trigger: 'blur'},
          { required: true, message: "传感器名称不能为空", validator: this.spaceJudgment, trigger: "blur" }
        ],
        type:[
          {required: true, message: '传感器类型不能为空', trigger: 'blur'},
          { required: true, message: "传感器类型不能为空", validator: this.spaceJudgment, trigger: "blur" }
        ],
        gatewayId:[
          {required: true, message: '网关不能为空', trigger: 'blur'},
          { required: true, message: "网关不能为空", validator: this.spaceJudgment, trigger: "blur" },
          { pattern:/^(192\.168(\.(\d|([1-9]\d)|(1\d{2})|(2[0-4]\d)|(25[0-5]))){2})$/, message: "请输入正确的网关", trigger: "blur" }
        ],
        senseData:[
          {required: true, message: '检测数据不能为空', trigger: 'blur'},
          { required: true, message: "检测数据不能为空", validator: this.spaceJudgment, trigger: "blur" }
        ],
        dataUpper:[
          {required: true, message: '数据上限不能为空', trigger: 'blur'},
          { required: true, message: "数据上限不能为空", validator: this.spaceJudgment, trigger: "blur" }
        ],
        dataLower:[
          {required: true, message: '数据下限不能为空', trigger: 'blur'},
          { required: true, message: "数据下限不能为空", validator: this.spaceJudgment, trigger: "blur" }
        ],
        subjectId:[
          {required: true, message: '实验室不能为空', trigger: 'blur'}
        ]
      },
      //MQTT请求参数-设备
      msg:"",
    };
  },
  created() {
  },
  mounted(){
    this.getList();
    this.getDeptList();
  },
  methods: {
    /** 查询实验室字典列表 */
    getSubjectDictList (deptId) {
      this.subjectOptions = null;
      this.loading = true;
      // this.queryParams.deptId = deptId;
      let params = {};
      params.deptId = deptId;
      this.queryParams.subjectId = "";
      subjectDictList(params).then(response => {
        this.subjectOptions = response.data;
        this.loading = false;
      });
    },
    /** 查询实验室字典列表 */
    getSubjectAddDictList () {
      this.subjectAddOptions = null;
      this.loading = true;
      let params = {};
      subjectDictList(params).then(response => {
        this.subjectAddOptions = response.data;
        this.loading = false;
      });

      getSensorList().then(response => {
        this.sensorAddOptions = response.data;
      });
    },
    /** 查询传感器列表 */
    getList() {
      this.loading = true;
      listSensor(this.queryParams).then(response => {
        this.sensorList = 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;
      // console.log("data",data);
      this.getSubjectDictList(data);
      // this.getList();
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        factory: null,
        type: null,
        senseData: null,
        gatewayId: null,
        dataUpper: null,
        dataLower: null,
        macAdd: null,
        subjectId: null,
        deptId: null,
        createTime: null,
        deptName: null,
        userId: null,
        createBy: null,
        updateTime: null,
        updateBy: null,
        remark: null,
        configName:null,
        configStatus:null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.subjectOptions = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getSubjectAddDictList();
      this.open = true;
      this.title = "新增传感器";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getSubjectAddDictList();
      const id = row.id || this.ids
      getSensor(id).then(response => {
        this.form = response.data;
        this.form.type = response.data.type.enumName;
        this.open = true;
        this.title = "修改传感器";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            this.form.senseState = null
            updateSensor(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSensor(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('确认删除传感器吗?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delSensor(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('laboratory/sensor/export', {
        ...this.queryParams
      }, `laboratory_sensor.xlsx`)
    }
  },
};
</script>
<style scoped lang="scss">
  .sensor{
    display: flex!important;
    flex-direction: column;
    box-shadow: 0 0 8px 2px rgba(0, 0, 0, 0.1);
    padding:20px!important;
    .button-box{
      width:200px;
      display: flex;
    }
    .form-box{
    }
  }
</style>

