<template>
  <div id="container">
    <div class="alarmrecord">
      <el-card class="box-card">
        <el-row class="">
          <div class="search">
            <el-form :inline="true" :model="formInline" class="demo-form-inline">
              <el-form-item label="" v-if="userInfo.type==0">
                <!-- <el-select v-model="selectoptionValue" size="mini" placeholder="请选择数据中心" @change="selectTenantId"
                  style="width: 3rem;" >
                  <el-option v-for="item in selectoption" :key="item.value" :label="item.label" :value="item.value">
                  </el-option>
                </el-select> -->
				<selectoption></selectoption>
              </el-form-item>
              <el-form-item label="单位名称:">
                <el-select v-model="formInline.enterpriseId" size="small" clearable class="w200" placeholder="请选择所属单位">
                  <el-option :label="item.name" :value="item.id" v-for="item in enterpriselist" :key="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="建筑物:">
                <el-input v-model="formInline.name" placeholder="请输入建筑物名称" size="small" :clearable="true">
                </el-input>
              </el-form-item>
              <el-form-item>
                <el-button size="mini" @click="reset">重置</el-button>
                <el-button type="primary" size="mini" @click="getlist">查询</el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-row>
        <el-row class="marginTop">
          <div class="tablecell">
            <el-row class="floatRight">
              <!-- <el-button type="primary" :disabled="batch" size="mini">布防</el-button>
            <el-button type="danger" :disabled="batch" size="mini">撤防</el-button>
            <el-button type="default" :disabled="batch" size="mini">布防计划</el-button> -->
              <el-button type="primary" size="mini" @click="exportFun">导出</el-button>
              <el-button type="primary" size="mini" @click="batchProcessing">新增</el-button>
              <el-button type="danger" size="mini" :disabled="batch" @click="deleteAllList">删除</el-button>
            </el-row>
            <el-table ref="multipleTable" :data="tableData" :border="true" tooltip-effect="dark" style="width: 100%"
              :header-cell-style="rowClass" row-key="id" :default-expand-all="true"
              :tree-props="{children: 'children', hasChildren: 'hasChildren'}" :cell-style="{fontSize:'12px'}"
              @selection-change="handleSelectionChange" stripe height="590">
              <el-table-column type="selection" width="55">
              </el-table-column>
              <el-table-column prop="name" label="建筑物名称" width="120">
              </el-table-column>
              <el-table-column prop="enterpriseName" label="所属单位" show-overflow-tooltip>
              </el-table-column>
              <el-table-column prop="address" label="详细地址" show-overflow-tooltip>
              </el-table-column>
              <el-table-column label="快捷操作" width="340">
                <template slot-scope="scope">
                  <el-button type="primary" size="mini" @click="getdevicesstatu(scope.$index, scope.row)">
                    设备</el-button>
                  <el-button type="primary" size="mini" v-if="scope.row.type < 2"
                    @click="addRoom(scope.$index, scope.row)">
                    添加楼栋
                  </el-button>
                  <el-button type="primary" size="mini" v-if="scope.row.type==2"
                    @click="addRoom1(scope.$index, scope.row)">
                    添加房间
                  </el-button>
                  <el-button type="primary" size="mini" @click="modifyRoom(scope.$index, scope.row)">
                    编辑
                  </el-button>
                  <el-button type="danger" size="mini" @click="deleRoom(scope.$index, scope.row)">删除
                  </el-button>
                  <!-- <el-button type="primary" size="mini">布防</el-button>
                <el-button type="danger" size="mini">撤防</el-button> -->
                  <!-- <el-button size="mini" class="BtnOrange" @click="recordFun">未处理报警记录</el-button>
                <el-button size="mini" class="BtnBlue">历史事件记录</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>
        </el-row>
      </el-card>
      <el-dialog title="添加" :visible.sync="dialogVisible2" width="60%" style="overflow: hidden;"
        :before-close="handleClose">
        <Map ref="map" @close="$refs.map.close()" @updateLocation="updateLocation"></Map>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible2 = false">取 消</el-button>
          <el-button type="primary" @click="dialogVisible2 = false">提交</el-button>
        </span>
      </el-dialog>
      <el-dialog :title="addtitle" :visible.sync="dialogVisible3" width="30%" :before-close="handleClose3">
        <el-form ref="form4" :model="formInline3" label-width="120px" :inline="true">
          <el-form-item label="名称" prop="name1">
            <el-input v-model="formInline3.name" placeholder="名称" :clearable="true">
            </el-input>
          </el-form-item>
          <el-form-item label="数量" prop="floorNum">
            <el-input v-model="formInline3.count" placeholder="数量" :clearable="true">
            </el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible3 = false">取 消</el-button>
          <el-button type="primary" @click="addsaveEdit">提交</el-button>
        </span>
      </el-dialog>
      <el-dialog title="添加" :visible.sync="dialogVisible" width="30%" :before-close="handleClose">
        <el-form ref="form" :model="formRoom" label-width="120px" :inline="true" :rules="rules">
          <el-form-item label="房源名称" prop="name">
            <el-input v-model="formRoom.name" class="w200" :clearable="true"></el-input>
          </el-form-item>
          <el-form-item label="详细地址" prop="address">
            <el-input v-model="formRoom.address" class="w200" :clearable="true"></el-input>
          </el-form-item>
          <el-form-item label="楼栋名称" prop="floorNum" v-if="!modifyStatus" class="blockitem">
            <el-tooltip class="item" effect="dark" content="名称以 、间隔。名称填A,会生成A1、A2...,名称为10,会生成101、102..."
              placement="top">
              <el-input v-model="formRoom.name1" placeholder="名称以 、间隔。名称填A栋,以字母A为顺序,如B、C...,名称为10,自增为101、102..."
                :clearable="true">
              </el-input>
            </el-tooltip>
          </el-form-item>
          <el-form-item label="楼层数" prop="floorNum" v-if="!modifyStatus" class="blockitem">
            <el-input v-model="formRoom.floorNum" placeholder="例如:1(楼栋数)、2(房间数)" :clearable="true">
            </el-input>
          </el-form-item>
          <el-form-item label="所属单位" prop="region">
            <el-select v-model="formRoom.region" class="w200" placeholder="请选择所属单位">
              <el-option :label="item.name" :value="item.id" v-for="item in enterpriselist" :key="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer" v-if="modifyStatus">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="updateRoom">修改</el-button>
        </span>
        <span slot="footer" class="dialog-footer" v-else>
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveEdit">提交</el-button>
        </span>
      </el-dialog>
      <el-dialog title="设备列表" :visible.sync="dialogVisible1" width="60%" class="dialogcontent"
        :before-close="handleClose1">
        <div class="tablecell">
          <el-table ref="multipleTable1" :data="deviceList" :border="true" tooltip-effect="dark" style="width: 100%"
            :header-cell-style="rowClass" :cell-style="{fontSize:'12px'}" stripe height="400">
            <el-table-column prop="id" label="序列号" width="80">
            </el-table-column>
            <el-table-column prop="imei" label="IMEI" width="150">
            </el-table-column>
            <el-table-column prop="deviceNum" label="设备名称" width="150">
            </el-table-column>
            <el-table-column prop="isOnline" label="设备状态" show-overflow-tooltip>
              <template slot-scope="scope">
                <span v-if="scope.row.isOnline==0">离线</span>
                <span v-if="scope.row.isOnline==1">在线</span>
              </template>
            </el-table-column>
            <el-table-column prop="roomName" label="安装点位" show-overflow-tooltip>
            </el-table-column>
            <el-table-column prop="accessPlatform" label="类型" show-overflow-tooltip>
              <template slot-scope="scope">
                <span v-if="scope.row.accessPlatform==0">锁平台</span>
                <span v-if="scope.row.accessPlatform==1">电信</span>
                <span v-if="scope.row.accessPlatform==2">移动</span>
                <span v-if="scope.row.accessPlatform==3">联通</span>
              </template>
            </el-table-column>
            <el-table-column prop="lastReportAt" label="最近事件时间" label-width="200px" show-overflow-tooltip>
            </el-table-column>
            <el-table-column prop="enterpriseName" label="所属单位" show-overflow-tooltip>
            </el-table-column>
          </el-table>
        </div>
        <div class="page">
          <el-pagination @size-change="handleSizeChange1" @current-change="handleCurrentChange1"
            :current-page="currentPage1" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
            :total="pageTotal1">
          </el-pagination>
        </div>
      </el-dialog>
    </div>
  </div>
</template>
<script>
  import {
    export_json_to_excel
  } from "../../vendor/Export2Excel.js"
  import {
    httpGet,
    httpPost
  } from "../../api/index";
  import {
    ztreeToElementTree,
    recursion,
    uniqueArray,
    paramsValidate
  } from "../../utils/index"
  import Map from "./common/map.vue"
  import moment from "moment"
  export default {
    // inject: ['reload'],
    name: "alarmRecord",
    data() {
      return {
        // selectoption:[],
        // selectoptionValue:'',
        pageTotal: 0,
        addtitle: "添加楼栋",
        rules: {
          region: [{
            required: true,
            message: '请选择所属单位',
            trigger: 'blur'
          }],
          address: [{
            required: true,
            message: '请输入地址',
            trigger: 'blur'
          }],
          name: [{
            required: true,
            message: '请输入名称',
            trigger: 'blur'
          }],
          floorNum: [{
            required: true,
            message: '请输入楼层',
            trigger: 'blur'
          }],
        },
        dialogVisible2: false,
        titleText: '设备未处理报警记录(IMEI:860709056256857)',
        textarea: '', //批量处理备注
        dialogVisible: false,
        dialogVisible1: false,
        input: '',
        content: '切换单个/多个查询模式',
        selected: true,
        advancedQueryStatus: false,
        advancedQueryText: '高级查询',
        formInline: {
          enterpriseId: '',
          name: ''
        },
        formInline3: {
          count: '',
          name: ''
        },
        tableData: [],
        rowStyle: {
          background: '#f8f9fa',
          fontSize: '12px'
        },
        multipleSelection: [],
        enterpriselist: [],
        formRoom: {
          name: '',
          address: '',
          floorNum: '',
          region: ''
        },
        form1: {
          address: '',
          province: '',
          city: '',
          latitude: 0, // 纬度
          longitude: 0, // 经度
          district: ''
        },
        currentPage: 1,
        currentPage1: 1,
        pageSize: 10,
        pageTotal1: 0,
        batch: true,
        zNodes: [],
        modifyRow: '',
        modifyStatus: false,
        deviceList: [],
        devicerow: '',
        pageSize1: 10,
        dialogVisible3: false,
        addselect: 0,
		userInfo:{type:''}
      }
    },
    components: {
      Map
    },
    computed: {

    },
    created() {
      // this.$store.commit('updateTenantId', 400)
      this.userInfo = JSON.parse(localStorage.getItem('info'))
      this.getEnterprise()
      this.getlist()
      // this.selectoption=JSON.parse(localStorage.getItem('selectoption'))
      // this.selectoptionValue=localStorage.getItem('tenantId')
    },
    methods: {
      // selectTenantId(e) {
      //   localStorage.setItem('tenantId', e)
      //   this.reload()
      // },
      addsaveEdit() {
        var count = this.formInline3.count
        var name = this.formInline3.name
        var data = {
          ancestor: this.addrow.id,
          count: count,
          site: {
            address: this.addrow.address,
            name: name,
            type: 1,
            enterpriseId: this.addrow.enterpriseId,
          }
        }
        if (this.addselect == 0) {
          data = {
            ancestor: this.addrow.id,
            count: count,
            site: {
              address: this.addrow.address,
              name: name,
              type: 1,
              enterpriseId: this.addrow.enterpriseId,
            }
          }
        } else if (this.addselect == 1) {
          data = {
            ancestor: this.addrow.id,
            count: count,
            site: {
              address: this.addrow.address,
              name: name,
              type: 1,
              isRoom: 0,
              enterpriseId: this.addrow.enterpriseId,
            }
          }
        }
        httpPost(data, this.$api.addNodes).then(res => {
          if (res.success) {
            this.dialogVisible3 = false;
            this.getlist();
            this.$message.success("添加成功")
          } else {
            this.$message.error("添加失败")
          }
        }).error(er => {
          this.$message.error("添加失败")
        })
      },
      addRoom(index, row) {
        this.addselect = 0
        this.addrow = row
        this.dialogVisible3 = true
      },
      addRoom1(index, row) {
        this.addselect = 1
        this.addrow = row
        this.dialogVisible3 = true
      },
      exportFun() {
        var data = {
          pageNum: 10,
          pageSize: 0,
          q: JSON.stringify({
            enterpriseId: this.formInline.enterpriseId,
            name: this.formInline.name,
          })
        };
        httpGet(data, this.$api.getSiteList).then((res) => {
          if (res.success) {
            res.data.list.map(li=>{
              this.enterpriselist.find((item,index)=>{
                if(item.id==li.enterpriseId){
                  li['enterpriseName']=item.name
                }
              })
            })
            require.ensure([], () => {
              const tHeader = ['房源ID', '建筑物名称', '所属单位ID', '所属单位名称', '详细地址', '设备IMEI'
              ]
              const filterVal = ['id', 'name', 'enterpriseId', 'enterpriseName', 'address',
                'imei'
              ]
              const data = this.formatJson(filterVal, res.data.list)
              export_json_to_excel(tHeader, data, '房源列表')
            })
          } else {
            this.$message.error("导出失败")
          }
        });
      },
      formatJson(filterVal, jsonData) {
        return jsonData.map(v => filterVal.map(j => v[j]))
      },
      // 批量删除
      deleteAllList() {
        var multipleSelection = this.multipleSelection
        if (multipleSelection.length == 0) {
          this.$message.error("请选择要删除的房源")
        } else {
          var _this = this
          this.$confirm("确定要删除吗？", "提示", {
              type: "warning",
            })
            .then(() => {
              this.currentPage = 1
              var ids = []
              multipleSelection.map(li => {
                ids.push(li.id)
              })
              var data = {
                ids: ids
              }
              httpPost(data, _this.$api.deleteRoom).then(res => {
                if (res.success) {
                  _this.getlist()
                  _this.$message.success("删除成功")
                } else {
                  _this.$message.error("删除失败")
                }
              })
            })
        }
      },
      // 删除建筑
      deleRoom(index, row) {
        var _this = this
        this.$confirm("确定要删除吗？", "提示", {
            type: "warning",
          })
          .then(() => {
            var data = {
              ids: [row.id]
            }
            httpPost(data, _this.$api.deleteRoom).then(res => {
              if (res.success) {
                _this.getlist()
                _this.$message.success("删除成功")
              } else {
                _this.$message.error("删除失败")
              }
            })
          })
      },
      // 获取对应设备
      getdevicesstatu(index, row) {
        this.dialogVisible1 = true
        this.devicerow = row
        this.getDevice()
      },
      getDevice() {
        var data = {
          q: JSON.stringify({
            roomId: this.devicerow.id
          }),
          pageSize: this.pageSize1,
          pageNum: this.currentPage1
        }
        httpPost(data, this.$api.getList).then(res => {
          if (res.success) {
            res.data.list.map(li => {
              if (li.lastReportAt) {
                li.lastReportAt = moment(li.lastReportAt).format('YYYY/MM/DD HH:mm:ss')
              }
            })
            this.deviceList = res.data.list
            this.pageTotal1 = res.data.total
          } else {
            this.$message.console.error("查询失败");
          }
        })
      },
      reset() {
        var formInline = {
          enterpriseId: '',
          name: ''
        }
        this.formInline = formInline
      },
      // 修改房源
      modifyRoom(index, row) {
        var formRoom = {
          name: row.name,
          address: row.address,
          region: row.enterpriseId
        }
        this.formRoom = formRoom
        this.modifyRow = row
        this.dialogVisible = true
        this.modifyStatus = true
      },
      updateRoom() {
        var info = localStorage.getItem("info");
        var formRoom = this.formRoom
        var data = {
          list: [{
            id: this.modifyRow.id,
            address: formRoom.address,
            name: formRoom.name
          }]
        };
        if (formRoom.name == "") {
          this.$message.error("建筑名称不能为空");
        } else {
          httpPost(data, this.$api.updatePlace).then((res) => {
            if (res.success) {
              this.$message.success("修改成功")
              this.dialogVisible = false;
              this.getlist();
            } else {
              this.$message.error("修改失败")
            }
          });
        }
      },
      // 保存房源
      saveEdit() {
        var info = localStorage.getItem("info");
        var formRoom = this.formRoom
        if (formRoom.name == "") {
          this.$message.error("建筑名称不能为空");
        } else {
          var names = this.formRoom.name1.split('、')
          var counts = this.formRoom.floorNum.split('、')
          var data = {
            address: formRoom.address,
            counts: counts,
            enterpriseId: formRoom.region,
            names: names,
            rootName: formRoom.name
          }
          httpPost(data, this.$api.createModPlace).then((res) => {
            if (res.success) {
              this.dialogVisible = false;
              this.getlist();
              this.$message.success("创建成功")
            } else {
              this.$message.error("创建失败");
            }
          })
        }
      },
      yz(obj) {
        var str = {}
        Object.keys(obj).forEach(function(key) {
          if (obj[key] != '') {
            str[key] = obj[key]
          }
        })
        return str
      },
      // 获取列表
      getlist() {
        var q = this.yz(this.formInline)
        var data = {
          pageNum: 1,
          pageSize: this.pageSize,
          orderBy: "create_time desc",
          q: JSON.stringify(q)
        };
        httpGet(data, this.$api.getSiteList).then((res) => {
          if (res.data.list.length > 0) {
            res.data.list.map(li=>{
              this.enterpriselist.find((item,index)=>{
                if(item.id==li.enterpriseId){
                  li['enterpriseName']=item.name
                }
              })
            })
            var arrdata = uniqueArray(res.data.list, "id")
            this.tableData = ztreeToElementTree(arrdata, {});
            // this.tableData=res.data.list
            this.pageTotal = res.data.total
          } else {
            this.tableData = []
            this.pageTotal = 0
          }
        });
      },
      getlist1() {
        var q = this.yz(this.formInline)
        var data = {
          pageNum: this.currentPage,
          pageSize: this.pageSize,
          orderBy: "create_time desc",
          q: JSON.stringify(q)
        };
        httpGet(data, this.$api.getSiteList).then((res) => {
          if (res.data.list.length > 0) {
            res.data.list.map(li=>{
              this.enterpriselist.find((item,index)=>{
                if(item.id==li.enterpriseId){
                  li['enterpriseName']=item.name
                }
              })
            })
            var arrdata = uniqueArray(res.data.list, "id")
            this.tableData = ztreeToElementTree(arrdata, {});
            // this.tableData=res.data.list
            this.pageTotal = res.data.total
          } else {
            this.tableData = []
            this.pageTotal = 0
          }
        });
      },
      openMap() {
        if (this.form.longitude == 'undefined' && this.form.latitude == 'undefined') {
          this.$refs.map.open()
        } else {
          this.$refs.map.open(this.form1)
        }
      },
      updateLocation(orgAddr, lon, lat, province, city, district) {
        this.form1 = {
          address: orgAddr,
          province: province,
          city: city,
          latitude: lat, // 纬度
          longitude: lon, // 经度
          district: district
        }
      },
      // 获取单位
      getEnterprise() {
        var data = {
          q: JSON.stringify({
            name: this.formInline.name
          })
        }
        httpGet(data, this.$api.getEnterprise).then((res) => {
          if (res.success) {
            this.enterpriselist = res.data.list
            this.zNodes = []
            this.zNodes = ztreeToElementTree(res.data.list, {});
          } else {
            this.$message.error("获取失败")
          }
        });
      },
      // 未处理记录打开
      recordFun() {
        this.dialogVisible1 = true
      },
      // 未处理记录处理关闭
      handleClose1(done) {
        done();
      },
      handleClose3(done) {
        this.dialogVisible3 = false
      },
      // 批量处理关闭
      handleClose(done) {
        done();
        this.modifyStatus = false
      },
      // 批量处理
      batchProcessing() {
        this.dialogVisible = true
        this.formRoom = {
          name: '',
          address: '',
          floorNum: '',
          region: ''
        }
        this.modifyStatus = false
      },
      // 分页
      handleSizeChange(val) {
        this.pageSize = val
        this.getlist1()
        console.log(`每页 ${val} 条`);
      },
      handleCurrentChange(val) {
        this.currentPage = val
        this.getlist1()
        console.log(`当前页: ${val}`);
      },
      // 分页
      handleSizeChange1(val) {
        this.pageSize1 = val
        this.getDevice()
        console.log(`每页 ${val} 条`);
      },
      handleCurrentChange1(val) {
        this.currentPage1 = val
        this.getDevice()
        console.log(`当前页: ${val}`);
      },
      // 表头样式
      rowClass({
        row,
        rowIndex
      }) {
        return "background:#f8f9fa;color:#333;font-blod:none;font-size:12px;"
      },
      // 表格勾选
      handleSelectionChange(val) {
        this.multipleSelection = 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) {
        console.log(e)
      },
      // 单个/多个查询切换
      switchFun() {
        this.selected = !this.selected
      }
    },
    mounted() {

    }
  }
</script>

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

  .search .inputInline {
    display: inline-block;
  }

  .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;
  }

  .curpoiner {
    cursor: pointer;
    display: flex;
    align-items: center;
    color: #508dfe;
  }

  .curpoiner .icon-erweima {
    font-size: 24px;
  }

  .curpoiner .operation {
    margin-left: 6px;
  }

  .search .el-form-item {
    margin-bottom: 0;
  }

  .tablecell>>>.el-table__expand-icon {
    display: inline-block;
  }

  .blockitem {
    width: 100%;
  }

  .blockitem>>>.el-form-item__content {
    width: calc(95% - 120px);
  }
</style>
