<template>
  <basic-container>
    <avue-crud :option="option" :table-loading="loading" :data="data" :page.sync="page" ref="crud" v-model="form"
      :before-open="beforeOpen" @search-change="searchChange" @search-reset="searchReset"
      @selection-change="selectionChange" @current-change="currentChange" @size-change="sizeChange"
      @refresh-change="refreshChange" @on-load="onLoad">
      <template slot="menuLeft">
        <el-button type="danger" size="small" icon="el-icon-turn-off" @click="doSetupAlarm" plain>布防
        </el-button>
        <el-button type="danger" size="small" icon="el-icon-turn-off" @click="doCloseAlarm" plain>撤防
        </el-button>
        <el-button type="warning" size="small" icon="el-icon-turn-off" @click="doBypass" plain>旁路
        </el-button>
        <el-button type="warning" size="small" icon="el-icon-turn-off" @click="doUnBypass" plain>旁路恢复
        </el-button>
      </template>
    </avue-crud>
  </basic-container>
</template>

<script>
import { bizLogin, bizDeviceList, bizDeviceStatus, bizNodeType, warnClear, setupAlarm, closeAlarm, bypass, unBypass } from "@/api/wirelessintrusion/wirelessintrusion";

export default {
  data() {
    return {
      form: {},
      query: {},
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: {
        height: 'auto',
        calcHeight: 30,
        dialogWidth: 950,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: true,
        viewBtn: true,
        editBtn: false,
        delBtn: false,
        addBtn: false,
        menu: true,
        menuWidth: 100,
        selection: true,
        dialogClickModal: false,
        column: [
          {
            label: "设备名称",
            prop: "name1",
            span: 12,
            formatter: (val, value, label) => {
              return val.name
            },
            labelWidth: 120,
            viewDisplay: false,
          },
          {
            label: "备注",
            prop: "remark1",
            span: 12,
            formatter: (val, value, label) => {
              return val.remark
            },
            labelWidth: 120,
            viewDisplay: false,
          },
          {
            label: "设备名称",
            prop: "name",
            search: true,
            labelWidth: 120,
            hide: true
          },
          {
            label: "备注名称",
            prop: "remark",
            span: 12,
            hide: true,
            labelWidth: 120,
            overHidde: true
          },
          {
            label: "设备所属产品",
            prop: "productName",
            span: 12,
            labelWidth: 120
          },
          {
            label: "节点类型",
            type: "select",
            dicData: [],
            props: {
              label: "dictLabel",
              value: "dictValue"
            },
            search: true,
            prop: "node",
            labelWidth: 120,
            viewDisplay: false
          },
          {
            label: "位置",
            prop: "position",
            span: 12,
            labelWidth: 120,
            minWidth: 200
          },
          {
            label: "经纬度",
            prop: "xy",
            span: 12,
            labelWidth: 120,
            hide: true
          },
          {
            label: "节点类型",
            prop: "nodeLabel",
            span: 12,
            labelWidth: 120,
            hide: true
          },
          {
            label: "网关信息",
            prop: "gateway",
            span: 12,
            formatter: (val, value, label) => {
              return val.gateway || '-'
            },
            labelWidth: 120
          },
          {
            label: "设备状态",
            type: "select",
            span: 12,
            dicData: [],
            props: {
              label: "dictLabel",
              value: "dictValue"
            },
            search: true,
            prop: "status",
            labelWidth: 120,
            viewDisplay: false,
          },
          {
            label: "创建时间",
            prop: "createTime",
            span: 12,
            labelWidth: 120,
            hide: true,
          }, 
          // {
          //   label: "最后上线时间",
          //   span: 24,
          //   prop: "lastOnline",
          //   labelWidth: 120
          // },
        ]
      },
      data: [],
      nodeType: [],//节点类型
    };
  },
  computed: {
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        let tags = JSON.parse(ele.tags)
        ids.push(tags.sectorNo);
      });
      return ids.join(",");
    }
  },
  mounted() {
    this.loadDict();
  },
  methods: {
    //字典加载
    loadDict() {
      let token = window.sessionStorage.getItem('bizToken');
      if (token == 'undefined' || !token) {
        bizLogin({ appKey: 'Arf7bd4f26', appSecret: 'kb207044c8' }).then(res => {
          window.sessionStorage.setItem('bizToken', res.data.data.token);
          bizDeviceStatus(res.data.data.token).then(res => {
            const column = this.findObject(this.option.column, "status");
            column.dicData = res.data.data;
          })
          bizNodeType(res.data.data.token).then(res => {
            const column = this.findObject(this.option.column, "node");
            column.dicData = res.data.data;
          })
        })
      } else {
        bizDeviceStatus(token).then(res => {
          if (res.data.code == 401) {
            window.sessionStorage.removeItem('bizToken');
            this.loadDict();
          }
          else if (res.data.code == 200) {
            const column = this.findObject(this.option.column, "status");
            column.dicData = res.data.data;
          }
        })
        bizNodeType(token).then(res => {
          const column = this.findObject(this.option.column, "node");
          column.dicData = res.data.data;
        })
      }
    },
    //布防
    doSetupAlarm() {
      if (this.selectionList.length !== 1) {
        this.$message.warning("只能选择一条数据");
        return;
      }
      this.$confirm("确定对该防区布防吗?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return setupAlarm({ num: this.ids });
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.$refs.crud.toggleSelection();
        });
    },
    //撤防
    doCloseAlarm() {
      if (this.selectionList.length !== 1) {
        this.$message.warning("只能选择一条数据");
        return;
      }
      this.$confirm("确定对该防区撤防吗?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return closeAlarm({ num: this.ids });
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.$refs.crud.toggleSelection();
        });
    },
    //旁路
    doBypass() {
      if (this.selectionList.length !== 1) {
        this.$message.warning("只能选择一条数据");
        return;
      }
      this.$confirm("确定对该防区进行旁路吗?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return bypass({ num: this.ids });
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.$refs.crud.toggleSelection();
        });
    },
    //旁路恢复
    doUnBypass() {
      if (this.selectionList.length !== 1) {
        this.$message.warning("只能选择一条数据");
        return;
      }
      this.$confirm("确定对该防区进行旁路恢复吗?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return unBypass({ num: this.ids });
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.$refs.crud.toggleSelection();
        });
    },
    //节点类型转换
    renderLabel(node, col) {
      const column = this.findObject(this.option.column, col);
      let idx = column.dicData.findIndex(item => item.dictValue == node);
      return idx > -1 ? column.dicData[idx].dictLabel : '';
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    beforeOpen(done, type) {
      console.log(this.form)
      if (["edit", "view"].includes(type)) {
        // let token = window.sessionStorage.getItem('bizToken');
        // if (token == 'undefined') {
        //   bizDeviceDetail(this.form.id).then(res => {
        //     this.form = res.data.data;
        //   });
        // }
      }
      done();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      let values = {
        ...params,
        ...this.query,
        pid: 100
      };
      let token = window.sessionStorage.getItem('bizToken');
      if (token == 'undefined' || !token) {
        bizLogin({ appKey: 'Arf7bd4f26', appSecret: 'kb207044c8' }).then(res => {
          window.sessionStorage.setItem('bizToken', res.data.data.token);
          this.loading = true;
          bizDeviceList(res.data.data.token, { ...values, pageSize: page.pageSize, pageNum: page.currentPage }).then(res2 => {
            const data = res2.data;
            this.page.total = data.total;
            data.rows.map(item => {
              item.node = item.bizProduct.node;
              item.nodeLabel = this.renderLabel(item.node, 'node');
              item.statusLabel = this.renderLabel(item.status, 'status')
              item.productName = item.bizProduct.name;
              if (item.tags) {
                let tags = JSON.parse(item.tags);
                item.buildingNo = tags.buildingNo;
                item.floorNo = tags.floorNo;
                // console.log('tags ====>',tags)
                item.xy = tags.coordinate.replace('-',',');
                item.position = tags.buildingNo + '号楼' + tags.floorNo + '层' + tags.address;
              }
            })
            this.data = data.rows;
            console.log('data ====>',data)
            this.loading = false;
          }, () => {
            this.loading = false;
            this.selectionClear();
          });
        })
      } else {
        this.loading = true;
        bizDeviceList(token, { ...values, pageSize: page.pageSize, pageNum: page.currentPage, pid: 100 }).then(res2 => {
          this.loading = false;
          this.selectionClear();
          if (res2.data.code == 401) {
            console.log(res2.data.code)
            window.sessionStorage.removeItem('bizToken');
            this.onLoad(page);
          }
          else if (res2.data.code == 200) {
            const data = res2.data;
            this.page.total = data.total;
            data.rows.map(item => {
              item.node = item.bizProduct.node;
              item.nodeLabel = this.renderLabel(item.node, 'node');
              item.statusLabel = this.renderLabel(item.status, 'status')
              item.productName = item.bizProduct.name;
              if (item.tags) {
                let tags = JSON.parse(item.tags);
                item.buildingNo = tags.buildingNo;
                item.floorNo = tags.floorNo;
                // item.xy = tags.lng + ',' + tags.lat;
                 item.xy = tags.coordinate.replace('-',',');
                item.position = tags.buildingNo + '号楼' + tags.floorNo + '层' + tags.address;
              }
            })
            this.data = data.rows;
            console.log('data ====>',this.data)

          }
        }, () => {
          this.loading = false;
          this.selectionClear();
        });
      }
    }
  }
};
</script>

<style></style>
