<template>
  <div class="uav-list" :class="{ collapse: listCollapse }">
    <div class="uav-list_btn" @click="collapseFlagfn">
      <img style src="./assets/images/collapse.svg" />
    </div>
    <div class="uav-list-header">
      <span class="uav-list-header__text">{{ $t('uavList.无人机列表') }} </span>
    </div>
    <div class="uav-search">
      <el-input
        class="uav-search__input"
        clearable
        :placeholder="$t('uavList.请输入无人机名称机构名称')"
        v-model="uavSearchContent"
        v-on:keyup.enter.native="onUavSearch"
      >
        <i
          slot="suffix"
          class="el-input__icon el-icon-search"
          style="color: rgba(123, 181, 213, 1)"
        ></i>
      </el-input>
      <el-button class="uav-search__btn" @click="onUavSearch" v-hover
        >{{ $t('common.搜索') }}</el-button
      >
    </div>
    <List
      class="uav-list-main"
      :containerStyle="{
        width: '400PX',
        height: '275px',
      }"
      :list="uavList"
      @refresh="initList"
    />
    <div></div>
  </div>
</template>

<script>
import { mapState } from "vuex";
import { Control_API } from "../../../../api";
import List from "./components/list";
// import data from "./data.json";

export default {
  components: {
    List,
  },
  inject: ["bus"],
  data() {
    return {
      uavList: [], // 无人机列表
      uavSearchContent: "", // 无人机搜索内容
      timeHandle: null, // 定时刷新句柄
      deviceType: 1, // 设备类型 1无人机
    };
  },
  computed: {
    ...mapState("MMCFlightControlCenter", ["showAirwayEdit"]),
    // 收起列表按钮
    listCollapse: {
      get() {
        return this.$store.state.MMCFlightControlCenter.listCollapse;
      },
      set(val) {
        this.$store.commit("MMCFlightControlCenter/setState", {
          key: "listCollapse",
          value: val,
        });
      },
    },
  },
  watch: {
    showAirwayEdit(newVal) {
      if (newVal) {
        this.listCollapse = true;
      }
    },
  },
  mounted() {
    this.initList();
    // 移除重复的事件监听，避免与 update-uav-list 冲突
    this.bus.$on("uas-device-getTree-message", this.initList);
    this.bus.$on("update-uav-list", this.updateUavList);
    // this.timeHandle = setInterval(() => {
    //   this.initList();
    // }, 10000);
  },
  beforeDestroy() {
    // clearInterval(this.timeHandle);
    // 清理事件监听
    this.bus.$off("update-uav-list", this.updateUavList);
  },
  methods: {
    async initList() {
      let res = await Control_API.getUavTree({
        serchKey: this.uavSearchContent,
        deviceType: this.deviceType,
      });
        this.uavList = res.data;
    },
    collapseFlagfn() {
      this.listCollapse = !this.listCollapse;
    },
    /**
     * 无人机搜索
     */
    onUavSearch() {
      this.initList();
    },
    /**
     * 更新无人机列表数据
     */
    updateUavList(data) {
      console.log('updateUavList 接收到数据:', data);
      
      // 数据安全检查
      if (!data || !Array.isArray(data)) {
        console.warn('updateUavList: 接收到的数据无效', data);
        return;
      }
      
      if (!this.uavList || !Array.isArray(this.uavList)) {
        this.uavList = [];
      }
      this.uavList = data
    },
    
    /**
     * 备用更新方法 - 简单的状态保留更新
     * @param {Array} data 新数据
     */
    fallbackUpdate(data) {
      console.log('执行备用更新方法');
      const oldUavList = this.uavList || [];
      const newUavList = JSON.parse(JSON.stringify(data));
      
      // 保留状态
      newUavList.forEach((newItem) => {
        if (!newItem || !newItem.deptId) return;
        
        const oldItem = oldUavList.find((old) => old && old.deptId === newItem.deptId);
        if (oldItem) {
          // 保留collapse和isCheck状态
          if (oldItem.hasOwnProperty('collapse')) {
            this.$set(newItem, 'collapse', oldItem.collapse);
          } else {
            this.$set(newItem, 'collapse', false);
          }
          if (oldItem.hasOwnProperty('isCheck')) {
            this.$set(newItem, 'isCheck', oldItem.isCheck);
          }
        } else {
          this.$set(newItem, 'collapse', false);
        }
      });
      
      this.uavList = newUavList;
      console.log('备用更新完成');
    },
    /**
     * 更新子设备
     * @param {Object} oldItem 旧项目
        return;
      }
      
      if (!oldItem.child || !Array.isArray(oldItem.child)) {
        this.$set(oldItem, 'child', []);
      }
      
      // 删除不存在的子设备
      for (let i = oldItem.child.length - 1; i >= 0; i--) {
        const oldChild = oldItem.child[i];
        if (!oldChild || !oldChild.deptId) continue;
        
        const newChild = newItem.child.find(child => child && child.deptId === oldChild.deptId);
        if (!newChild) {
          console.log('删除子设备:', oldChild.deptName);
          this.$delete(oldItem.child, i);
        }
      }
      
      // 新增和更新子设备
      newItem.child.forEach((newChild) => {
        if (!newChild || !newChild.deptId) return;
        
        const oldChildIndex = oldItem.child.findIndex(child => child && child.deptId === newChild.deptId);
        
        if (oldChildIndex === -1) {
           // 新增子设备
           console.log('新增子设备:', newChild.deptName);
           const newChildCopy = JSON.parse(JSON.stringify(newChild));
           // 保留旧的isCheck状态（如果存在）
           if (newChild.hasOwnProperty('isCheck')) {
             this.$set(newChildCopy, 'isCheck', newChild.isCheck);
           }
           this.$set(oldItem.child, oldItem.child.length, newChildCopy);
        } else {
          // 更新子设备字段
          const oldChild = oldItem.child[oldChildIndex];
          const childFields = ['deptName', 'deviceCount', 'onlineCount', 'offlineCount', 'takeStatus', 'takeOver', 'online', 'status'];
          
          childFields.forEach(field => {
            if (newChild.hasOwnProperty(field) && oldChild[field] !== newChild[field]) {
              console.log(`更新子设备字段 [${oldChild.deptName}] ${field}:`, oldChild[field], '->', newChild[field]);
              this.$set(oldChild, field, newChild[field]);
            }
          });
        }
      });
    },
    
    /**
     * 更新设备列表
     * @param {Object} oldItem 旧项目
     * @param {Object} newItem 新项目
     */
    updateDeviceList(oldItem, newItem) {
      if (!newItem.deviceDOList || !Array.isArray(newItem.deviceDOList)) {
        if (oldItem.deviceDOList && Array.isArray(oldItem.deviceDOList)) {
          this.$set(oldItem, 'deviceDOList', []);
        }
        return;
      }
      
      if (!oldItem.deviceDOList || !Array.isArray(oldItem.deviceDOList)) {
        this.$set(oldItem, 'deviceDOList', []);
      }
      
      // 删除不存在的设备
      for (let i = oldItem.deviceDOList.length - 1; i >= 0; i--) {
        const oldDevice = oldItem.deviceDOList[i];
        if (!oldDevice || !oldDevice.deviceId) continue;
        
        const newDevice = newItem.deviceDOList.find(device => device && device.deviceId === oldDevice.deviceId);
        if (!newDevice) {
          console.log('删除设备:', oldDevice.deviceName || oldDevice.deviceId);
          this.$delete(oldItem.deviceDOList, i);
        }
      }
      
      // 新增和更新设备
      newItem.deviceDOList.forEach((newDevice) => {
        if (!newDevice || !newDevice.deviceId) return;
        
        const oldDeviceIndex = oldItem.deviceDOList.findIndex(device => device && device.deviceId === newDevice.deviceId);
        
        if (oldDeviceIndex === -1) {
           // 新增设备
           console.log('新增设备:', newDevice.deviceName || newDevice.deviceId);
           const newDeviceCopy = JSON.parse(JSON.stringify(newDevice));
           // 保留设备的状态属性（如果存在）
           Object.keys(newDevice).forEach(key => {
             if (key.includes('Check') || key.includes('State') || key.includes('Status')) {
               if (newDevice.hasOwnProperty(key)) {
                 this.$set(newDeviceCopy, key, newDevice[key]);
               }
             }
           });
           this.$set(oldItem.deviceDOList, oldItem.deviceDOList.length, newDeviceCopy);
        } else {
          // 更新设备字段
          const oldDevice = oldItem.deviceDOList[oldDeviceIndex];
          const deviceFields = ['deviceName', 'takeStatus', 'takeOver', 'online', 'status', 'connectionStatus', 'currentOperator'];
          
          deviceFields.forEach(field => {
            if (newDevice.hasOwnProperty(field) && oldDevice[field] !== newDevice[field]) {
              console.log(`更新设备字段 [${oldDevice.deviceName || oldDevice.deviceId}] ${field}:`, oldDevice[field], '->', newDevice[field]);
              this.$set(oldDevice, field, newDevice[field]);
            }
          });
        }
      });
    },
    
    /**
     * 对比新旧UAV数据，检查是否有变化
     * @param {Array} oldData 旧数据
     * @param {Array} newData 新数据
     * @returns {boolean} 是否有变化
     */
    compareAndUpdateUavData(oldData, newData) {
      // 如果数组长度不同，肯定有变化
      if (oldData.length !== newData.length) {
        console.log('数据长度变化:', oldData.length, '->', newData.length);
        return true;
      }
      
      // 基于 deptId 进行匹配对比，而不是按索引位置
      for (const newItem of newData) {
        if (!newItem || !newItem.deptId) {
          console.log('新数据项无效或缺少 deptId:', newItem);
          return true;
        }
        
        const oldItem = oldData.find(item => item && item.deptId === newItem.deptId);
        
        if (!oldItem) {
          console.log('发现新增项目:', newItem.deptId, newItem.deptName);
          return true;
        }
        
        // 对比关键字段 - 主要判断接管状态和设备在线离线状态
        const keyFields = ['deptName', 'deviceCount', 'onlineCount', 'offlineCount', 'takeStatus', 'takeOver', 'online', 'status'];
        for (const field of keyFields) {
          if (oldItem[field] !== newItem[field]) {
            console.log(`字段变化 [${newItem.deptName}] ${field}:`, oldItem[field], '->', newItem[field]);
            return true;
          }
        }
        
        // 对比子设备数组
        if (this.compareChildDevices(oldItem.child || [], newItem.child || [])) {
          console.log('子设备数据变化:', newItem.deptName);
          return true;
        }
        
        // 对比设备列表
        if (this.compareDeviceList(oldItem.deviceDOList || [], newItem.deviceDOList || [])) {
          console.log('设备列表数据变化:', newItem.deptName);
          return true;
        }
      }
      
      // 检查是否有项目被删除
      for (const oldItem of oldData) {
        if (oldItem && oldItem.deptId) {
          const newItem = newData.find(item => item && item.deptId === oldItem.deptId);
          if (!newItem) {
            console.log('发现删除项目:', oldItem.deptId, oldItem.deptName);
            return true;
          }
        }
      }
      
      return false;
    },
    
    /**
     * 对比子设备数据
     */
    compareChildDevices(oldChildren, newChildren) {
      if (oldChildren.length !== newChildren.length) {
        return true;
      }
      
      // 基于 deptId 进行匹配对比
      for (const newChild of newChildren) {
        if (!newChild || !newChild.deptId) {
          return true;
        }
        
        const oldChild = oldChildren.find(item => item && item.deptId === newChild.deptId);
        
        if (!oldChild) {
          return true;
        }
        
        const childFields = ['deptName', 'deviceCount', 'onlineCount', 'offlineCount', 'takeStatus', 'takeOver', 'online', 'status'];
        for (const field of childFields) {
          if (oldChild[field] !== newChild[field]) {
            return true;
          }
        }
      }
      
      // 检查是否有子设备被删除
      for (const oldChild of oldChildren) {
        if (oldChild && oldChild.deptId) {
          const newChild = newChildren.find(item => item && item.deptId === oldChild.deptId);
          if (!newChild) {
            return true;
          }
        }
      }
      
      return false;
    },
    
    /**
     * 对比设备列表数据
     */
    compareDeviceList(oldDevices, newDevices) {
      if (oldDevices.length !== newDevices.length) {
        return true;
      }
      
      // 基于 deviceId 进行匹配对比
      for (const newDevice of newDevices) {
        if (!newDevice || !newDevice.deviceId) {
          return true;
        }
        
        const oldDevice = oldDevices.find(item => item && item.deviceId === newDevice.deviceId);
        
        if (!oldDevice) {
          return true;
        }
        
        const deviceFields = ['deviceName', 'status', 'online', 'takeStatus', 'takeOver', 'connectionStatus', 'currentOperator'];
        for (const field of deviceFields) {
          if (oldDevice[field] !== newDevice[field]) {
            return true;
          }
        }
      }
      
      // 检查是否有设备被删除
      for (const oldDevice of oldDevices) {
        if (oldDevice && oldDevice.deviceId) {
          const newDevice = newDevices.find(item => item && item.deviceId === oldDevice.deviceId);
          if (!newDevice) {
            return true;
          }
        }
      }
      
      return false;
    },
  },
};
</script>

<style lang="scss" scoped>
.collapse {
  transform: translateX(-100%);
  transition: 0.3s;

  .uav-list_btn {
    &::before {
      transform: translate(-63%, -50%) rotate(90deg) !important;
    }
  }
}

.uav-list {
  display: flex;
  flex-direction: column;
  position: absolute;
  width: 420px;
  height: 100%;
  left: 0;
  top: 0;
  // height: 86vh;
  z-index: 99;
  transition: 0.3s;
  background: #222222;
  // border: 1px solid #70daf9;
  .uav-list_btn {
    position: absolute;
    cursor: pointer;
    right: -35px;
    top: 23%;
    transform: translate(0, -50%);
    z-index: 99;

    &::before {
      content: "";
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-63%, -50%) rotate(-90deg);
      width: 0px;
      height: 0px;
      border-left: 7px solid transparent;
      border-right: 7px solid transparent;
      border-bottom: 9px solid #fff;
    }
  }
}

.uav-list-header {
  flex-shrink: 0;
  box-sizing: border-box;
  display: flex;
  align-items: center;
  width: 100%;
  height: 54px;
  padding: 0 16px;

  .uav-list-header__text {
    font-family: PingFangSC, PingFang SC;
    font-weight: 600;
    font-size: 16px;
    color: #ffffff;
  }
}

.uav-search::v-deep {
  flex-shrink: 0;
  padding: 0 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;

  .uav-search__input {
    width: 292px;
    height: 32px;
    border-radius: 4px;

    .el-input__icon {
      line-height: 32px;
      color: #a8abb2 !important;
    }

    input {
      height: 32px;
      background: #191919;
      font-family: PingFangSC, PingFang SC;
      font-weight: 400;
      font-size: 12px;
      color: #fff;
      border: 1px solid #4b4b4b;

      &::placeholder {
        font-size: 12px;
        color: #a8abb2;
      }
    }
  }

  .uav-search__btn {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 80px;
    height: 32px;
    font-size: 14px;
    color: #fff;
    border-radius: 2px;
    border: 0;
    background: #3388ff;
  }
}

.uav-list-main {
  margin-top: 20px;

  /* 滚动条整体样式 */
  &::-webkit-scrollbar {
    width: 10px; /* 滚动条宽度 */
  }

  /* 滚动条滑块样式 */
  &::-webkit-scrollbar-thumb {
    background-color: #02173d; /* 滑块颜色 */
  }

  /* 滚动条滑块悬停样式 */
  &::-webkit-scrollbar-thumb:hover {
    background-color: #112d5b; /* 悬停时滑块颜色 */
  }

  &::-webkit-scrollbar-track-piece {
    /* background-color: #182F5C; */
  }

  &::-webkit-scrollbar-track {
    background-color: #182f5c;
  }
}
</style>