<template>
  <el-dialog title="提示" :visible.sync="dialogVisible" :width="dialogWidth" @close="handleClose" id="delRelation">
    <span>确定要清除对应关系？</span>
    <div v-loading="loading">
      <div v-show="ltableData.length>1">
        <div style="margin:10px 0;">有多个对象标识对应了该对象实例，是否一并清除对应关系？</div>
        <el-row class="bgf5">
          <el-col :span="18">
            <el-table :data="ltableData" style="width: 100%;max-height:400px;" height="calc(100% - 160px)" @selection-change="changeSelection"
              ref="ltable">
              <el-table-column label="对象标识" align="right" class-name="bgfff">
                <el-table-column label="数据源" prop="Datasource" align="right" class-name="bgfff" show-overflow-tooltip></el-table-column>
                <el-table-column label="位置标签" prop="LocationFlag" align="right" class-name="bgfff" show-overflow-tooltip>
                  <template slot-scope="scope">
                    <div class="tool-tip">{{scope.row.LocationFlag.toString()}}</div>
                  </template>
                </el-table-column>
                <el-table-column label="对象标识" prop="EquipmentMark" align="right" class-name="bgf5" show-overflow-tooltip></el-table-column>
                <el-table-column type="selection" class-name="bgf5"></el-table-column>
              </el-table-column>
            </el-table>
          </el-col>
          <el-col :span="6">
            <div class="singleDir pl-10 font-default">对象实例</div>
            <div class="pl-10 font-default">{{rtableData[0]?rtableData[0].ObjectLocalName?rtableData[0].ObjectLocalName:'--':'--'}}</div>
            <div class="pl-10 font-default">{{rtableData[0]?rtableData[0].BuildLocalName:'--'}}-{{rtableData[0]?rtableData[0].FloorLocalName:'--'}}
            </div>
            <div class="pl-10 font-default">{{rtableData[0]?rtableData[0].RoomLocalName?rtableData[0].RoomLocalName:'--':'--'}}</div>
          </el-col>
        </el-row>
      </div>
      <div v-show="rtableData.length>1">
        <div style="margin:10px 0;">有多个对象实例对应了该对象标识，是否一并清除对应关系？</div>
        <el-row class="bgf5">
          <el-col :span="6">
            <div class="singleDir pr-10 font-default tr">对象标识</div>
            <div class="pr-10 font-default tr">{{ltableData[0]?ltableData[0].EquipmentMark:'--'}}</div>
            <div class="pr-10 font-default tr">{{ltableData[0]?ltableData[0].LocationFlag.toString():'--'}}</div>
            <div class="pr-10 font-default tr">{{ltableData[0]?ltableData[0].Datasource:'--'}}</div>
          </el-col>
          <el-col :span="18">
            <el-table :data="rtableData" style="width: 100%;max-height:400px;" height="calc(100% - 160px)" @selection-change="changeSelection"
              ref="rtable">
              <el-table-column label="对象实例" class-name="bgfff">
                <el-table-column type="selection" class-name="bgf5"></el-table-column>
                <el-table-column v-for="(item,index) in rightTableHeader" :label="item.label" :key="item.prop" :class-name="index>0?'bgfff':'bgf5'">
                  <template slot-scope="scope">
                    <div v-if="item.prop=='BuildLocalName'">
                      <el-tooltip
                        :content="scope.row.BuildLocalName&&scope.row.BuildLocalName!='null'?scope.row.FloorLocalName&&scope.row.FloorLocalName!='null'?scope.row.BuildLocalName+'-'+scope.row.FloorLocalName:scope.row.BuildLocalName:''"
                        placement="top"
                        :disabled="!(scope.row.BuildLocalName&&scope.row.BuildLocalName!='null'?scope.row.FloorLocalName&&scope.row.FloorLocalName!='null'?scope.row.BuildLocalName+'-'+scope.row.FloorLocalName:scope.row.BuildLocalName:'')">
                        <div class="tool-tip">
                          {{scope.row.BuildLocalName&&scope.row.BuildLocalName!='null'?scope.row.FloorLocalName&&scope.row.FloorLocalName!='null'?scope.row.BuildLocalName+'-'+scope.row.FloorLocalName:scope.row.BuildLocalName:'--'}}
                        </div>
                      </el-tooltip>
                    </div>
                    <div v-else>
                      <el-tooltip :content="scope.row[item.prop]?scope.row[item.prop].toString():''" placement="top"
                        :disabled="!scope.row[item.prop]">
                        <div class="tool-tip">{{scope.row[item.prop]?scope.row[item.prop].toString():'--'}}</div>
                      </el-tooltip>
                    </div>
                  </template>
                </el-table-column>
              </el-table-column>
            </el-table>
          </el-col>
        </el-row>
      </div>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button size="small" @click="handleClose">取消</el-button>
      <el-button size="small" type="primary" @click="handleDelete" :disabled="deleDisabled">清除已选</el-button>
    </span>
  </el-dialog>
</template>
<script>
import {
  dynamicDeleteRelation,
  dynamicQueryPrompt,
  projectQuery, //数据中心查询项目信息
  zoneQuery, //数据中心所有空间实例
  queryLinkSys, //数据中心系统查询
  queryTenant, //数据中心查询租户
  partsQuery, //数据中心部件查询
} from "@/api/scan/request";
import { queryEquip } from "@/api/object/equip";
import { floorQuery } from '@/api/object/floor'

import { buildingQuery } from '@/api/object/build'

export default {
  data() {
    return {
      dialogVisible: false, //弹窗显示与隐藏
      ltableData: [], // 左侧数据
      rtableData: [], // 右侧数据
      loading: false, //loading状态
      dialogWidth: "20%", //弹窗宽度
      selection: [],
      deleDisabled: true,
      deleParam: [],
      allHeaderData: {
        equip: [
          { label: '对象实例名称', prop: "ObjectLocalName" },
          { label: '对象本地编码', prop: "ObjectLocalCode" },
          { label: '所在建筑楼层', prop: "BuildLocalName" },
          { label: '所在业务空间', prop: "RoomLocalName" },
        ],
        parts: [
          { label: '对象实例名称', prop: "ObjectLocalName" },
          { label: '对象本地编码', prop: "ObjectLocalCode" },
          { label: '所在建筑楼层', prop: "BuildLocalName" },
          { label: '所在业务空间', prop: "RoomLocalName" },
          { label: '所属设备实例', prop: "CascadeEquipLocalName" },
        ],
        system: [
          { label: '对象实例名称', prop: "ObjectLocalName" },
          { label: '对象本地编码', prop: "ObjectLocalCode" },
        ],
        space: [
          { label: '对象实例名称', prop: "ObjectLocalName" },
          { label: '对象本地编码', prop: "ObjectLocalCode" },
          { label: '所在建筑楼层', prop: "BuildLocalName" },
        ],
        build: [
          { label: '对象实例名称', prop: "ObjectLocalName" },
          { label: '对象本地编码', prop: "ObjectLocalCode" }
        ],
        floor: [
          { label: '对象实例名称', prop: "ObjectLocalName" },
          { label: '对象顺序号', prop: "ObjectLocalCode" },
          { label: '所在建筑', prop: "BuildLocalName" },
        ],
        tenant: [
          { label: '对象实例名称', prop: "ObjectLocalName" },
          { label: '对象本地编码', prop: "ObjectLocalCode" },
          { label: '所在业务空间', prop: "BuildLocalName" },
        ],
        project: [
          { label: '对象实例名称', prop: "ObjectLocalName" },
          { label: '对象本地编码', prop: "ObjectLocalCode" },
        ],
      },
      rightTableHeader: []
    };
  },
  props: {
    typeName: {
      default: 'equip'
    }
  },
  methods: {
    //弹窗显示
    showDialog(row) {
      this.dialogVisible = true;
      this.loading = true;
      this.rightTableHeader = this.allHeaderData[this.typeName]
      //需先用对象请求接口返回所需对象
      this.getDynamicQueryPrompt(row)
    },
    handleClose(done) {
      this.dialogVisible = false;
      this.deleDisabled = true
    },
    //确认清除对应关系
    handleDelete() {
      dynamicDeleteRelation(this.deleParam, res => {
        this.$emit("refresh");
        this.dialogVisible = false;
        this.$message.success('清除成功');
      });
    },
    //表格中选择事件 1-n or n-1 公用
    changeSelection(selection) {
      this.deleParam = []
      let tempObj = {}
      this.deleDisabled = selection.length <= 0
      if (this.ltableData.length > this.rtableData.length) {
        tempObj.Objs = [selection[0]]
        tempObj.Points = selection
      } else if (this.ltableData.length < this.rtableData.length) {
        tempObj.Objs = selection
        tempObj.Points = [selection[0]]
      } else {
        tempObj.Objs = selection
        tempObj.Points = selection
      }
      this.deleParam.push(tempObj)
    },
    //查询两边数据,同时拼删除param
    getDynamicQueryPrompt(row) {
      let p1 = {
        Filters: `TypeCode='${row.TypeCode}';SubTypeCode='${row.SubTypeCode}';EquipmentMark='${row.EquipmentMark}'`,
        PageNumber: 1,
        PageSize: 500
      }
      //通过标识查询对象实例
      let promise1 = new Promise((resolve, reject) => {
        dynamicQueryPrompt(p1, res => {
          let dyData = res.Content;
          let name = this.typeName;
          if (name == 'equip') {
            let tempArr = dyData.map(t => {
              if (t.Related == 'True') {
                t.EquipID = t.TypeCode + t.ProjectId + t.ObjectID;
                return t.EquipID;
              }
              return undefined;
            }).filter(item => item);
            if (tempArr.length) {
              queryEquip({
                pageSize: 500,
                filters: `equipID in ${JSON.stringify(tempArr)}`,
                cascade: [{ name: "zoneSpaceInBase" }, { name: 'building' }, { name: 'floor' }]
              }, response => {
                let Data = response.content;
                dyData.forEach(item => {
                  Data.forEach(t => {
                    if (t.equipID == item.EquipID) {
                      item.ObjectLocalName = t.equipLocalName;
                      item.FloorLocalName = t.floor ? t.floor.localName : '';
                      item.BuildLocalName = t.building ? t.building.localName : '';
                      item.RoomLocalName = '';
                      if (t.zoneSpaceBaseIn) {
                        t.zoneSpaceBaseIn.forEach(it => {
                          item.RoomLocalName += it.roomLocalName + ',';
                        })
                        item.RoomLocalName = item.RoomLocalName.substring(0, item.RoomLocalName.length - 1);
                      }
                    }
                  })
                })
                resolve(res);
              })
            } else {
              resolve(res);
            }
          } else if (name == 'parts') {
            let tempArr = dyData.map(t => {
              if (t.Related == 'True') {
                t.EquipID = t.TypeCode + t.ProjectId + t.ObjectID;
                return t.EquipID;
              }
              return undefined;
            }).filter(item => item);
            if (tempArr.length) {
              partsQuery({
                PageSize: 500,
                Filters: `EquipID in ${JSON.stringify(tempArr)}`
              }, response => {
                let Data = response.Content;
                dyData.forEach(item => {
                  Data.forEach(t => {
                    if (t.EquipID == item.EquipID) {
                      item.ObjectLocalName = t.EquipLocalName;
                    }
                  })
                })
                resolve(res);
              })
            } else {
              resolve(res);
            }
          } else if (name == 'system') {
            let tempArr = dyData.map(t => {
              if (t.Related == 'True') {
                t.SysID = t.TypeCode + t.ProjectId + t.ObjectID;
                return t.SysID;
              }
              return undefined;
            }).filter(item => item);
            if (tempArr.length) {
              queryLinkSys({
                pageSize: 500,
                filters: `id in ${JSON.stringify(tempArr)}`
              }, response => {
                let Data = response.content;
                dyData.forEach(item => {
                  Data.forEach(t => {
                    if (t.SysID == item.SysID) {
                      item.ObjectLocalName = t.localName;
                    }
                  })
                })
                resolve(res);
              })
            } else {
              resolve(res);
            }
          } else if (name == 'space') {
            let tempArr = dyData.map(t => {
              if (t.Related == 'True') {
                t.RoomID = t.TypeCode + t.ProjectId + t.ObjectID;
                return t.RoomID;
              }
              return undefined;
            }).filter(item => item);
            if (tempArr.length) {
              zoneQuery({
                PageSize: 500,
                Filters: `id in ${JSON.stringify(tempArr)}`,
                Cascade: [{ Name: 'building' }, { Name: 'floor' }],
              }, response => {
                let Data = response.Content;
                dyData.forEach(item => {
                  Data.forEach(t => {
                    if (t.RoomID == item.RoomID) {
                      item.ObjectLocalName = t.RoomLocalName;
                      item.BuildLocalName = t.Building ? t.Building.BuildLocalName : '';
                      item.FloorLocalName = t.Floor ? t.Floor.FloorLocalName : '';
                    }
                  })
                })
                resolve(res);
              })
            } else {
              resolve(res);
            }
          } else if (name == 'build') {
            let tempArr = dyData.map(t => {
              if (t.Related == 'True') {
                t.BuildID = t.TypeCode + t.ProjectId + t.ObjectID;
                return t.BuildID;
              }
              return undefined;
            }).filter(item => item);
            if (tempArr.length) {
              buildingQuery({
                PageSize: 500,
                Filters: `id in ${JSON.stringify(tempArr)}`
              }, response => {
                let Data = response.Content;
                dyData.forEach(item => {
                  Data.forEach(t => {
                    if (t.BuildID == item.BuildID) {
                      item.ObjectLocalName = t.BuildLocalName;
                    }
                  })
                })
                resolve(res);
              })
            } else {
              this.loading = false;
              this.tableData = dyData;
            }
          } else if (name == 'floor') {
            let tempArr = dyData.map(t => {
              if (t.Related == 'True') {
                t.FloorID = t.TypeCode + t.ProjectId + t.ObjectID;
                return t.FloorID;
              }
              return undefined;
            }).filter(item => item);
            if (tempArr.length) {
              floorQuery({
                pageSize: 500,
                cascade: [{ name: 'building' }],
                filters: `id in ${JSON.stringify(tempArr)}`
              }, response => {
                let Data = response.content;
                dyData.forEach(item => {
                  Data.forEach(t => {
                    if (t.id == item.FloorID) {
                      item.ObjectLocalName = t.localName;
                      item.ObjectSequenceID = t.floorSequenceID;
                      item.BuildLocalName = t.building ? t.building.localName : '';
                    }
                  })
                })
                resolve(res)
              })
            } else {
              resolve(res)
            }
          } else if (name == 'tenant') {
            let tempArr = dyData.map(t => {
              if (t.Related == 'True') {
                t.TenantID = t.TypeCode + t.ProjectId + t.ObjectID;
                return t.TenantID;
              }
              return undefined;
            }).filter(item => item);
            if (tempArr.length) {
              queryTenant({
                PageSize: 500,
                Cascade: [{ Name: 'zoneTenantList' }],
                Filters: `TenantID in ${JSON.stringify(tempArr)}`
              }, response => {
                let Data = response.Content;
                dyData.forEach(item => {
                  Data.forEach(t => {
                    if (t.TenantID == item.TenantID) {
                      item.ObjectLocalName = t.TenantLocalName;
                      item.RoomLocalName = '';
                      if (t.ZoneTenantList) {
                        t.ZoneTenantList.forEach(it => {
                          item.RoomLocalName += it.RoomLocalName + ',';
                        });
                        item.RoomLocalName = item.RoomLocalName.substring(0, item.RoomLocalName.length - 1);
                      }
                    }
                  })
                })
                resolve(res);
              })
            } else {
              resolve(res);
            }
          } else if (name == 'project') {
            let tempArr = dyData.map(t => {
              if (t.Related == 'True') {
                t.ProjID = t.TypeCode + t.ProjectId;
                return t.ProjID;
              }
              return undefined;
            }).filter(item => item);
            if (tempArr.length) {
              projectQuery({
                PageSize: 500,
                Filters: `ProjID in ${JSON.stringify(tempArr)}`
              }, response => {
                let Data = response.Content;
                dyData.forEach(item => {
                  Data.forEach(t => {
                    if (t.ProjID == item.ProjID) {
                      item.ObjectLocalName = t.ProjLocalName;
                    }
                  })
                })
                resolve(res)
              })
            } else {
              resolve(res)
            }
          }
        })
      })
      let p2 = {
        Filters: `ObjectID='${row.ObjectID}';TypeCode='${row.TypeCode}'`,
        PageNumber: 1,
        PageSize: 500
      }
      let promise2 = new Promise((resolve, reject) => {
        dynamicQueryPrompt(p2, res => {
          resolve(res)
        })
      })
      Promise.all([promise1, promise2]).then(res => {
        this.deleParam = [];
        this.ltableData = res[1].Content;
        this.rtableData = res[0].Content;
        if (this.ltableData.length > 1 || this.rtableData.length > 1) {
          this.dialogWidth = "60%";
        } else {
          this.dialogWidth = "20%";
        }
        this.$nextTick(() => {
          this.toggleSelection(row);
        })
        this.loading = false;
      })
    },
    //设置默认选中
    toggleSelection(row) {
      if (this.ltableData.length > this.rtableData.length) {
        this.ltableData.map((t, i) => {
          if (t.ObjectID == row.ObjectID) {
            this.$refs.ltable.toggleRowSelection(this.ltableData[i], true)
            return;
          }
        })
      } else {
        this.rtableData.map((t, i) => {
          if (t.ObjectID == row.ObjectID) {
            this.$refs.rtable.toggleRowSelection(this.rtableData[i], true)
            return;
          }
        })
      }
    }
  },
  mounted() { },
  created() { }
};
</script>
<style lang="scss" scoped>
#delRelation {
  /deep/ .bgf5 {
    background-color: #f5f7fa;
  }
  /deep/ .bgfff {
    background-color: #fff;
  }
  div.singleDir {
    font-weight: 800;
    color: #606266;
    border-bottom: 1px solid #ebeef5;
    background: #fff;
    border-top: 1px solid #ebeef5;
  }
  .pl-10 {
    padding-left: 10px;
  }
  .pr-10 {
    padding-right: 10px;
  }
  .font-default {
    line-height: 42px;
    font-size: 12px;
  }
  .tr {
    text-align: right;
  }
  .tool-tip {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}
</style>
