<template>
  <div id="container">
    <div class="alarmrecord">
      <el-card class="box-card">
        <el-row class="">
          <div class="search">
            <div class="inputInline">
              <el-select v-model="selectoptionValue" v-if="userInfo.type==0"  class="w150" size="mini" placeholder="请选择数据中心"  @change="selectTenantId" style="width: 1.5rem;" >
                  <el-option v-for="item in selectoption" :key="item.value" :label="item.label" :value="item.value">
                  </el-option>
                </el-select>
              <!-- <selectoption></selectoption> -->
              <el-cascader :options="roomData" v-model="searchForm.roomName" class="w150" popper-class="cascadername"
                :props="{ checkStrictly: true }" @change="checkNode" clearable size="mini">
              </el-cascader>
              <el-input v-model="searchForm.deviceNum" class="w150" :clearable="true" placeholder="设备名称" size="mini"
                @input="InputFun($event,'deviceNum')"></el-input>
              <el-input v-model="searchForm.imei" :clearable="true" class="w150" placeholder="IMEI" size="mini"
                @input="InputFun($event,'imei')"></el-input>
              <!--< el-input v-model="searchForm.name" :clearable="true" placeholder="请输入房间名称" size="mini"
								@input="InputFun($event,'name')"></el-input> -->
              <!-- <el-input v-model="searchForm.siteIds" :clearable="true" placeholder="位置名称" size="mini"
								@input="InputFun($event,'siteIds')"></el-input> -->
              <el-date-picker size="mini" class="w250" v-model="searchForm.time" @input="InputFun($event,'time')"
                type="datetimerange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
              </el-date-picker>
              <div class="quantity">
                电量： <el-input placeholder="" clearable v-model="searchForm.startBattery" class="w50" size="mini"
                  @input="InputFun($event,'startBattery')">
                  <template slot="append">%</template>
                </el-input> - <el-input placeholder="" clearable v-model="searchForm.endBattery" class="w50" size="mini"
                  @input="InputFun($event,'endBattery')">
                  <template slot="append">%</template>
                </el-input>
              </div>
              <div class="quantity">
                <el-select v-model="searchForm.operateCode" class="w150" @input="InputFun($event,'operateCode')" clearable placeholder="报警类型"
                  size="mini">
                  <el-option v-for="item in alertType" :key="item.value" :label="item.label" :value="item.value">
                  </el-option>
                </el-select>
              </div>
            </div>
            <el-button size="mini" @click="reset">重置</el-button>
            <el-button type="primary" size="mini" @click="getReportList">查询</el-button>
          </div>
        </el-row>
        <el-row class="marginTop">
          <div class="tablecell">
            <el-row class="floatRight">
              <el-button type="primary" size="mini" @click="exportFun">导出</el-button>
            </el-row>
            <el-table ref="multipleTable" :data="tableData" :border="true" tooltip-effect="dark" style="width: 100%"
              :header-cell-style="rowClass" :cell-style="{fontSize:'12px'}" @selection-change="handleSelectionChange"
              stripe height="590">
              <!-- 	<el-table-column type="selection" width="55">
							</el-table-column> -->
              <el-table-column prop="deviceNum" label="设备名称" width="200"></el-table-column>
              <el-table-column prop="name" label="房间名称" width="200"></el-table-column>
              <el-table-column prop="imei" label="IMEI" width="200"></el-table-column>
              <el-table-column prop="imsi" label="IMSI" width="200"></el-table-column>
              <el-table-column prop="battery" label="电池电量">
              </el-table-column>
              <el-table-column prop="voltage" label="电池电压">
              </el-table-column>
              <el-table-column prop="rssi" label="信号强度">
              </el-table-column>
              <el-table-column prop="operateCode" label="报警类型">
                <template slot-scope="scope">
                  <span v-if="scope.row.operateCode==0">心跳</span>
                  <span v-if="scope.row.operateCode==1">开门报警</span>
                  <span v-if="scope.row.operateCode==2">低电报警</span>
                  <span v-if="scope.row.operateCode==4">防拆报警</span>
                  <span v-if="scope.row.operateCode==5">设备故障报警</span>
                  <span v-if="scope.row.operateCode==13">设备测试</span>
                  <span v-if="scope.row.operateCode==17">关门报警</span>
                  <span v-if="scope.row.operateCode==18">低电压恢复与上电开机</span>
                  <span v-if="scope.row.operateCode==20">防拆恢复</span>
                  <span v-if="scope.row.operateCode==21">故障恢复</span>
                  <span v-if="scope.row.operateCode==170">设备ACK</span>
                  <span v-if="scope.row.operateCode==30">添加子设备</span>
                  <span v-if="scope.row.operateCode==31">删除子设备</span>
                </template>
              </el-table-column>
              <el-table-column prop="createAt" label="最近报警时间" width="200">
              </el-table-column>
            </el-table>
          </div>
          <div class="page">
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
              :current-page="currentPage" :page-sizes="[10, 20, 30, 100]" :page-size="pageSize"
              layout="total, sizes, prev, pager, next, jumper" :total="pageTotal">
            </el-pagination>
          </div>
        </el-row>
      </el-card>
      <el-dialog title="报警处理" :visible.sync="dialogVisible" width="30%" :before-close="handleClose">
        <el-input type="textarea" :rows="2" :clearable="true" placeholder="备注" v-model="textarea" @input="textareaFun">
        </el-input>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="dialogVisible = false">处 理</el-button>
        </span>
      </el-dialog>
      <el-dialog :title="titleText" :visible.sync="dialogVisible1" width="60%" class="dialogcontent"
        :before-close="handleClose1">
        <div class="tablecell">
          <el-row class="floatRight">
            <el-button type="danger" size="mini" @click="batchProcessing">一键处理处理全部报警</el-button>
            <el-button type="primary" size="mini">导出</el-button>
          </el-row>
          <el-table ref="multipleTable" :data="tableData" :border="true" tooltip-effect="dark" style="width: 100%"
            :header-cell-style="rowClass" :cell-style="{fontSize:'12px'}" @selection-change="handleSelectionChange"
            stripe height="400">
            <el-table-column type="selection" width="55">
            </el-table-column>
            <el-table-column label="日期" width="120">
              <template slot-scope="scope">{{ scope.row.date }}</template>
            </el-table-column>
            <el-table-column prop="name" label="姓名" width="120">
            </el-table-column>
            <el-table-column prop="address" label="地址" show-overflow-tooltip>
            </el-table-column>
            <el-table-column label="操作" width="80">
              <template slot-scope="scope">
                <el-button type="primary" size="mini">处理</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="page">
          <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
            :current-page="currentPage" :page-sizes="[10, 20, 30, 100]" :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper" :total="pageTotal">
          </el-pagination>
        </div>
        <!-- <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible1 = false">取 消</el-button>
                <el-button type="primary" @click="dialogVisible1 = false">处 理</el-button>
            </span> -->
      </el-dialog>
    </div>
  </div>
</template>

<script>
  import {
    httpGet,
    httpPost,
    downloadPost,
    download
  } from "../../api/index";
  import axios from "axios"
  import {
    ztreeToElementTree,
    recursion,
    uniqueArray,
    uniqueArray1,
    paramsValidate
  } from "../../utils/index"
  import moment from "moment"
  // import XLSX from "xlsx";
  export default {
    inject: ['reload'],
    name: "alarmRecord",
    data() {
      return {
        selectoption:[],
        selectoptionValue:'',
        alertType: [{
          value: '0',
          label: '心跳'
        }, {
          value: '1',
          label: '开门报警'
        }, {
          value: '2',
          label: '低电报警'
        }, {
          value: '4',
          label: '防拆报警'
        }, {
          value: '5',
          label: '设备故障报警'
        }, {
          value: '13',
          label: '设备测试'
        }, {
          value: '17',
          label: '关门报警'
        }, {
          value: '18',
          label: '低电压恢复与上电开机'
        }, {
          value: '20',
          label: '防拆恢复'
        }, {
          value: '21',
          label: '故障恢复'
        }, {
          value: '30',
          label: '添加子设备'
        }, {
          value: '31',
          label: '删除子设备'
        }, {
          value: '170',
          label: '设备ACK'
        }, ],
        searchForm: {
          operateCode: '',
          roomName: '',
          time: '',
          name: "",
          deviceNum: '',
          siteIds: '',
          startBattery: '',
          endBattery: '',
          startTime: '',
          endTime: ''
        },
        titleText: '设备未处理报警记录(IMEI:860709056256857)',
        textarea: '', //批量处理备注
        dialogVisible: false,
        dialogVisible1: false,
        input: '',
        content: '切换单个/多个查询模式',
        selected: true,
        advancedQueryStatus: false,
        advancedQueryText: '高级查询',
        formInline: {
          region: '',
        },
        tableData: [],
        rowStyle: {
          background: '#f8f9fa',
          fontSize: '12px'
        },
        multipleSelection: [],
        currentPage: 1,
        batch: true,
        pageTotal: 0,
        pageSize: 10,
        roomData: [],
        checkNodeId: '',
        selectRow: [],
        userInfo: {
          type: ''
        }
      }
    },
    created() {
      this.userInfo = JSON.parse(localStorage.getItem('info'))
      this.selectoption=JSON.parse(localStorage.getItem('selectoption'))
      this.selectoptionValue=localStorage.getItem('tenantId')
      this.getReportList()
      this.getlist()
    },
    mounted() {},
    computed: {

    },
    methods: {
      selectTenantId(e) {
        localStorage.setItem('tenantId', e)
        this.reload()
      },
      exportFun() {
        var q = this.yz(this.searchForm)
        var data = {
          fileName: "报警记录",
          q: JSON.stringify(q),
        };
        downloadPost(data, this.$api.deviceReport).then((res) => {
          const link = document.createElement("a");
          let blob = new Blob([res], {
            type: "application/vnd.ms-excel"
          });
          var objectUrl = URL.createObjectURL(blob);
          link.href = objectUrl;
          link.download = "报警记录.xlsx";
          link.click();
          URL.revokeObjectURL(objectUrl);
        });
      },
      // 选择房源
      checkNode(e) {
        this.checkNodeId = e
        // var str=this.getCascaderObj([e[e.length-1]],this.roomData)
        // console.log(str)
        var selectRow = []
        // this.roomData.map((li,index)=>{
        // 	if(li.id==e[0]){
        // 		selectRow=li
        // 	}
        // })
        selectRow = this.getChild(this.roomData, e[e.length - 1], [])
        // console.log(arr)
        // this.selectRow=selectRow
        this.searchForm.siteIds = selectRow
      },
      getChild(nodes, item, arr) {
        for (let el of nodes) {
          if (el.id === item) {
            arr.push(el.id);
            if (el.children) {
              this.childNodesDeep(el.children, arr);
            }
          } else if (el.children) {
            this.getChild(el.children, item, arr);
          }
        }
        return arr;
      },
      childNodesDeep(nodes, arr) {
        if (nodes)
          nodes.forEach((ele) => {
            arr.push(ele.id);
            if (ele.children) {
              this.childNodesDeep(ele.children, arr);
            }
          });
      },
      getCascaderObj(val, opt) {
        return val.map(function(value, index, array) {
          for (var itm of opt) {
            if (itm.value == value) {
              opt = itm.children;
              return itm;
            }
          }
          return null;
        });
      },
      // 获取列表
      getlist() {
        var data = {};
        httpGet(data, this.$api.getPlaceList).then((res) => {
          if (res.data.list.length > 0) {
            var arrdata = uniqueArray(res.data.list, "id")
            this.roomData = ztreeToElementTree(arrdata, {});
          }
        });
      },

      reset() {
        this.searchForm = {
          operateCode: '',
          roomName: '',
          time: '',
          name: "",
          deviceNum: '',
          siteIds: '',
          startBattery: '',
          endBattery: '',
          startTime: '',
          endTime: ''
        }
      },
      yz(obj) {
        var str = {}
        Object.keys(obj).forEach(function(key) {
          if (obj[key] != '' && key != 'roomName' && key != 'time') {
            str[key] = obj[key]
          }
        })
        return str
      },
      getReportList() {
        var q = this.yz(this.searchForm)
        var data = {
          pageNum: this.currentPage,
          pageSize: this.pageSize,
          orderType: 'desc',
          orderBy: "createAt",
          q: JSON.stringify(q)
        }
        httpPost(data, this.$api.getReportList).then(res => {
          if (res.success) {
            res.data.list.map(li => {
              li.createAt = moment(li.createAt).format('YYYY/MM/DD HH:mm:ss')
            })
            this.tableData = res.data.list
            this.pageTotal = res.data.total
          } else {
            this.$message.console.error("查询失败");
          }
        })
      },
      // 未处理记录打开
      recordFun() {
        this.dialogVisible1 = true
      },
      // 未处理记录处理关闭
      handleClose1(done) {
        done();
      },
      // 批量处理关闭
      handleClose(done) {
        done();
      },
      // 批量处理
      batchProcessing() {
        this.dialogVisible = true
      },
      // 分页
      handleSizeChange(val) {
        this.pageSize = val
        this.getReportList()
        console.log(`每页 ${val} 条`);
      },
      handleCurrentChange(val) {
        this.currentPage = val
        this.getReportList()
        console.log(`当前页: ${val}`);
      },
      // 表头样式
      rowClass({
        row,
        rowIndex
      }) {
        return "background:#f8f9fa;color:#333;font-blod:none;font-size:12px;"
      },
      // 表格勾选
      handleSelectionChange(val) {
        if (val.length > 0) {
          this.batch = false
        } else {
          this.batch = true
        }
      },
      // 高级查询显示
      advancedQueryFun() {
        if (this.advancedQueryStatus) {
          this.advancedQueryText = "高级查询"
          this.advancedQueryStatus = false
        } else {
          this.advancedQueryText = "同用查询"
          this.advancedQueryStatus = true
        }
      },
      // 批量处理备注监控
      textareaFun(e) {
        this.textarea = e
      },
      // 输入监控
      InputFun(e, name) {
        if (name == 'startBattery' || name == 'endBattery') {
          if (Number(e) < 0) {
            e = 0
          }
          if (Number(e) > 100) {
            e = 100
          }
        }
        if (name == "time") {
          this.searchForm.startTime = moment(e[0]).format('YYYY-MM-DD HH:mm:ss')
          this.searchForm.endTime = moment(e[1]).format('YYYY-MM-DD HH:mm:ss')
        }
        this.searchForm[name] = e
      },
      // 单个/多个查询切换
      switchFun() {
        this.selected = !this.selected
      }
    },

  }
</script>

<style scoped>
  .search {
    display: flex;
    align-items: center;
  }

  .search .inputInline {
    margin-right: 0.625rem;
  }

  .search .inputInline .el-input {
    width: 10vw;
  }

  .topBottom {
    margin: 0 10px;
    cursor: pointer;
  }

  .topBottom .iconfont {
    display: block;
    font-size: 12px;
  }

  .topBottom .icon-xiangxia1 {
    margin-top: -3px;
  }

  .topBottom .selected {
    color: #409eff;
  }

  .textBlue {
    color: #409eff;
    font-size: 14px;
    margin-left: 10px;
    cursor: pointer;
  }

  .marginTop {
    margin-top: 20px;
  }

  .tablecell {
    border: 1px solid #eee;
  }

  .floatRight {
    float: right;
    margin: 10px;
  }

  .page {
    margin-top: 20px;
  }

  .page .el-pagination {
    margin-bottom: 0;
    float: none;
  }

  .tablecell>>>.BtnOrange {
    border: 1px solid #ffb6b6;
    color: #ff4949;
    background: #ffeded;
  }

  .tablecell>>>.BtnOrange:hover {
    background: #ff4949;
    border-color: #ff4949;
    color: #fff;
  }

  .tablecell>>>.BtnBlue {
    border: 1px solid #a3d3ff;
    color: #1890ff;
    background: #e8f4ff;
  }

  .tablecell>>>.BtnBlue:hover {
    background: #1890ff;
    border-color: #1890ff;
    color: #fff;
  }

  .dialogcontent {
    padding-bottom: 20px;
  }

  .quantity {
    display: inline-block;
  }

  .search .inputInline .w50 {
    width: 1.5rem;
  }

  .w150 {
    margin-bottom: 10px;
    width: 150px;
  }
  .w250{
    width: auto;
  }
</style>
