<template>
  <div class="app-container">
    <el-form :inline="true" :model="formSearch" class="demo-form-inline">
      <el-form-item label="设备编号">
        <el-input v-model="formSearch.deviceNum" placeholder="输入完整设备编号"></el-input>
      </el-form-item>
      <el-form-item label="设备名称">
        <el-input v-model="formSearch.deviceName" placeholder="设备名称"></el-input>
      </el-form-item>
      <el-form-item label="设备类型">
        <el-select
          v-model="formSearch.deviceType"
          style="margin-left: 20px;"
          placeholder="请选择"
        >
          <el-option
            v-for="item in optionTypes"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="状态">
        <el-select
          v-model="formSearch.deviceStatus"
          style="margin-left: 20px;"
          placeholder="请选择"
        >
          <el-option
            v-for="item in optionStatus"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button v-if="device != '' " v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">
          {{ $t('table.export') }}
        </el-button>
      </el-form-item>
    </el-form>
    <el-table :key="tableKey" v-loading="loading" :data="device" border fit highlight-current-rows>
      <el-table-column align="center" label="ID" width="80">
        <template slot-scope="scope">
          <span>{{ scope.row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="设备编号" width="150">
        <template slot-scope="scope">
          <span @click="handleCopy(scope.row.devicenum,$event)">{{ scope.row.devicenum }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="设备名称" width="200">
        <template slot-scope="scope">
          <span>{{ scope.row.username }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="设备详情">
        <template slot-scope="scope">
          <span>{{ scope.row.deviceinfo }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="设备类型" width="150">
        <template slot-scope="scope">
          <span>{{ scope.row.tname }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="检测介质" width="170">
        <template slot-scope="scope">
          <span>{{ scope.row.gas }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="切断装置" width="170">
        <template slot-scope="scope">
          <span>{{ shutoffDevice(scope.row.shutoff_type) }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="检测值" width="100">
        <template slot-scope="scope">
          <span>{{ scope.row.nd }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="单位" width="100">
        <template slot-scope="scope">
          <span>{{ scope.row.danwei }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="切断装置状态" width="120">
        <template slot-scope="scope">
          <span>
            <el-popconfirm
              :title="'确定' + unshutoff_status(scope.row.shutoff_status) + scope.row.username + shutoffDevice(scope.row.shutoff_type) + '吗?'"
              @onConfirm="changeShutoffStatus(scope.row.id, scope.row.shutoff_status, scope.row.dtype)"
              @onCancel="()=>{}"
            >
              <el-button
                slot="reference"
                :loading="shutoff_loading"
                size="mini"
                :type=" scope.row.shutoff_status==1 ? 'success' : 'warning' "
                @click="shutoff_visible = true"
              >
                {{ shutoffStatus(scope.row.shutoff_status) }}
              </el-button>
            </el-popconfirm>
          </span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="实时状态" width="120">
        <template slot-scope="scope">
          <span>
            <el-tag :type=" scope.row.status_name=='正常' ? 'success' : 'warning' " effect="dark">{{ scope.row.status_name }}</el-tag>
          </span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="状态" width="70">
        <template slot-scope="scope">
          <span v-if="scope.row.status_name=='正常' " :style="{color:( scope.row.devicestatus==1 ? '#67C23A' : '#F56C6C' )}">{{ scope.row.devicestatus==1 ? '正常' : '错误' }}</span>
          <span v-if="scope.row.status_name!='正常' " :style="{color:( scope.row.status_name=='正常' ? '#67C23A' : '#F56C6C' )}">{{ scope.row.status_name=='正常' ? '正常' : '异常' }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="最后更新时间" width="170">
        <template slot-scope="scope">
          <span v-if="scope.row.update_time > 0">{{ scope.row.update_time | parseTime('{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="formSearch.page"
      :limit.sync="formSearch.limit"
      :page-sizes="[10,30,80]"
      @pagination="devicelist"
    />
  </div>
</template>

<script>
import { control, updedata } from '@/api/device';
import Pagination from '@/components/Pagination'; // 分页
import websocketurl from '@/api/configurl';
import clip from '@/utils/clipboard';
import waves from '@/directive/waves'; // 水波纹效果
import { parseTime } from '@/utils';
export default {
  name: 'Devicetype',
  directives: { waves },
  components: { Pagination },
  data() {
    return {
      shutoff_visible: false,
      shutoff_loading: false,
      downloadLoading: false,
      tableKey: 0,
      loading: true,
      device: [],
      type: 1,
      total: 0,
      paper: undefined,
      timer: '',
      formSearch: {
        deviceNum: '',
        deviceName: '',
        deviceType: 0,
        deviceStatus: 0,
        userId: 0,
        page: 1,
        limit: 10,
      },
      optionStatus: [{
        value: 0,
        label: '全部',
      }, {
        value: 1,
        label: '正常',
      }, {
        value: 2,
        label: '错误',
      }, {
        value: 3,
        label: '传感器故障',
      }, {
        value: 4,
        label: '报警',
      }, {
        value: 5,
        label: '低报',
      }, {
        value: 6,
        label: '高报',
      }, {
        value: 7,
        label: '通信故障',
      }, {
        value: 8,
        label: '超量程',
      }, {
        value: 9,
        label: '离线',
      }, {
        value: 10,
        label: '电量低',
      }, {
        value: 11,
        label: '主电故障',
      }, {
        value: 12,
        label: '备电故障',
      }, {
        value: 13,
        label: '无此节点',
      }, {
        value: 14,
        label: '低电压',
      }, {
        value: 15,
        label: '故障',
      }, {
        value: 16,
        label: '报警联动',
      }],
      optionTypes: [{
        value: 0,
        label: '全部',
      }, {
        value: 2,
        label: '家用报警器',
      }, {
        value: 4,
        label: '家用报警器(IOT)',
      }, {
        value: 6,
        label: '烟雾感应设备',
      }, {
        value: 7,
        label: '烟雾感应设备(联通)',
      }, {
        value: 8,
        label: '家用报警器(RTU)',
      }, {
        value: 9,
        label: '液位探测器',
      }, {
        value: 11,
        label: '消防报警及联动设备',
      }],
    };
  },
  created() {
    this.devicelist(); // 设备状态
    this.initWebSocket();
  },

  methods: {
    // 切断装置
    shutoffDevice(id) {
      const shutoff_types = [];
      shutoff_types[0] = '未绑定';
      shutoff_types[1] = '电磁阀';
      shutoff_types[2] = '机械手';
      return shutoff_types[id];
    },
    shutoffStatus(id) {
      const shutoff = [];
      shutoff[2] = '初始化';
      shutoff[0] = '开启';
      shutoff[1] = '关闭';
      return shutoff[id];
    },
    unshutoff_status(state) {
      return state === 0 ? '关闭' : '开启';
    },
    // 修改切断装置状态
    changeShutoffStatus(id, shutoff_status, tid) {
      updedata({ deid: id, device_control: shutoff_status !== 1 ? 1 : 0, tid: tid })
        .then(response => {
          // this.devicelist();
        })
        .catch(err => {
          console.log(err);
        });
    },
    onSubmit() {
      this.formSearch.page = 1;
      this.devicelist();
    },
    devicelist() {
      const limit = this.formSearch.limit;
      const page = this.formSearch.page;
      this.loading = true;
      control(page, limit, this.type, this.formSearch)
        .then(response => {
          var devicetype = response.data['devicelist'];
          this.device = devicetype;
          this.device.forEach((element, index) => {
            element['index'] = (page - 1) * limit + index + 1;
          });
          this.total = response.data.count;
          this.loading = false;
        })
        .catch(err => {
          console.log(err);
        });
    },
    initWebSocket(){ // 初始化weosocket
      const wsuri = websocketurl.fireUrl;
      this.websock = new WebSocket(wsuri);
      this.websock.onmessage = this.websocketonmessage;
      this.websock.onopen = this.websocketonopen;
      this.websock.onerror = this.websocketonerror;
      this.websock.onclose = this.websocketclose;
    },
    websocketonopen(){ // 连接建立之后执行send方法发送数据
      this.timer = setInterval(() => {
        this.websocketsend();
      }, 5000);
    },
    websocketonerror(){ // 连接建立失败重连
      this.$notify({
        title: '警告',
        message: '建立链接失败,正在重连',
        type: 'warning',
      });
      this.initWebSocket();
    },
    websocketonmessage(e){ // 数据接收
      const redata = JSON.parse(e.data);
      this.device = redata.data.devicelist;
      this.total = redata.data.count;
    },
    websocketsend(){ // 数据发送
      this.formSearch.userId = localStorage.getItem('userinfoid');
      this.websock.send(JSON.stringify(this.formSearch));
    },
    websocketclose(e){ // 关闭
      console.log('断开连接', e);
      this.$notify({
        title: '警告',
        message: '危化监测长连接已断开',
        type: 'warning',
      });
      clearInterval(this.timer);
    },
    handleClick(tab) {
      this.type = tab.$attrs.tid;
      this.devicelist();
    },
    handleCopy(text, event) {
      clip(text, event);
    },
    handleCopyphone(text, event){
      clip(text, event);
    },
    // 导出到excel
    handleDownload() {
      this.downloadLoading = true;
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['ID', '设备编号', '设备名称', '设备详情', '设备类型', '检测介质', '切断装置', '单位', '切断装置状态', '实时状态', '最后更新时间'];
        const filterVal = ['id', 'devicenum', 'username', 'deviceinfo', 'tname', 'gas', 'shutoff_type', 'danwei', 'shutoff_status', 'status_name', 'update_time'];
        const data = this.formatJson(filterVal, this.device);
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: '消防监测',
        });
        this.downloadLoading = false;
      });
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        if (j === 'shutoff_type') {
          return this.shutoffDevice(v[j]);
        } else if (j === 'shutoff_status') {
          return this.shutoffStatus(v[j]);
        } else if (j === 'update_time') {
          return parseTime(v[j]);
        } else {
          return v[j];
        }
      }));
    },
  },
};
</script>

<style>
</style>