<template>
  <div class="cpt-app-uav-list">
    <div class="uav-item-box">
      <div class="uav-item-inner" @click="$set(data, 'collapse', !data.collapse)">
        <div class="title-box">
          <span class="el-icon-caret-right" :class="{ collapse: data.collapse }"></span>
          <img class="level-icon" src="./assets/images/uav_item1_1.png" v-if="level === 1" />
          <img class="level-icon" src="./assets/images/uav_item2.svg" v-if="level === 2" />
          <img class="level-icon" src="./assets/images/uav_item3.svg" v-if="level === 3" />
          <div class="org-name" :title="data.name">{{ data.name }}</div>
          <i class="refresh-icon el-icon-refresh-right" v-if="level === 1" @click.stop="$emit('refresh')" />
        </div>
        <div class="online-info">
          （共 {{ data.onLineCount + data.offLineCount }} 架
          <span class="ml10" :class="{ online: data.onLineCount }">{{ data.onLineCount }} 在线</span>
          /
          {{ data.offLineCount }} 离线）
        </div>
      </div>
      <div class="uav-item-child-box" :class="{ collapse: data.collapse }">
        <Item v-for="child in data.child" :key="child.deptId" :data="child" :level="level + 1"
          @refresh="$emit('refresh')" />
        <div class="device-item-box" :class="{ online: device.isOnline }" v-for="device in data.deviceDOList"
          :key="`device_${device.deviceId}`">
          <div class="device-name">
            <!-- <span
              style="margin-right:10px"
              :class="device.status==1&&device.currentOperator==1? 'blue' : device.status==1&&device.currentOperator!=1 ?'yellow':'' "
              :title="device.name"
            >{{device.name}}</span>-->
            <span style="margin-right:10px" :class="'blue'" :title="device.name">{{ device.name }}</span>
            <span style="color:#31DB24 " class="dib" v-if="device.isOnline">(在线)</span>
            <span v-else class="dib">(离线)</span>
            <div class="symbol-icon-box">
              <!-- <template v-if="device.modelName && device.modelName.includes('入云龙1')">
                <div class="uav_version status-icon cp">
                  <img src="./assets/images/I.svg" />
                </div>
              </template>
<template v-if="device.modelName && device.modelName.includes('入云龙2')">
                <div class="uav_version status-icon cp">
                  <img src="./assets/images/I.svg" />
                  <img src="./assets/images/I.svg" />
                </div>
              </template>
<template v-if="device.modelName && device.modelName.includes('插翅虎')">
                <div class="uav_version status-icon cp">
                  <img src="./assets/images/cq.svg" />
                </div>
              </template>-->
              <template>
                <div class="uav_version status-icon cp">
                  <!-- <img src="./assets/images/I.svg" />
                  <img src="./assets/images/I.svg" />-->
                  {{ device.modelName }}
                </div>
              </template>
            </div>
          </div>
          <div class="device-fns">
            <div v-if="showVideoPanel" class="iconfont icon-luxiang_xianxing"
              :class="{ active: uav && device.deviceId === uav.deviceId && uav.showPlayer }" title="视频"
              @click="onShowPlayer(device)" v-hover></div>
            <div class="iconfont icon-kongzhi_xianxing"
              :class="{ active: uav && device.deviceId === uav.deviceId && uav.showPanel }" title="控制面板"
              @click="onShowPanel(device)" v-hover></div>
            <div class="takeover" title="接管" @click="onTakeOver(device, data.name)" v-hover>
              <img src="./assets/images/jieguan_active.svg" v-if="device.currentOperator === userInfo.id" />
              <img src="./assets/images/jieguan.svg" v-else />
            </div>
          </div>
        </div>
      </div>
    </div>
    <el-dialog title="接管确认" :visible.sync="takeOverVisible" width="20%" :modal-append-to-body="false"
      :append-to-body="false" :close-on-click-modal="false" @close="takeLoading = false">
      <span>是否请求接管 {{ departmentName }} 下的 {{ takeDevice.name }}</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="takeOverVisible = false">取 消</el-button>
        <el-button @click="onForceTakeOver" type="danger" :loading="forceTakeLoading">强制接管</el-button>
        <el-button type="primary" @click="onApplyTakeOver" :loading="takeLoading">确 认</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mapActions, mapState } from "vuex";
import { Control_API } from "../../../../../../../../api";

export default {
  name: "Item",
  inject: ["rootNode", "bus"],
  props: {
    data: {
      type: Object,
      default: () => ({}),
    },
    level: {
      type: Number,
      default: -1,
    },
  },
  data() {
    return {
      takeOverVisible: false,
      // 接管设备信息
      takeDevice: {
        name: "",
      },
      departmentName: "",
      takeLoading: false, //接管等待中
      forceTakeLoading: false, //强制接管等待
    };
  },

  computed: {
    ...mapState("MMCFlightControlCenter/uav", [
      "uav",
      "showPlayer",
      "showPanel",
    ]),
    ...mapState("MMCFlightControlCenter", [
      "userInfo",
      "showAirwayEdit",
      "deptId",
      'showVideoPanel',
    ]),
  },
  watch: {
    showAirwayEdit(newVal) {
      if (newVal) {
        this.$store.commit("MMCFlightControlCenter/uav/setState", {
          key: "showPlayer",
          value: false,
        });
        this.$store.commit("MMCFlightControlCenter/uav/setState", {
          key: "uav",
          value: {
            ...this.uav,
            showPlayer: false,
          },
        });
      }
    },
  },
  beforeDestroy() {
    this.bus.$off("uas-device-take-agree-message", this.onTakeAgree);
    this.bus.$off("uas-device-take-refuse-message", this.onTakeAgree);
  },
  methods: {
    /**
     * 同意接管事件
     */
    onTakeAgree({ type, content, msg }) {
      console.log("onTakeAgree");
      //接管消息
      if (content.isAgree) {
        this.$notify.success({
          title: "接管消息",
          message: msg,
          duration: 0,
        });
        this.$emit("refresh");
        this.takeOverVisible = false;
      } else {
        this.$notify.warning({
          title: "接管消息",
          message: msg,
          duration: 0,
        });
        this.$message.warning("申请接管拒绝");
      }
      this.takeLoading = false;
      this.bus.$off("uas-device-take-agree-message", this.onTakeAgree);
      this.bus.$off("uas-device-take-refuse-message", this.onTakeAgree);
    },
    /**
     * 申请接管
     */
    async onApplyTakeOver() {
      this.takeLoading = true;
      let res = await Control_API.applyControlUav({
        deviceId: this.takeDevice.id,
      });
      console.log("申请接管");
      if (res.code === 0) {
        this.bus.$on("uas-device-take-agree-message", this.onTakeAgree);
        this.bus.$on("uas-device-take-refuse-message", this.onTakeAgree);
      } else {
        this.$message.warning("申请接管失败");
        this.takeLoading = false;
      }
      setTimeout(() => {
        if (this.takeLoading) {
          this.$message.error(`申请接管失败`);
          this.takeLoading = false
        }
      }, 5500);
    },
    /**
     * 强制接管
     */
    async onForceTakeOver() {
      this.forceTakeLoading = true;
      try {
        let res = await Control_API.setUavControlOnForce({
          deviceId: this.takeDevice.id,
        });
        if (res.code === 0) {
          this.$message.success(`请开始操作${this.takeDevice.name}`);
          this.takeOverVisible = false;
          this.$emit("refresh");
        }
      } catch (e) { }

      this.forceTakeLoading = false;
    },
    /**
     * 接管无人机
     */
    async onTakeOver(uav, departmentName) {
      this.departmentName = departmentName;
      if (!uav.currentOperator) {
        // 没有接管人的情况下该设备所属部门与用户一致则直接接管
        if (this.deptId === uav.departmentId) {
          let res = await Control_API.updateCurrentOperator({
            deviceId: uav.id,
          });
          if (res.code === 0) {
            this.$message.success(`请开始操作${uav.name}`);
            this.$emit("refresh");
          }
        } else {
          // 不一致则申请接管
          this.takeDevice = uav;
          this.takeOverVisible = true;
        }
      } else if (
        // 判断当前接管人是不是自已, 是则提示退出接管, 不是则提示是否强制接管
        uav.currentOperator === this.userInfo.id
      ) {
        try {
          await this.$confirm(`请确认是否退出接管${uav.name}?`, "安全确认", {
            cancelButtonText: "取消",
            confirmButtonText: "确定",
            customClass: "uav_controlPane",
            showClose: false,
          });
          let res = await Control_API.setUavControlOff({
            deviceId: uav.id,
          });
          if (res.code === 0) {
            this.$message.success(`已退出接管${uav.name}`);
            this.$emit("refresh");
          }
        } catch (e) { }
      } else {
        // 已被接管且接管人不是自已的情况下, 需要申请接管
        this.takeDevice = uav;
        this.takeOverVisible = true;
      }
    },
    /**
     * 显示面板
     */
    async onShowPanel(item) {
      // 选中与取消选中
      if (this.uav?.deviceId === item.deviceId) {
        // 已打开播放器的情况下只需要展示数据面板
        if (this.showPlayer && !this.showPanel) {
          this.$store.commit("MMCFlightControlCenter/uav/setState", {
            key: "showPanel",
            value: true,
          });
          this.$store.commit("MMCFlightControlCenter/uav/setState", {
            key: "uav",
            value: {
              ...this.uav,
              showPanel: true,
            },
          });
        } else {
          // 未打开播放器的情况下关闭数据面板并取消订阅
          this.$store.commit("MMCFlightControlCenter/uav/setState", {
            key: "showPanel",
            value: false,
          });
          this.$store.commit("MMCFlightControlCenter/uav/setState", {
            key: "uav",
            value: {
              ...this.uav,
              showPanel: false,
            },
          });
          this.$store.dispatch("MMCFlightControlCenter/uav/unsubscribe");
        }
      } else {
        // 打开新的无人机面板
        if (this.uav) {
          this.$store.dispatch("MMCFlightControlCenter/uav/unsubscribe");
        }
        // 在未打开播放器的情况下，有uav信息，到此步时肯定已经展开了面板，判断是否有流媒体信息, 并显示播放器
        if (!item.streamConfiguration) {
          let res = await Control_API.getDeviceStream({
            deviceId: item.id,
          });
          item.streamConfiguration = res.data.list;
        }
        this.$store.commit("MMCFlightControlCenter/uav/setState", {
          key: "showPanel",
          value: true,
        });
        this.$store.commit("MMCFlightControlCenter/uav/setState", {
          key: "showPlayer",
          value: true,
        });
        this.$store.commit("MMCFlightControlCenter/uav/setState", {
          key: "uav",
          value: {
            ...item,
            showPlayer: true,
            showPanel: true,
          },
        });

        this.$store.dispatch("MMCFlightControlCenter/uav/subscribe");
      }

      if (this.showPanel) {
        this.$store.commit("MMCFlightControlCenter/setState", {
          key: "listCollapse",
          value: true,
        });
      }
      this.rootNode.$emit("uavChange", {
        uav: this.uav,
        showPanel: this.showPanel,
        showPlayer: this.showPlayer,
      });
    },
    /**
     * 显示播放器
     */
    async onShowPlayer(item) {
      // 选中与取消选中
      if (this.uav?.deviceId === item.deviceId) {
        if (this.showPlayer) {
          // 已显示播放器则关掉
          this.$store.commit("MMCFlightControlCenter/uav/setState", {
            key: "showPlayer",
            value: false,
          });
          this.$store.commit("MMCFlightControlCenter/uav/setState", {
            key: "uav",
            value: {
              ...this.uav,
              showPlayer: false,
              showPanel: this.showPanel,
            },
          });
          // 关闭播放器时若未展开面板，需要取消订阅
          if (!this.showPanel) {
            this.$store.dispatch("MMCFlightControlCenter/uav/unsubscribe");
          }
        } else {
          // 在未打开播放器的情况下，有uav信息，到此步时肯定已经展开了面板，判断是否有流媒体信息, 并显示播放器
          if (!item.streamConfiguration) {
            let res = await Control_API.getDeviceStream({
              deviceId: item.id,
            });
            item.streamConfiguration = res.data.list;
          }
          this.$store.commit("MMCFlightControlCenter/uav/setState", {
            key: "showPlayer",
            value: true,
          });
          this.$store.commit("MMCFlightControlCenter/uav/setState", {
            key: "uav",
            value: {
              ...item,
              ...(this.uav || {}),
              showPlayer: true,
              showPanel: this.showPanel,
            },
          });
        }
      } else {
        // 由于hardId不同，到此步时可能是第一次点击，或者是面板已展开
        if (this.showPanel) {
          // 面板已展开禁止切换视频
          return;
        }

        if (this.uav) {
          // 切换无人机视频前需要取消订阅前一台无人机消息
          this.$store.dispatch("MMCFlightControlCenter/uav/unsubscribe");
        }

        // 获取该无人机视频流信息
        if (!item.streamConfiguration) {
          let res = await Control_API.getDeviceStream({
            deviceId: item.id,
          });
          item.streamConfiguration = res.data.list;
        }
        this.$store.commit("MMCFlightControlCenter/uav/setState", {
          key: "showPlayer",
          value: true,
        });
        this.$store.commit("MMCFlightControlCenter/uav/setState", {
          key: "uav",
          value: {
            ...item,
            showPlayer: true,
            showPanel: this.showPanel,
          },
        });
        this.$store.dispatch("MMCFlightControlCenter/uav/subscribe");
      }
      this.rootNode.$emit("uavChange", {
        uav: this.uav,
        showPanel: this.showPanel,
        showPlayer: this.showPlayer,
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.cpt-app-uav-list {
  .uav-item-box {
    font-family: Microsoft YaHei;
    font-size: 16px;
    color: #b3bbc5;
    font-weight: 400;

    .uav-item-inner {
      height: 30px;
      display: flex;
      align-items: center;
      box-sizing: border-box;
      cursor: pointer;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      display: flex;
      justify-content: space-between;
      align-items: center;

      .title-box {
        display: flex;
        align-content: center;
        align-items: center;

        .el-icon-caret-right {
          cursor: pointer;
          transition: 0.3s;
          transform-origin: center;
          transform: rotate(90deg);
          margin-right: 4px;

          &.collapse {
            transform: rotate(0deg);
          }
        }

        .org-name {
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          font-size: 13px;
        }
      }

      .online-info {
        font-size: 12px;
        white-space: nowrap;

        .online {
          color: #31db24;
        }
      }
    }

    .uav-item-child-box {
      padding-left: 20px;

      max-height: 20000px;
      transition: 0.3s;
      overflow: hidden;
      position: relative;

      &::before {
        content: " ";
        display: block;
        height: 100%;
        width: 1px;
        background-color: rgba(255, 255, 255, 0.2);
        position: absolute;
        left: 7px;
        top: 0;
      }

      &.collapse {
        max-height: 0;
      }

      .device-item-box {
        height: 30px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        box-sizing: border-box;
        transition: 0.2s;

        .device-name {
          display: flex;
          align-items: center;
          width: calc(100% - 150px);
          white-space: nowrap;
          text-overflow: ellipsis;
          font-size: 13px;
        }

        &.online {
          .device-name {
            color: #00ffff;
          }
        }

        .device-fns {
          display: flex;
          align-items: center;
          justify-content: space-between;

          .takeover {
            width: 20px;
            cursor: pointer;
            height: 20px;
            background-size: 100% 100%;

            img {
              width: 100%;
              height: 100%;
            }
          }

          .iconfont {
            font-size: 24px;
            margin-right: 8px;
            cursor: pointer;

            &.active {
              color: #00ffff;
            }
          }
        }
      }
    }
  }

  .goodsName_two {
    background-image: url("./assets/images/goodsName_two.svg");
    background-size: 100% 100%;
  }

  .goodsName_one {
    background-image: url("./assets/images/goodsName_one.svg");
    background-size: 100% 100%;
  }
}

.green {
  color: #31db24;
}

.red {
  color: red;
}

.item_items {
  align-items: center;
}

.level-icon {
  width: 16px;
  margin-right: 6px;
}

.refresh-icon {
  width: 16px;
  margin-left: 34px;
}

.jcsb {
  justify-content: left;
}

.status-icon {
  margin-left: 12px;
  font-size: 14px;
  color: RGBA(251, 192, 1, 1);
}

.uav_version {
  margin-top: 1px;
  // width: 14px;
  // height: 12px;
  background: rgba(255, 255, 255, 0.4);
  border-radius: 2px;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 4px;
  color: #fff;
  font-size: 8px;
}

.symbol-icon-box {
  display: flex;
  align-items: center;

  img {
    height: 8px;
  }
}
</style>