<template>
  <div>
    <div class="search" style="margin-bottom:10px;">
      <div>
        <el-input
          placeholder="输入设备名称或设备本地编码进行查询"
          style="width:300px;float:left;margin-right:10px;"
          v-model="search.filter"
          clearable
        ></el-input>
        <el-button @click="filterBox" plain>查 找</el-button>
      </div>
      <div style="margin-top:10px;">
        <span>所属楼层</span>
        <el-cascader
          @change="filterBox"
          v-model="search.floor"
          :options="optionsWithDisabled"
        ></el-cascader>
        <el-checkbox
          style="margin-left:20px;"
          @change="filterBox"
          :checked="search.checkbox"
          label="只显示在当前业务空间中的设备"
        ></el-checkbox>
      </div>
    </div>
    <el-table
      ref="multipleTable"
      :data="tableData"
      v-loading="isLoading"
      tooltip-effect="dark"
      class="data-table border"
      height="300"
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column width="180" label="设备名称">
        <template slot-scope="scope">
          <span>
            <el-tooltip
              :content="scope.row.infos.EquipLocalName ||scope.row.infos.EquipName"
              placement="top"
            >
              <span>{{scope.row.infos.EquipLocalName || scope.row.infos.EquipName | cutString(15)}}</span>
            </el-tooltip>
          </span>
        </template>
      </el-table-column>
      <el-table-column width="180" label="设备本地编码">
        <template slot-scope="scope">
          <span>
            <el-tooltip :content="scope.row.infos.EquipLocalID || '--'" placement="top">
              <span>{{scope.row.infos.EquipLocalID || "--" | cutString(15)}}</span>
            </el-tooltip>
          </span>
        </template>
      </el-table-column>
      <el-table-column width="160" label="设备类">
        <template slot-scope="scope">
          <span>
            <span>{{getName(scope.row.category)}}</span>
          </span>
        </template>
      </el-table-column>
      <el-table-column width="160" label="已关联其他业务空间">
        <template slot-scope="scope">
          <span>
            <el-tooltip :content="changeArray(scope.row.spaceName)" placement="top">
              <span>{{changeArray(scope.row.spaceName) | cutString(6)}}</span>
            </el-tooltip>
          </span>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button plain @click="lockDetails(scope.row)">设备详情</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog width="40%" title="设备详情" :visible.sync="innerVisible" append-to-body>
      <iframe height="400px" width="100%" :src="iframeSrc"></iframe>
    </el-dialog>
    <div class="right" v-if="tableData.length">
        <my-pagination :page="page" @change="pageChange"></my-pagination>
    </div>
    <div class="el-dialog__footer">
        <span class="dialog-footer">
            <el-button@click="clearBox">取 消</el-button>
            <el-button type="primary" @click="addReal">确 定</el-button>
        </span>
    </div>
  </div>
</template>

<script>
import {
  getSpaceEquip,
  searchCode,
  getEqCode,
  getSpaceFloor,
  createRelation,
  getGraphyId,
  getEquipSearch,
  getListForBuss
} from "@/api/scan/request";
import myPagination from "@/components/common/myPagination.vue";
import tools from "@/utils/scan/tools";
import {
    mapGetters,
    mapActions
} from "vuex";
export default {
  name: "equip-table",
  components: {
    myPagination
  },
  computed: {
        ...mapGetters("layout", [
            "projectId",
            "secret",
            "userId"
        ])
    },
  data() {
    return {
      search: {
        filter: "",
        checkbox: false,
        floor: [],
        leiArr: []
      },
      innerVisible: false,
      iframeSrc: "",
      page: {
        size: 50,
        sizes: [10, 30, 50, 100, 150, 200],
        total: 400,
        currentPage: 1
      },
      optionsWithDisabled: [],
      tableData: [],
      allData: [], //全部的数据
      multipleSelection: [],
      list: {},
      build: {},
      graphyId: "",
      isLoading: false,
      activeTabType: null,
    };
  },
  created() {
    // this.getData();
    this.getEqCode();
    this.getFloor();
  },
  methods: {
    getEqCode() {
      getEqCode()
        .then(res => {
          if (res.data.Result == "success") {
            this.EqCode = res.data.Content;
          } else {
            this.$message.error(res.data.ResultMsg);
          }
        })
        .catch(() => {
          this.$message.error("请求失败");
        });
    },
    changeArray(val) {
      if (val instanceof Array) {
        return val.join(",");
      } else {
        return "--";
      }
    },
    clearBox() {
      this.$refs.multipleTable.clearSelection();
    },
    //获取设备关系
    getGraphyId() {
      let param = {
        type: this.type,
        ProjId: this.projectId, //项目id
        secret: this.secret
      };
      getGraphyId(param)
        .then(res => {
          if (res.data.Result == "success") {
            this.graphyId = res.data.graph_id;
            this.getEquip()
          } else {
            this.$message.error(res.data.ResultMsg);
          }
        })
        .catch(() => {
          this.$message.error("请求错误");
        });
    },
    //获取楼层
    getFloor() {
      let param = {
        ProjId: this.projectId,
        UserId: this.userId,
        secret: this.secret
      };
      getSpaceFloor(param)
        .then(res => {
          if (res.data.Result == "success") {
            this.optionsWithDisabled = this.changeArr(res.data.Content);
            this.optionsWithDisabled = this.optionsWithDisabled.map(item => {
              if (item.children && item.children.length) {
                item.children.unshift({
                  value: "no",
                  label: "未指定楼层的设备"
                });
              } else {
                item.children = [{
                  value: "no",
                  label: "未指定楼层的设备"
                }];
              }
              return item;
            });
          } else {
            this.$message.error(res.data.ResultMsg);
          }
        })
        .catch(() => {
          this.$message.error("请求出错");
        });
    },
    getName(code) {
      let text = "",
        myClass = code.substring(0, 2),
        system = code.substring(2, 4),
        last = code.substring(2, 6);
      if (this.EqCode && this.EqCode.length) {
        this.EqCode.map(item => {
          if (item.code == myClass) {
            item.content.map(i => {
              if (i.code == system) {
                i.content.map(e => {
                  if ((e.code == last)) {
                    text = e.facility;
                  }
                });
              }
            });
          }
        });
      }
      return text;
    },
    //工具函数，获取下拉列表
    changeArr(arr) {
      return arr.map(item => {
        if (item.floors && item.floors.length) {
          return {
            value: item.id,
            label: item.infos.BuildLocalName || "--",
            children: item.floors.map(i => {
              return {
                value: i.id,
                label: i.infos.FloorLocalName || "--"
              };
            })
          };
        } else {
          return {
            value: item.id,
            label: item.infos.BuildLocalName || "--",
            children: null
          };
        }
      });
    },
    /**
     * 过滤条件
     */
    filterBox(val) {
      if (typeof val == "boolean") {
        this.search.checkbox = val;
      }
      if (this.search.checkbox) {
        this.getEquip()
      } else {
        if (!!this.search.filter) {
          searchCode({
            key: this.search.filter
          })
            .then(res => {
              if (res.data.Result == "success") {
                this.search.leiArr = res.data.Content;
                this.getEquip();
              } else {
                this.$message.error(res.data.ResultMsg);
              }
            })
            .catch(() => {
              this.$message.error("请求出错");
            });
        } else {
          this.getEquip();
        }
      }
    },
    /**
     * 删除
     * @param row 点击的当条数据
     */
    deleteSpace(row) { },
    /**
     * 获取数据
     * @param data 由上级页面传入,初始化table表格
     */
    getData(list, build, type, activeTabType) {
      this.activeTabType = activeTabType
      this.list = list;
      this.build = build;
      this.search.floor = [build.buildCode, build.code];
      this.type = type
      this.getGraphyId();
      this.page = {
        size: 50,
        sizes: [10, 30, 50, 100, 150, 200],
        total: 0,
        currentPage: 1
      };
      this.getEquip();
    },
    //获取数据
    getEquip() {
      this.isLoading = true;
      let relType = ""
      if (this.activeTabType.rel_type == 99) {
        relType = "1"
      } else {
        if (this.activeTabType.rel_type > 9) {
          relType = (this.activeTabType.rel_type * 100).toString()
        } else {
          relType = '0' + this.activeTabType.rel_type * 100
        }
      }
      if (this.type == "EquipinSpace" && this.activeTabType.rel_type == 99) {
        if (this.search.checkbox) {
          this.isLoading = false
          this.tableData = []
          this.page.total = 0
        } else {
          if (!this.search.filter) {
            this.search.leiArr = []
          }
          let param = {
            data: {
              limit: {
                // 可选
                skip: this.page.size * (this.page.currentPage - 1), // 跳过多少数据
                count: this.page.size // 查询跳过300条数据之后的50条 (默认按照创建时间从大-->小排序)
              },
              criteria: {
                building: this.search.floor[0], //建筑
                floor: this.search.floor[1] == "no" ? null : this.search.floor[1], // 选填, 指定楼层id
                name: this.search.filter, // 选填, 模糊搜索指定信息点的值
                type: this.search.leiArr.length ? this.search.leiArr : ["Eq"],
                space: this.list.id, // 必填, 指定业务空间id
                excludeGraphType: this.type,
                excludeRelType: relType,
                isGeneralZone: true,
                type: ["Eq"] // 必填, 查询类型, 允许四位编码的详细设备类
              }
            },
            ProjId: this.projectId, //项目id
            secret: this.secret
          };
          getEquipSearch(param)
            .then(res => {
              if (res.data.Result == "success") {
                this.page.total = res.data.TotalCount;
                this.tableData = res.data.Content;
                this.isLoading = false;
              } else {
                this.$message.error(res.data.ResultMsg);
              }
            })
            .catch(() => this.$message.error("请求失败"));
        }
      } else {
        if (this.search.checkbox) {
          let param = {
            data: {
              limit: {
                // 可选
                skip: this.page.size * (this.page.currentPage - 1), // 跳过多少数据
                count: this.page.size // 查询跳过300条数据之后的50条 (默认按照创建时间从大-->小排序)
              },
              criteria: {
                building: this.search.floor[0], //建筑
                floor: this.search.floor[1] == "no" ? null : this.search.floor[1], // 选填, 指定楼层id
                name: this.search.filter, // 选填, 模糊搜索指定信息点的值
                type: this.search.leiArr.length ? this.search.leiArr : ["Eq"],
                space: this.list.id, // 必填, 指定业务空间id
                excludeGraphType: this.type,
                excludeRelType: relType
              }
            },
            ProjId: this.projectId, //项目id
            secret: this.secret
          };
          getListForBuss(param, res => {
            this.page.total = res.TotalCount;
            this.tableData = res.Content;
            this.isLoading = false;
          })
        } else {
          let param = {
            data: {
              limit: {
                // 可选
                skip: this.page.size * (this.page.currentPage - 1), // 跳过多少数据
                count: this.page.size // 查询跳过300条数据之后的50条 (默认按照创建时间从大-->小排序)
              },
              criteria: {
                building: this.search.floor[0], //建筑
                floor: this.search.floor[1] == "no" ? null : this.search.floor[1], // 选填, 指定楼层id
                name: this.search.filter, // 选填, 模糊搜索指定信息点的值
                type: this.search.leiArr.length ? this.search.leiArr : ["Eq"],
                space: this.list.id, // 必填, 指定业务空间id
                excludeGraphType: this.type,
                excludeRelType: relType,
                type: ["Eq"] // 必填, 查询类型, 允许四位编码的详细设备类
              }
            },
            ProjId: this.projectId, //项目id
            secret: this.secret
          };
          getEquipSearch(param)
            .then(res => {
              if (res.data.Result == "success") {
                this.page.total = res.data.TotalCount;
                this.tableData = res.data.Content;
                this.isLoading = false;
              } else {
                this.$message.error(res.data.ResultMsg);
              }
            })
            .catch(() => this.$message.error("请求失败"));
        }
      }
    },
    /**
     * 分页函数
     * @param pageNo   当前页数
     * @param pageSize 当前条数
     * @param array    全部数据
     */
    pagination(pageNo, pageSize, array) {
      let offset = (pageNo - 1) * pageSize;
      return offset + pageSize >= array.length ?
        array.slice(offset, array.length) :
        array.slice(offset, offset + pageSize);
    },
    /**
     * 查看详情
     * @param row 点击的当条数据
     */
    lockDetails(row) {
      this.innerVisible = true;
      this.iframeSrc = this.iframeSrc =
        process.env.BASE_URL + ":8889/#/details?perjectId=" +
        this.projectId +
        "&secret=" +
        this.secret +
        "&FmId=" +
        row.id +
        "&type=0&code=" +
        row.category.substring(2, 6);
    },
    pageChange() {
      this.getEquip();
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    //添加关系，点击确定按钮
    addReal() {
      if (this.multipleSelection && this.multipleSelection.length) {
        let param = {
          data: {
            criterias: []
          },
          ProjId: this.projectId, //项目id
          secret: this.secret
        };
        let falg = false;
        if (!!!this.activeTabType) {
          this.$message.error("没有rel_type")
        }
        this.multipleSelection.map(item => {
          let rel_type = ""
          if (this.activeTabType.rel_type < 10) {
            rel_type = '0' + (this.activeTabType.rel_type * 100)
          } else {
            rel_type = (this.activeTabType.rel_type * 100).toString()
          }
          param.data.criterias.push({
            from_id: item.id,
            to_id: this.list.id,
            graph_id: this.graphyId,
            rel_type: this.activeTabType.rel_type == "99" ? "1" : rel_type
          });
          if (!!item.spaceName) {
            falg = true;
          }
        });
        if (falg) {
          this.$confirm("选择的部分设备不在业务空间中确定添加？", "删除", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          })
            .then(() => {
              this.createReal(param);
            })
            .catch(() => {
              this.$message({
                type: "info",
                message: "已取消添加"
              });
              this.clearBox();
            });
        } else {
          this.createReal(param);
        }
      } else {
        this.$message.error("请选择设备再确定关联");
      }
    },
    createReal(param) {
      createRelation(param)
        .then(res => {
          if (res.data.Result == "success") {
            this.$message.success("添加成功");
            this.getEquip();
          } else {
            this.$message.error(res.data.ResultMsg);
          }
        })
        .catch(() => {
          this.$message.error("请求出错");
        });
    }
  },
  filters: {
    cutString: function (str, len) {
      //length属性读出来的汉字长度为1
      if (!!str && typeof str == "string" && str.length > len) {
        return str.substring(0, len) + "...";
      } else {
        return str || "--";
      }
    }
  }
};
</script>