<template>
  <div>
    <el-breadcrumb separator=">">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>
        <a href="#">系统管理</a>
      </el-breadcrumb-item>
      <el-breadcrumb-item>
        <a href="/deviceInfo">设备管理</a>
      </el-breadcrumb-item>
    </el-breadcrumb>
    <el-divider></el-divider>
    <!--
      要resetFields起作用，必须配置:model和prop
    -->
    <el-form ref="queryForm" :model="queryModel" inline class="demo-form-inline">
      <el-form-item label="所属单位" prop="companyId">
        <!-- <el-select
          v-model="queryModel.companyId"
          size="mini"
          filterable
          placeholder="请选择"
          style="width:280px"
        >
          <el-option
            v-for="company in companyResult"
            :key="company.id"
            :label="company.name"
            :value="company.id"
          ></el-option>
        </el-select>-->
        <el-select-tree
          :props="props"
          :options="companyResult"
          :value="queryModel.companyId"
          @getValue="getSelectedValue($event)"
          height="200"
        ></el-select-tree>&nbsp;
      </el-form-item>
      <el-form-item label="设备编号" prop="deviceNo">
        <el-input type="text" size="mini" v-model="queryModel.deviceNo"></el-input>
      </el-form-item>
      <el-form-item label="设备别名" prop="aliasName">
        <el-input type="text" size="mini" v-model="queryModel.aliasName"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          size="mini"
          icon="ios-search"
          @click="changePage(1)"
          :loading="loading"
        >查询</el-button>&nbsp;
        <el-button
          type="info"
          size="mini"
          style="margin-left: 8px"
          @click="handleReset('queryForm')"
        >重置</el-button>&nbsp;
      </el-form-item>
    </el-form>
    <el-divider></el-divider>
    <el-row class="button-group">
      <el-button type="primary" size="small" plain icon="el-icon-circle-plus" @click="handleAdd">新增</el-button>
      <el-button
        type="primary"
        size="small"
        plain
        icon="el-icon-remove"
        :disabled="multipleSelection.length==0"
        @click="handleBatchDelete"
      >删除选中项</el-button>
    </el-row>
    <el-table
      ref="formTable"
      :data="tableData"
      v-loading="loading"
      stripe
      @sort-change="sortChange"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="deviceNo" label="设备编号" width="200" fixed="left"></el-table-column>
      <el-table-column type="index" label="序号" :index="indexMethod" width="50"></el-table-column>
      <el-table-column prop="companyName" label="单位" width="280" show-overflow-tooltip></el-table-column>

      <el-table-column prop="aliasName" label="设备别名" width="250" show-overflow-tooltip></el-table-column>
      <el-table-column prop="isOnline" label="运行状态" width="80">
        <template slot-scope="{row}">
          <div
            v-if="row.isOnline"
            style="border-radius: 30px;background-color:#67C23A;width:20px;height:20px;"
          ></div>
          <div
            v-if="!row.isOnline"
            style="border-radius: 30px;background-color:#F56C6C;width:20px;height:20px;"
          ></div>
        </template>
      </el-table-column>
      <el-table-column prop="ipAddress" label="ip地址" width="150"></el-table-column>
      <el-table-column prop="port" label="端口" width="80"></el-table-column>
      <!-- <el-table-column prop="unlockPassword" label="开锁密码" width="150"></el-table-column>
      <el-table-column prop="codeAddress" label="二维码地址" width="180"></el-table-column>-->
      <el-table-column prop="typeN" label="类型" width="80"></el-table-column>
      <el-table-column label="操作" width="250">
        <template slot-scope="{row}">
          <el-row>
            <el-col :span="8">
              <el-link type="primary" @click="handleEdit(row)">编辑</el-link>
            </el-col>
            <el-col :span="8">
              <el-link type="danger" @click="handleDelete(row)">删除</el-link>
            </el-col>
            <el-col :span="8">
              <el-link type="primary" @click="handlePoint(row)">定位</el-link>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-link type="primary" @click="handleBindPerson(row)">用户关联</el-link>
            </el-col>
            <el-col :span="8">
              <el-link type="primary" @click="handleEditRule(row)">验证规则</el-link>
            </el-col>
            <el-col :span="8">
              <el-link type="primary" @click="handleReboot(row)">重启设备</el-link>
            </el-col>
          </el-row>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      :current-page.sync="pageIndex"
      :total="totalElements"
      :page-sizes="pageSizeList"
      @current-change="changePage"
      @size-change="pageSizeChange"
      layout="total, sizes, prev, pager, next, jumper"
    ></el-pagination>
    <deviceInfo-detail
      v-if="showModal"
      :businessKey="businessKey"
      :title="modalTitle"
      :typeData="typeData"
      :companyResult="companyResult"
      @close="onDetailModalClose"
    ></deviceInfo-detail>
    <!-------------设备验证规则start------------------>
    <el-dialog
      title="设备验证规则"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      append-to-body
      width="30%"
    >
      <el-form
        :model="ruleModel"
        ref="ruleForm"
        :rules="ruleValidate"
        inline
        :label-width="'100px'"
        style="text-align:left;"
      >
        <el-row>
          <el-col>
            <el-form-item label="安全帽">
              <el-radio-group v-model="ruleModel.needCap">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <el-form-item label="口罩">
              <el-radio-group v-model="ruleModel.needMask">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <el-form-item label="测温">
              <el-radio-group v-model="ruleModel.measureTemperature">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="ruleModel.measureTemperature == 1">
          <el-row>
            <el-col>
              <el-form-item label="位置">
                <el-radio-group v-model="ruleModel.type">
                  <el-radio :label="0">额头</el-radio>
                  <el-radio :label="1">手腕</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col>
              <el-form-item label="最低温度" prop="minimum">
                <el-input-number
                  v-model="ruleModel.minimum"
                  placeholder="请输入最低温度"
                  :precision="2"
                  :step="0.1"
                  :max="45"
                  :min="30"
                  style="width:200px"
                ></el-input-number>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col>
              <el-form-item label="最高温度" prop="maximum">
                <el-input-number
                  v-model="ruleModel.maximum"
                  placeholder="请输入最高温度"
                  :precision="2"
                  :step="0.1"
                  :max="45"
                  :min="30"
                  style="width:200px"
                ></el-input-number>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col>
              <el-form-item label="温度误差" prop="preAlarmOffset">
                <el-input-number
                  v-model="ruleModel.preAlarmOffset"
                  placeholder="请输入温度误差"
                  :precision="2"
                  :step="0.1"
                  :max="1"
                  :min="0.1"
                  style="width:200px"
                ></el-input-number>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col>
              <el-form-item label="报警温度" prop="alarmThreshold">
                <el-input-number
                  v-model="ruleModel.alarmThreshold"
                  placeholder="请输入报警温度"
                  :precision="2"
                  :step="0.1"
                  :max="45"
                  :min="30"
                  style="width:200px"
                ></el-input-number>
              </el-form-item>
            </el-col>
          </el-row>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveDeviceRule">确 定</el-button>
      </span>
    </el-dialog>
    <!-------------设备验证规则end------------------>
    <deviceInfo-map
      v-if="showMapModal"
      :businessKey="businessKey"
      :title="modalTitle"
      :typeData="typeData"
      :companyResult="companyResult"
      @close="onDetailModalClose"
    ></deviceInfo-map>
  </div>
</template>
<script>
import Constant from "@/constant";
import DeviceInfoDetail from "./deviceInfo-detail";
import DeviceInfoMap from "./deviceInfo-amap";
import deviceInfoApi from "@/api/base/deviceInfo";
import dataDictionaryApi from "@/api/sys/dataDictionary";
import companyInfoApi from "@/api/base/companyInfo";
import SelectTree from "@/components/SelectTree";

import NProgress from "nprogress"; // progress bar
import "nprogress/nprogress.css"; // progress bar style

export default {
  name: "BaseDeviceInfoList",
  data() {
    var self = this;

    return {
      ruleValidate: {
        minimum: [{ required: true, message: "不能为空", trigger: "blur" }],
        maximum: [{ required: true, message: "不能为空", trigger: "blur" }],
        alarmThreshold: [
          { required: true, message: "不能为空", trigger: "blur" }
        ]
      },
      queryModel: {
        deviceNo: "",
        aliasName: "",
        companyId: ""
      },
      loading: false,
      tableData: [],
      pageIndex: 1,
      pageSize: 10,
      totalPages: 0,
      totalElements: 0,
      field: "",
      direction: "",
      pageSizeList: [10, 20, 30],
      multipleSelection: [],
      showModal: false,
      modalTitle: "",
      businessKey: "",
      typeData: [],
      companyResult: [],
      tableHeight: 400,
      dialogVisible: false,
      ruleDeviceId: "",
      // ruleList: [],
      // temperatureRule: "",
      ruleModel: {
        needCap: "",
        needMask: "",
        measureTemperature: "",
        type: "",
        minimum: "",
        maximum: "",
        preAlarmOffset: "",
        alarmThreshold: ""
      },
      treeData: [],
      props: {
        // 配置项（必选）
        value: "id",
        label: "name",
        children: "children"
      },
      showMapModal: false
    };
  },
  created() {
    var formData = new FormData();
    formData.append("catalogName", "设备类型");
    dataDictionaryApi.findByCatalogName(formData).then(response => {
      var jsonData = response.data;
      this.typeData = jsonData.data;
    });

    var self = this;
    companyInfoApi.list().then(function(response) {
      var jsonData = response.data;
      if (jsonData.result) {
        self.companyResult = jsonData.data;
      }
    });

    this.loadTree();
  },
  methods: {
    indexMethod(index) {
      return (this.pageIndex - 1) * this.pageSize + (index + 1);
    },
    getSelectedValue(value) {
      this.queryModel.companyId = value;
    },
    loadTree() {
      var formData = new FormData();

      companyInfoApi.loadChildren(formData).then(resp => {
        var jsonData = resp.data;

        if (jsonData.result) {
          this.treeData = jsonData.data;
        } else {
          this.$message.error(jsonData.message + "");
        }
      });
    },
    loadChildren(tree, treeNode, resolve) {
      console.log(tree);

      var formData = new FormData();
      formData.append("parentId", tree.id);

      companyInfoApi.loadChildren(formData).then(resp => {
        var jsonData = resp.data;

        if (jsonData.result) {
          resolve(jsonData.data);
        } else {
          this.$message.error(jsonData.message + "");
        }
      });
    },
    changePage(pageIndex) {
      var self = this;

      self.loading = true;

      self.pageIndex = pageIndex;
      var formData = new FormData();

      formData.append("pageIndex", self.pageIndex);
      formData.append("pageSize", self.pageSize);

      formData.append("deviceNo", self.queryModel.deviceNo);
      formData.append("aliasName", self.queryModel.aliasName);
      var companyId = self.queryModel.companyId;
      if (companyId == null) {
        companyId = "";
      }
      formData.append("companyId", companyId);

      if (this.field != null) {
        formData.append("field", this.field);
      }

      if (this.direction != null) {
        formData.append("direction", this.direction);
      }

      deviceInfoApi
        .pageList(formData)
        .then(function(response) {
          self.loading = false;

          var jsonData = response.data.data;

          self.tableData = jsonData.data;
          self.totalPages = jsonData.totalPages;
          self.totalElements = jsonData.recordsTotal;

          //45为分页栏的高度
          //页面高度-列表上面的高度-分页栏高度
          self.tableHeight =
            window.innerHeight - self.$refs.formTable.$el.offsetTop - 45;
        })
        .catch(error => {
          self.loading = false;
          // self.$message.error(error + "");
        });
    },
    pageSizeChange(pageSize) {
      this.pageSize = pageSize;
    },
    sortChange(data) {
      this.field = data.column.field;
      this.direction = data.order;

      this.changePage(this.pageIndex);
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handleReset(name) {
      this.$refs[name].resetFields();
    },
    handleAdd() {
      this.modalTitle = "新增";
      this.businessKey = "";
      this.showModal = true;
    },
    handleEdit(record) {
      this.modalTitle = "编辑";
      this.businessKey = record.id;
      this.showModal = true;
    },
    handleDelete(record) {
      var self = this;

      self
        .$confirm("是否确认删除?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
        .then(() => {
          deviceInfoApi.remove(record.id).then(function(response) {
            var jsonData = response.data;

            if (jsonData.result) {
              // var index = self.tableData.indexOf(record);
              // self.tableData.splice(index, 1);
              self.changePage(self.pageIndex);

              self.$message({
                type: "success",
                message: "删除成功!"
              });
            }
          });
        });
    },
    handleBatchDelete() {
      var self = this;

      var idList = this.multipleSelection.map(record => {
        return record.id;
      });

      this.$confirm("是否确认删除选中项？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        deviceInfoApi.batchRemove(idList).then(function(response) {
          var jsonData = response.data;

          if (jsonData.result) {
            self.changePage(self.pageIndex);

            self.$message({
              type: "success",
              message: "删除成功!"
            });
          }
        });
      });
    },
    onDetailModalClose(refreshed) {
      //保存成功后回调
      this.showModal = false;
      this.showMapModal = false;

      if (refreshed) {
        this.changePage(this.pageIndex);
      }
    },
    handleEditRule(record) {
      var self = this;
      self.loading = true;
      var formData = new FormData();
      formData.append("deviceId", record.id);
      self.ruleDeviceId = record.id;
      deviceInfoApi.getDeviceRule(formData).then(function(response) {
        var jsonData = response.data;
        if (jsonData.result) {
          self.loading = false;
          self.dialogVisible = true;
          console.log(jsonData.data);
          //开关列表
          var ruleList = jsonData.data.RuleList;
          ruleList.forEach((item, index) => {
            if (item.Mode == "1") {
              self.ruleModel.needCap = item.Enabled;
            } else if (item.Mode == "2") {
              self.ruleModel.needMask = item.Enabled;
            } else if (item.Mode == "3") {
              self.ruleModel.measureTemperature = item.Enabled;
            }
          });
          //获取温度设置列表
          var temperatureRule = jsonData.data.TemperatureRule;
          self.ruleModel.type = temperatureRule.Type;
          self.ruleModel.minimum = temperatureRule.Minimum;
          self.ruleModel.maximum = temperatureRule.Maximum;
          self.ruleModel.preAlarmOffset = temperatureRule.PreAlarmOffset;
          self.ruleModel.alarmThreshold = temperatureRule.AlarmThreshold;
        } else {
          self.loading = false;
          self.$alert(jsonData.message, "提示", {
            confirmButtonText: "确定"
          });
        }
      });
    },
    saveDeviceRule() {
      var self = this;
      this.$refs["ruleForm"].validate(valid => {
        if (valid) {
          var formData = new FormData();
          formData.append("deviceInfoId", self.ruleDeviceId);
          formData.append("needCap", self.ruleModel.needCap);
          formData.append("needMask", self.ruleModel.needMask);
          formData.append(
            "measureTemperature",
            self.ruleModel.measureTemperature
          );
          formData.append("type", self.ruleModel.type);
          formData.append("minTemper", self.ruleModel.minimum);
          formData.append("maxTemper", self.ruleModel.maximum);
          formData.append("alarmThreshold", self.ruleModel.alarmThreshold);
          deviceInfoApi.saveDeviceRule(formData).then(function(response) {
            var jsonData = response.data;
            if (jsonData.result) {
              self.$message({
                type: "success",
                message: "成功"
              });
              self.dialogVisible = false;
            } else {
              self.$message({
                type: "success",
                message: jsonData.message
              });
            }
          });
        }
      });
    },
    handlePoint(record) {
      this.modalTitle = "定位";
      this.businessKey = record.id;
      this.showMapModal = true;
    },
    handleReboot(record) {
      var self = this;

      this.$confirm("是否确定将" + record.aliasName + "重启?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        self.loading = true;
        self.loadingText = "重启中...";

        var formData = new FormData();
        formData.append("deviceId", record.id);

        deviceInfoApi.reboot(formData).then(function(response) {
          var jsonData = response.data;

          self.loading = false;
          self.loadingText = "";

          if (jsonData.result) {
            self.$message.success(jsonData.message + "");
          } else {
            self.$message.warning(jsonData.message + "");
          }
        });
      });
    }
  },
  mounted: function() {
    var self = this;
    this.changePage(1);
  },
  components: {
    "deviceInfo-detail": DeviceInfoDetail,
    "el-select-tree": SelectTree,
    "deviceInfo-map": DeviceInfoMap
  }
};
</script>
<style lang="scss" scoped>
.el-breadcrumb {
  margin: 10px;
  line-height: 20px;
}

.el-divider {
  margin: 5px 0;
}

.demo-form-inline {
  margin-left: 10px;
  text-align: left;
}

.button-group {
  margin-left: 10px;
  text-align: left;
}
</style>