<template>
  <div class="cpt-nest-list-item wih100">
    <div class="nest-group_box">
      <div class="group-title_box">
        <div class="title-box">
          <span :title="data.name" class="title">{{ data.name }}</span>
        </div>
        <div class="line-box w210">
          (
          <span class="cf">共 {{ data.onLineCount + data.offLineCount }} 架</span>
          <span class="healthy--un ml5" style="color: #31db24">{{ data.onLineCount }} 架在线</span>
          <span>/</span>
          <span class="healthy--total" style="color: #cad8d9">{{ data.offLineCount }} 离线</span>)
        </div>
      </div>
    </div>

    <div class="nest-children" :class="{ collapse: listCollapse }">
      <template v-if="data && data.deviceDOList && data.deviceDOList.length">
        <div class="nest-device-list">
          <div v-for="device in data.deviceDOList" :key="`device_${device.id}`" class="nest-device-item"
            :class="{ online: device.isOnline }">
            <!-- 最前面的选项框 -->
            <div class="title-box">
              <el-tooltip :content="device.isOnline ? '在线' : '离线'" placement="top" :enterable="false">
                <el-checkbox :value="hangar && device.deviceId === hangar.deviceId && device.isCheck"
                  @change="(e) => handClick(e, device)"></el-checkbox>
              </el-tooltip>
              <span :title="device.name" class="title">{{ device.name }}</span>
              <span class="li" v-if="!device.isOnline">（离线）</span>
              <span class="zai" v-else>（在线）</span>
              <span :title="device.comment || '异常'" v-if="device.state == 2" style="color: red"
                class="status-icon iconfont icon-yichang1"></span>
              <span :title="device.comment || '维修'" v-if="device.state == 3"
                class="status-icon iconfont icon-weixiu"></span>
              <span :title="device.comment || '保养'" v-if="device.state == 4"
                class="status-icon iconfont icon-baoyang"></span>
            </div>

            <div class="icon-box">
              <span class="type fr" v-if="device.status">{{ typeName(device.status) }}</span>
              <span @click="onLocation(device)" class="iconfont fr icon-dingwei1" v-hover></span>
              <!-- 相同部门不需要接管 -->
              <span 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 />
              </span>
            </div>
          </div>
        </div>
      </template>
      <div class="nest-child_group_box" v-if="data.child && data.child.length">
        <Item v-for="(item, i) in data.child" :data="item" :key="`device_child_${i}`" />
      </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 { mapState } from "vuex";
import { Control_API } from "../../../../../../api";

export default {
  name: "Item",
  props: {
    data: {
      type: Object,
      default: () => ({}),
    },
  },
  inject: ["rootNode", "bus"],
  data() {
    return {
      locationEntity: null,
      takeOverVisible: false,
      // 接管设备信息
      takeDevice: {
        name: "",
      },
      departmentName: "",
      takeLoading: false, //接管等待中
      forceTakeLoading: false, //强制接管等待
    };
  },
  computed: {
    ...mapState("MMCFlightControlCenter", [
      "listCollapse",
      "cesiumViewer",
      "userInfo",
      "deptId",
    ]),
    ...mapState("MMCFlightControlCenter/hangar", ["showPanel", "hangar"]),
    ...mapState("MMCFlightControlCenter/uav", ["uav"]),
  },
  watch: {
    hangar() {
      this.onLocation(this.hangar);
    },
  },
  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: 30000,
          offset:40
        });
        this.$emit("refresh");
        this.takeOverVisible = false;
      } else {
        this.$notify.warning({
          title: "接管消息",
          message: msg,
          duration: 30000,
          offset:40
        });
        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,
      });
      setTimeout(() => {
        if (this.takeLoading) {
          this.$message.error(`接管失败，申请单位未同意`);
          this.takeLoading = false
        }
      }, 5500);
      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;
    },
    typeName(val) {
      let name = "";
      switch (val) {
        case 1:
          name = "正常";
          break;

        case 2:
          name = "维修中";
          break;

        case 3:
          name = "损坏";
          break;

        case 4:
          name = "保养中";
          break;
      }
      return name;
    },
    // 机库选中
    handClick(isCheck, device) {
      console.log("checkbox", isCheck, device);
      device.isCheck = isCheck;

      // 切换订阅的机库, 需要先取消订阅旧机库, 再重新订阅新机库
      this.hangar &&
        this.$store.dispatch("MMCFlightControlCenter/hangar/unsubscribe");
      this.uav &&
        this.$store.dispatch("MMCFlightControlCenter/uav/unsubscribe");

      // todo 由于unsubscribe操作会将hangar设置为null, 所以unsubscribe操作要放在if判断之后再执行
      if (isCheck) {
        this.$store.commit("MMCFlightControlCenter/hangar/setState", {
          key: "showPanel",
          value: true,
        });

        this.$store.commit("MMCFlightControlCenter/hangar/setState", {
          key: "hangar",
          value: {
            ...device,
            showPanel: true,
          },
        });
        this.$store.dispatch("MMCFlightControlCenter/hangar/subscribe");

        // 切换订阅的无人机, 需要先取消订阅旧无人机, 再重新订阅新无人机
        this.uav &&
          this.$store.dispatch("MMCFlightControlCenter/uav/unsubscribe");
        if (device.uav) {
          this.$store.commit("MMCFlightControlCenter/uav/setState", {
            key: "uav",
            value: device.uav,
          });
          this.$store.dispatch("MMCFlightControlCenter/uav/subscribe");
          // 获取无人机视频
          if (!this.uav.streamConfiguration) {
            Control_API.getDeviceStream({
              deviceId: this.uav.id,
            }).then((res) => {
              this.$store.commit("MMCFlightControlCenter/uav/setState", {
                key: "uav",
                value: {
                  ...this.uav,
                  streamConfiguration: res.data.list,
                },
              });
            });
          }
        } else {
          this.$message.error("该机库中没有无人机!");
        }

        //获取机库中视频
        if (!this.hangar.streamConfiguration) {
          Control_API.getDeviceStream({
            deviceId: this.hangar.id,
          }).then((res) => {
            this.$store.commit("MMCFlightControlCenter/hangar/setState", {
              key: "hangar",
              value: {
                ...this.hangar,
                streamConfiguration: res.data.list,
              },
            });
          });
        }
      } else {
        this.$store.commit("MMCFlightControlCenter/hangar/setState", {
          key: "showPanel",
          value: false,
        });
        this.$store.commit("MMCFlightControlCenter/hangar/setState", {
          key: "hangar",
          value: null,
        });
      }
      if (this.showPanel) {
        this.$store.commit("MMCFlightControlCenter/setState", {
          key: "listCollapse",
          value: true,
        });
      }
      this.rootNode.$emit("hangarChange", { hangar: this.hangar }); //根节点发出机库更换事件
    },
    // 机库定位
    onLocation(device) {
      let viewer = this.cesiumViewer;
      if (!device) {
        if (this.locationEntity) {
          viewer.entities.remove(this.locationEntity);
        }
      } else if (device.latitude && device.longitude) {
        if (this.locationEntity) {
          viewer.entities.remove(this.locationEntity);
        }
        this.locationEntity = viewer.entities.add({
          position: Cesium.Cartesian3.fromDegrees(
            Number(device.longitude),
            Number(device.latitude)
          ),
          billboard: {
            image: require("../../assets/images/address.png"),
            width: 30,
            height: 40,
            distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0),
            disableDepthTestDistance: Number.POSITIVE_INFINITY,
          },
        });
        viewer.camera.flyTo({
          destination: Cesium.Cartesian3.fromDegrees(
            Number(device.longitude),
            Number(device.latitude),
            30000
          ),
          maximumHeight: 10,
        });
      } else {
        this.$message.warning("该机库没有经纬度");
      }
    },
    /**
     * 接管无人机
     */
    async onTakeOver(hangar, departmentName) {
      // console.log('onTakeOver:',hangar);
      //upkeepStatus保养状态, upkeepErrorCode异常信息代码,upkeepTime保养时间
      const {upkeepStatus,upkeepErrorCode,upkeepTime,countdown} = hangar;
      
      //设备超过保养时间，不能起飞
      if(!upkeepStatus){
        await this.$confirm(`设备超三个月未进行保养，存在安全隐患，无法进行正常飞行！`, "温馨提示", {
          cancelButtonText: "取消",
          confirmButtonText: "确定",
          showClose: false,
        });
        return;
      }

      //保养周期小于20天时，提示保养
      if(countdown==0 || (countdown && countdown<=20)){
        this.$message({
          type: "warning",
          message: `需安排时间进行保养，上次保养时间为${upkeepTime}，距离下次保养时间还有${countdown}日！超出时间将无法正常飞行！！！`,
          duration: 2000,
        });
      }

      this.departmentName = departmentName;
      if (!hangar.currentOperator) {
        // 没有接管人的情况下该设备所属部门与用户一致则直接接管
        if (this.deptId === hangar.departmentId) {
          let res = await Control_API.updateCurrentOperator({
            deviceId: hangar.id,
          });
          if (res.code === 0) {
            this.$message.success(`请开始操作${hangar.name}`);
            this.$emit("refresh");
          }
        } else {
          // 不一致则申请接管
          this.takeDevice = hangar;
          this.takeOverVisible = true;
          setTimeout(() => {
            if (this.takeLoading) {
              this.$message.error(`接管失败，申请单位未同意`);
              this.takeLoading = false
            }
          }, 5500);
        }
      } else if (
        // 判断当前接管人是不是自已, 是则提示退出接管, 不是则提示是否强制接管
        hangar.currentOperator === this.userInfo.id
      ) {
        try {
          await this.$confirm(`请确认是否退出接管${hangar.name}?`, "安全确认", {
            cancelButtonText: "取消",
            confirmButtonText: "确定",
            customClass: "uav_controlPane",
            showClose: false,
          });
          let res = await Control_API.setUavControlOff({
            deviceId: hangar.id,
          });
          if (res.code === 0) {
            this.$message.success(`已退出接管${hangar.name}`);
            this.$emit("refresh");
          }
        } catch (e) { }
      } else {
        // 已被接管且接管人不是自已的情况下, 需要申请接管
        this.takeDevice = hangar;
        this.takeOverVisible = true;
        // 5秒后没收到通知认定接管失败
        setTimeout(() => {
          if (this.takeLoading) {
            this.$message.error(`接管失败，申请单位未同意`);
            this.takeLoading = false
          }
        }, 5500);
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.cpt-nest-list-item {
  .nest-group_box {
    width: 100%;

    .group-title_box {
      width: 100%;
      display: flex;
      align-items: center;
      justify-content: space-between;
      box-sizing: border-box;
      height: 40px;

      .title-box {
        width: calc(100% - 80px);
        display: flex;
        align-items: center;
        white-space: nowrap;
        overflow: hidden;

        .iconfont {
          color: #ccedff;
          transform: rotate(90deg);
          transition: 0.3s;
          cursor: pointer;

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

        .title {
          font-family: Microsoft YaHei;
          font-size: 14px;
          color: #ccedff;
          font-weight: 400;
          margin-left: 5px;
          width: 100%;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }
      }

      .line-box {
        display: flex;
        flex-shrink: 0;
        font-family: Arial, Helvetica, sans-serif;
        font-size: 14px;
        color: #ccedff;
        line-height: 19px;
        font-weight: 400;
        text-align: right;
        margin: 0 44px 0 0;
      }
    }
  }

  .nest-children {
    overflow: hidden;

    &.collapse {
      height: 0;
    }

    .nest-device-list {
      .nest-device-item {
        height: 30px;
        line-height: 30px;
        box-sizing: border-box;
        padding-left: 20px;
        display: flex;
        align-items: center;
        justify-content: space-between;

        .iconfont {
          font-size: 22px;
          color: #9baaac;
        }

        &.online {
          .title-box {
            .iconfont {
              // color: #fff;
            }

            .title {
              color: #fff;
            }
          }
        }

        .title-box::v-deep {
          height: 100%;
          white-space: nowrap;

          .el-checkbox {
            &.is-checked {
              .el-checkbox__input {
                .el-checkbox__inner {
                  border-color: #08c2d1;

                  &::after {
                    border-color: #08c2d1;
                  }
                }
              }
            }

            .el-checkbox__input {
              .el-checkbox__inner {
                border-radius: 0;
                width: 18px;
                height: 18px;
                background: #000000;
                // border-color: #08c2d1;
                border-color: #fff;
                box-sizing: border-box;

                &::after {
                  height: 10px;
                  left: 5px;
                  top: 1px;
                  width: 5px;
                }
              }
            }
          }

          .iconfont {
            font-size: 20px;
            color: #ccedff;
          }

          .title {
            font-family: MicrosoftYaHei;
            font-size: 14px;
            color: #9baaac;
            font-weight: 400;
            margin-left: 8px;
          }

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

        .icon-box {
          display: flex;
          align-items: center;
          gap: 8px;

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

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

    .nest-child_group_box {
      box-sizing: border-box;
      padding-left: 20px;
    }
  }
}

.li {
  font-size: 16px;
  color: #9baaac;
  font-weight: 400;
}

.zai {
  color: #31db24;
  font-weight: 400;
  font-size: 16px;
}

.type {
  cursor: default;
  font-weight: 400;
  font-size: 10px;
  height: 22px;
  line-height: 22px;
  transform: scale(0.9);
  border: 1px solid #c0aaaa;
  padding: 0 4px;
  border-radius: 4px 4px;
  color: #fff;
  background-color: #224563;
}

.el-checkbox__inner::v-deep {
  background: transparent !important;
}
</style>

<style>
.el-popover .popper__arrow::after {
  border-bottom-color: transparent !important;
}
</style>
