<template>
  <div class="app-container">
    <div class="filter-container" style="padding-bottom:0px">
      <div class="search-box-area" id="searchBox">
        <!-- <div class="search-item">
          <el-cascader
            class="filter-item form-search-input fl"
            v-model="queryParam.department_id"
            :options="departments"
            clearable
            :props="{
              checkStrictly: true,
              label: 'department_name',
              value: 'id',
            }"
            @change="handleChange"
          ></el-cascader>
        </div> -->
        <div class="search-item">
          <el-input
            v-model="queryParam.name"
            placeholder="基站名称"
            clearable
            class="filter-item form-search-input fl"
            @keyup.enter.native="handleSearch"
          />
        </div>
        <!-- <div class="search-item">
          <el-input
            v-model="queryParam.mac"
            placeholder="基站Mac"
            clearable
            class="filter-item form-search-input fl"
            @keyup.enter.native="handleSearch"
          />
        </div> -->
        <div class="search-item">
          <el-input
            v-model="queryParam.shortcode"
            placeholder="设备编码"
            clearable
            style="width:180px"
            class="filter-item form-search-input fl"
            @keyup.enter.native="handleSearch"
          />
        </div>
      </div>
      <div class="search-operate-area">
        <!-- <el-input v-model="queryParam.code" placeholder="唯一编码" clearable class="filter-item form-search-input fl" /> -->
        <el-button class="filter-item search fl" icon="el-icon-search" @click="handleSearch">搜索</el-button>
        <el-button class="filter-item fl" icon="el-icon-refresh" @click="handleRefresh">重置</el-button>
        <!-- <el-button
          class="filter-item search fl"
          :icon="this.searchDisplay?'el-icon-arrow-up':'el-icon-arrow-down'"
          @click="searchDis"
        >{{word}}</el-button> -->
      </div>
      <div class="list-operate-area">
        <!-- 动态隐藏显示列 -->
       
          <el-popover
            placement="bottom"
            min-width="80"
            trigger="click"
            popper-class="col-setting-popover"
          >
            <el-button
              slot="reference"
              icon="el-icon-setting"
              class="filter-item search fl"
            >列设置</el-button>
            <!-- <div class="col-setting-title">选择表列</div> -->
            <el-checkbox-group v-model="visibleIndexs" :min="1" class="col-setting-group">
              <el-checkbox
                v-for="colInfo in columnInfos"
                :label="colInfo.index"
                :key="colInfo.index"
                :disabled="colInfo.disabled"
                v-show="!colInfo.disabled || showAlwaysShowColumnInCheckbox"
              >{{ colInfo.label }}</el-checkbox>
            </el-checkbox-group>
          </el-popover>
       
         <el-button
          class="filter-item search fl"
          icon="el-icon-refresh-right"
          style="margin-left:10px"
          @click="refresh"
          >刷新</el-button
        >
      </div>
    </div>
    <el-table
      :data="data"
      v-loading="loading"
      ref="multipleTable"
      :columnVisibles="columnVisibles"
      @selection-change="handleSelectMulti"
      :showAlwaysShowColumnInCheckbox="true"
      :dynamicColumnSetting="true"
      @sort-change="sortChange"
      tooltip-effect="dark"
      style="width: 100%"
      border
      fit
    >
      <el-table-column type="selection" v-if="columnVisibles[0]" fixed="left" width="55"></el-table-column>

      <el-table-column
        prop="DEVICE_CODE"
        label="设备编码"
        align="center"
        v-if="columnVisibles[1]"
        :show-overflow-tooltip="true"
        width="120"
      />
      <el-table-column
        prop="DEVICE_NAME"
        label="基站名称"
        align="center"
        v-if="columnVisibles[2]"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        prop="OWNER_CODE"
        label="所属编码"
        align="center"
        v-if="columnVisibles[3]"
        :show-overflow-tooltip="true"
        width="200"
        sortable="custom"
      />
      <!-- <el-table-column
        prop="IS_ONLINE_TEXT"
        label="在线状态"
        align="center"
        v-if="columnVisibles[4]"
        :show-overflow-tooltip="true"

      /> -->
      <el-table-column
        prop="IS_ONLINE"
        label="在线状态"
        align="center"
        v-if="columnVisibles[4]"
        :show-overflow-tooltip="true"
        width="120"
      >
        <template slot-scope="record">
          <el-tag type="danger" v-if="record.row.IS_ONLINE == 0">离线</el-tag>
          <el-tag type="success" v-else-if="record.row.IS_ONLINE == 1">在线</el-tag>
        </template>
      </el-table-column>

       
      <el-table-column
        prop="UPDATE_DATE"
        label="修改时间"
        align="center"
        v-if="columnVisibles[5]"
        :show-overflow-tooltip="true"

      />
      <el-table-column
        prop="DEVICE_IP"
        label="设备IP"
        align="center"
        v-if="columnVisibles[6]"
        :show-overflow-tooltip="true"

      />
      <el-table-column
        prop="DEVICE_PORT"
        label="设备端口"
        align="center"
        v-if="columnVisibles[7]"
        :show-overflow-tooltip="true"

      />
      <el-table-column
        prop="LOGIN_NAME"
        label="登录名称"
        align="center"
        v-if="columnVisibles[8]"
        :show-overflow-tooltip="true"

      />
       <el-table-column
        prop="longitude"
        label="经度"
        align="center"
        v-if="columnVisibles[9]"
        :show-overflow-tooltip="true"
      />
       <el-table-column
        prop="latitude"
        label="纬度"
        align="center"
        v-if="columnVisibles[10]"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="操作"
       width="120"
        v-if="columnVisibles[11]"
        align="center"
        fixed="right"
      >
        <template slot-scope="record">
          <el-button type="info" icon="el-icon-view" @click="showDeviceList(record.row)"></el-button>
          <!-- <el-button type="primary" icon="el-icon-edit" @click="handleUpdate(record.row)"></el-button> -->
          <!-- <el-button type="danger" icon="el-icon-delete" @click="handleDelete(record.row.id)"></el-button> -->
        </template>
      </el-table-column>
    </el-table>
    <el-button
      type="primary"
      icon="el-icon-plus"
      v-action="'Station@save'"
      :loading="downloadLoading"
      style="margin-top: 15px"
      @click="handleCreate"
      >添加</el-button
    >
    <el-button
      type="warning"
      icon="el-icon-download"
      v-action="'Station@export_station'"
      :loading="downloadLoading"
      style="margin-top: 15px"
      @click="exportExcel"
      >导出</el-button
    >
    <el-button
      type="success"
      icon="el-icon-upload"
      v-action="'Station@import_station'"
      :loading="downloadLoading"
      style="margin-top: 15px"
      @click="importExcel"
      >导入</el-button
    >
    <el-button
      type="danger"
      icon="el-icon-delete"
      v-if="selectedIds.length>0"
      style="margin-top:15px"
      v-action="'Station@delete'"
      @click="handleMultiDelete()"
    >删除</el-button>
    <el-pagination
      background
      class="pagination-container"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="paginate.current"
      
      :page-sizes="paginate.sizes"
      :page-size="paginate.limit"
      :layout="paginate.layout"
      :total="paginate.total"
    />
    <!--------------------------------- 新增 修改弹框------------------------------------------------------->
    <!-- 上传弹窗 -->
    <el-dialog
      title="导入基站"
      append-to-body
      width="400px"
      :visible.sync="uploadDialogVisible"
      custom-class="upload-dialog"
    >
      <el-cascader
        v-model="selectedDepartId"
        class="filter-item form-search-input fl"
        :options="departments"
        :props="{ checkStrictly: true, label: 'department_name', value: 'id' }"
        style="margin-bottom: 10px"
        placeholder="所属部门"
        @change="changeDepart"
      ></el-cascader>
      <el-select v-model="selectedModelId" placeholder="设备型号" @change="changeModel" style="margin-bottom: 10px">
        <el-option
          v-for="item in models"
          :key="item.value"
          :label="item.text"
          :value="item.value">
        </el-option>
      </el-select>
      <el-upload
        class="upload-demo"
        drag
        :action="actionUrl"
        :headers="headers"
        :before-upload="beforeUpload"
        :show-file-list="true"
        :on-change="onchange"
        :on-remove="onremove"
        :on-exceed="onexeced"
        :limit="1"
        ref="upload"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip upload-tips" slot="tip">
          只能上传xls/xlsx文件
        </div>
      </el-upload>
      <el-link
        type="primary"
        href="https://rlfd.oss-cn-hangzhou.aliyuncs.com/catch_fd/excel_temp/fd_stations.xls"
        style="margin-top: 10px"
        >下载模板</el-link
      >
      <span slot="footer" class="dialog-footer">
        <el-button @click="uploadDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="importStations" :loading="loadings">{{
          submitText
        }}</el-button>
      </span>
    </el-dialog>
    <form-model
      @sendVal="closeDialog"
      :formModelVisible="formVisible"
      :title="title"
      :ref="formName"
      :location="location"
    />
    <!-- <heartLogTable
      :displayVisible="tableFormVisible"
      @formCancel="heartTableCancle"
      :currentRecord="currentRecord"
      ref="heartLog"
    /> -->
    <deviceList
      :displayVisible="deviceDialogVisible"
      @formCancel="deviceCancle"
      :station_code="station_code"
      ref="deviceList"
    />
    <bmap-model @sendVal="closeBmapDialog" :bmapModelVisible="bmapVisible" />
  </div>
</template>

<script>
import rlListOperate from "@/layout/rl-list-operate/rlListOperate";
import formModel from "./formModel";
import { getToken } from "../../../utils/auth";
import { action } from "@/directive/permission/index.js";
// import heartLogTable from "./heartLogTable";
import deviceList from "./deviceList";
import bmapModel from "./bmapModel.vue";
export default {
  name: "station",
  mixins: [rlListOperate],
  directives: { action },
  components: {
    formModel,
    bmapModel,
    // heartLogTable
    deviceList
  },
  data() {
    return {
      url: "station",
      queryParam: {
        department_id: "",
        mac: "",
        shortcode: "",
        name:''
      },
      exportUrl: "station/export_station", //导出url
      bmapVisible: false,
      location: "",
      formName: "station",
      formVisible: false,
      configFormVisible: false,
      // tableFormVisible: false,
       //导入请求url
      loadings: false,
      submitText: "确 定",
      uploadDialogVisible:false,
      actionUrl: process.env.VUE_APP_BASE_API + "/upload/file_excel",
      headers: { authorization: "Bearer " + getToken() },
      excel_url: "", //上传Excel返回的url
      selectedDepartId: "",
      selectedModelId:"",

      departments:[],
      models:[],
      currentRecord: {},
      tableVisible: false,

      searchDisplay: true,
      station_code:'',
      deviceDialogVisible:false,
      columnVisibles: new Array(12).fill(true), //初始为全true,并在每个列标签中使用v-if引用对应列下标的值。列下标从0开始。
      columnInfos: [], // 所有列的信息
      hidenColumnIndexs: [], //初始隐藏的列的下标。列下标从 0 开始
      visibleIndexs: [], // 可见列的下标集合
      showAlwaysShowColumnInCheckbox: true, //设置是否在checkbox显示不允许隐藏的列信息
      alwaysShowColumnIndexs: [0] // 总是显示的列的下标（不可隐藏的列）。列下标从 0 开始
    };
  },
  created() {
    this.$http.get("departments").then((response) => {
      this.departments = response.data;
    });
    this.$http.post('sysDictData/getOptions', {type: "StationModel"})
                .then( resp => {
                  this.models = resp.data
     })
  },
  methods: {
    showDeviceList(row) {
      this.deviceDialogVisible = true;
      this.station_code = row.LOGIN_NAME;
      // this.authorize = row.authorize;
    },
    deviceCancle() {
      this.deviceDialogVisible = false;
    },
    changeDepart(v) {
      this.selectedDepartId = v[v.length - 1];
    },
    changeModel(v){
      this.selectedModelId = v;
    },
    importExcel() {
      this.uploadDialogVisible = true;
    },
    handleChange(val) {
      this.queryParam.department_id = val;
      this.handleSearch();
    },
    handleUpdateConfig(record) {
      this.currentRecord = record;
      this.configFormVisible = true;
    },
    beforeUpload(file) {
      if (!/\.(xlsx|xls|XLSX|XLS)$/.test(file.name)) {
        this.$notify.error({
          title: "错误",
          message: "上传文件只能为excel文件，且为xlsx,xls格式",
        });
        return false;
      }
      return true;
    },
    onremove() {
      //移除文件钩子
      this.excel_url = "";
    },
    onexeced(files) {
      if (files.length == 1) {
        this.$message.error("只能上传一个文件");
      }
    },
    onchange(file, fileList) {
      if (file.response) {
        this.$message.success(file.response.data.msg);
        this.excel_url = file.response.data.excel_url;
      } else {
        // console.log(file);
      }
    },
    importStations() {
      // console.log(this.excel_url);
      var url = this.excel_url,depart_id = this.selectedDepartId,model_id = this.selectedModelId;
      if (depart_id == "") {
        this.$message.error("请选择部门");
        return;
      }
      if (model_id == "") {
        this.$message.error("请选择型号");
        return;
      }
      if (url == "") {
        this.$message.error("请上传文件");
        return;
      }
      this.loadings = true;
      this.submitText = "导入中";
      this.$http
        .post("import_station", { url: url, depart_id: depart_id,model_id:model_id })
        .then((response) => {
          if (response.data.error) {
            this.$message.error(response.data.msg);
          } else {
            this.$message.success(response.data);
          }
          this.excel_url = "";
          this.selectedDepartId = "";
          this.$refs.upload.clearFiles();
          this.loadings = false;
          this.submitText = "确定";
          this.uploadDialogVisible = false;
          this.getList();
        });
    },
    refresh() {
      this.queryParam.page = this.paginate.current;
      this.getList();
    },
    // 处理初始隐藏的列
    oprColumns(indexs, isShow) {
      let self = this;
      indexs.forEach(index => {
        self.$set(self.columnVisibles, index, isShow);
      });
    },
    searchDis() {
      this.searchDisplay = !this.searchDisplay;
      var searchBoxHeght = document.getElementById("searchBox");
      if (this.searchDisplay == false) {
        searchBoxHeght.style.height = 40 + "px";
      } else {
        searchBoxHeght.style.height = "auto";
      }
    }
  },
  watch: {
    visibleIndexs(newValue, oldValue) {
      let self = this;
      var willHideIndexs = [],
        willShowIndexs = [];

      willShowIndexs = newValue.filter(index => {
        return oldValue.indexOf(index) === -1;
      });

      willHideIndexs = oldValue.filter(index => {
        return newValue.indexOf(index) === -1;
      });

      self.oprColumns(willShowIndexs, true);
      self.oprColumns(willHideIndexs, false);
    }
  },
  computed: {
    word: function () {
      if (this.searchDisplay == false) {
        //对文字进行处理
        return "展开";
      } else {
        return "收起";
      }
    },
  },
  mounted() {
    let self = this;
    if (self.$refs.multipleTable.$slots.default) {
      self.$refs.multipleTable.$slots.default.forEach((columnIns, index) => {
        if (columnIns.componentOptions === undefined) {
          return;
        }
        let props = columnIns.componentOptions.propsData;
        if (
          props.label === undefined &&
          props.type !== "selection" &&
          props.type !== "index"
        ) {
          return;
        }
        // 保存所有列的信息
        let label =
            props.type === "selection"
              ? "多选框"
              : props.type === "index"
              ? "索引"
              : props.label,
          // 默认多选框和索引不可隐藏
          disabled =
            props.type === "selection" || props.type === "index" ? true : false;
        self.columnInfos.push({
          label: label,
          index: index,
          disabled: disabled
        });
        // console.log(this.columnInfos)
        // 记录初始展示的列的下标
        if (self.hidenColumnIndexs.indexOf(index) === -1) {
          self.visibleIndexs.push(index);
        }
      });
      // 处理总是显示的列（不可隐藏的列）
      self.alwaysShowColumnIndexs.forEach(
        index => (self.columnInfos[index].disabled = true)
      );
      // 处理初始隐藏的列
      self.oprColumns(self.hidenColumnIndexs, false);
    }
  }
};
</script>
<style lang="scss" scoped>
.col-setting-popover {
  min-width: 100px;
  padding: 9px 16px;
  .col-setting-title {
    color: #7f8b93;
    font-size: 12px;
  }
  .col-setting-group {
    .el-checkbox {
      display: block;
      margin-top: 5px;
    }
  }
}
.search-box-area {
  width: 70%;
  height: 44px;
  float: left;
}
.search-operate-area {
  width: 20%;
  height: 44px;
  float: left;
}
.search-item {
  width: 25%;
  height: 44px;
  float: left;
}
#searchBox {
  overflow: hidden;
}
</style>
