<template>
  <el-container class="app-container">
    <el-aside width="260px" class="aside-box">
      <div class="tab-content-title" style="padding-left: 0; font-weight: normal;justify-content: space-between;">
        <div class="tab-content-title-left">
          <img class="tab-content-title-icon" src="@/assets/images/watchApi/title-icon.png" />
          <span>基本信息</span>
        </div>
        <div class="tab-content-title-right" @click="handleOpenEdit">
          <i class="el-icon-edit"></i>
        </div>
      </div>
      <BaseInfoDialog ref="BaseInfoDialog" />
      <div class="aside-box-user">
        <el-avatar class="aside-box-user-avatar" size="large"
          src="https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png"></el-avatar>
        <div class="aside-box-user-right">
          <div>
            <span>{{ userInfo.nickname || '--' }}</span>
            <i class="el-icon-male" style="color: #2284ff" v-if="userInfo.gender == '男'"></i>
            <i class="el-icon-female" style="color: pink" v-if="userInfo.gender == '女'"></i>
          </div>
          <div class="aside-box-user-phone">
            <i class="el-icon-phone-outline" style="margin-left: 0; margin-right: 5px"></i>
            <span>{{ userInfo.phone || '--' }}</span>
          </div>
        </div>
      </div>
      <div class="aside-box-bodyinfo">
        <span>身高：</span>
        <span>{{ userInfo.height || '--' }}cm</span>
      </div>
      <div class="aside-box-bodyinfo">
        <span>体重：</span>
        <span>{{ userInfo.weight || '--' }}kg</span>
      </div>
      <div class="aside-box-bodyinfo" style="margin-bottom: 12px">
        <span>出生日期：</span>
        <span>{{ userInfo.birthday || '--' }}</span>
      </div>
      <div class="aside-box-equipment">
        <div class="tab-content-title" style="padding-left: 0; font-weight: normal">
          <img class="tab-content-title-icon" src="@/assets/images/watchApi/title-icon.png" />
          <span>设备信息</span>
        </div>
        <div class="aside-box-equipment-title">设备编号:</div>
        <div class="aside-box-equipment-num">{{ deviceDetails.deviceNumber || '--' }}</div>
      </div>
      <div class="equipment-box">
        <div class="equipment-body">
          <!-- <img class="equipment-body-img" src="@/assets/images/watchApi/watch_icon36.png" alt="设备图片" /> -->
          <img class="equipment-body-img" src="@/assets/images/watchApi/watch_icon36.png"/>
          <div style="flex: 1">
            <!-- <div class="equipment-body-name">设备名称</div> -->
            <div class="equipment-body-name">4G健康手表</div>
            <div class="equipment-body-other">
              <i class="el-icon-circle-check" style="color:#2284ff" v-show="deviceDetails.statusOut == 'ONLINE'"></i>
              <i class="el-icon-circle-close" style="color:#F56C6C" v-show="deviceDetails.statusOut == ''"></i>
              <span style="color: #2284ff; margin-right: 15px;margin-left: 5px;">{{ _statusOut(deviceDetails.statusOut)
                || '--'}}</span>
              <img src="@/assets/images/watchApi/battery.png">
              <span style="color: #00bc98;margin-left: 5px;">{{ deviceDetails.battery || '--' }}%</span>
            </div>
          </div>
        </div>
        <div class="equipment-day">
          <!-- 已绑定 <span>400</span> 天, 佩戴 <span>4365</span> 天 -->
        </div>
        <div class="equipment-btn">
          <el-button type="primary" size="small">一键上传</el-button>
          <el-button type="primary" size="small">恢复出厂</el-button>
        </div>
      </div>
    </el-aside>
    <el-main>
      <div class="switch-container">
        <el-switch v-model="detailsType" active-text="列表详情" inactive-text="图表详情"  @change="handleSwitchChange"></el-switch>
      </div>


      <el-tabs v-model="activeTab" @tab-click="handleTabClick" class="tabs">
        <el-tab-pane v-for="(item, index) in tabsList" :key="index" :label="item.label" :name="item.name"></el-tab-pane>
      </el-tabs>

      <keep-alive>
        <component :ref="currentTabComponent" :is="currentTabComponent" :deviceId="deviceId" :basicInfo="basicInfo" :detailsType="detailsType" :userInfo="userInfo">
        </component>
      </keep-alive>
    </el-main>
  </el-container>
</template>

<script>
import {
  getDeviceInfo,
  getUser,
  // getHeartRateData,
  getWatchData
} from "@/api/watch/deviceInfo";
import {realtimeLocation} from "@/api/watch/deviceInfoSet";
import moment from "moment"; // 用于获取当前日期
import LineChart from "@/components/Chart/LineChart.vue";
import Heartrate from "@/components/DeviceInfo/Heartrate.vue";
import AtrialFibrillation from "@/components/DeviceInfo/AtrialFibrillation.vue";
import Electrocardiogram from "@/components/DeviceInfo/Electrocardiogram.vue";
import Sports from "@/components/DeviceInfo/Sports.vue";
import Sleep from "@/components/DeviceInfo/Sleep.vue";
import Location from "@/components/DeviceInfo/Location.vue";
import Pulse from "@/components/DeviceInfo/Pulse.vue";
import BloodSugar from "@/components/DeviceInfo/BloodSugar.vue";
import BaseInfoDialog from '@/components/DeviceInfo/BaseInfoDialog.vue';
import Pressure from '@/components/DeviceInfo/Pressure.vue';
import Temperature from '@/components/DeviceInfo/Temperature.vue';
import Overview from '@/components/DeviceInfo/Overview.vue';
import Bloodoxygen from '@/components/DeviceInfo/Bloodoxygen.vue';
import Uricacid from '@/components/DeviceInfo/Uricacid.vue';
import Urineketones from '@/components/DeviceInfo/Urineketones.vue';
import PressureValue from '@/components/DeviceInfo/PressureValue.vue';
import Report from '@/components/DeviceInfo/Report.vue';

export default {
  name: "DeviceDetails",
  components: {
    BaseInfoDialog,
    LineChart,
    Heartrate,
    AtrialFibrillation,
    Electrocardiogram,
    Sports,
    Sleep,
    Location,
    Pulse,
    BloodSugar,
    Pressure,
    Temperature,
    Overview,
    Bloodoxygen,
    Uricacid,
    Urineketones,
    PressureValue,
    Report
  },
  data() {
    return {
      detailsType:false,
      // 导出遮罩层
      exportLoading: false,
      deviceId: "",
      af: "",
      heartRateData: {},
      currentDate: moment().format("YYYY-MM-DD"), // 获取当天日
      overviewTitle: "",
      deviceDetails: {},
      basicInfo: {},
      userInfo: {},
      activeTab: "overview", // 当前选中的导航标签
      tabsList: [
        {
          label: '概况',
          name: 'overview'
        },
        {
          label: '心率',
          name: 'heartRate'
        },
        {
          label: '房颤',
          name: 'afib'
        },
        // {
        //   label: '心电',
        //   name: 'ecg'
        // },
        {
          label: '运动',
          name: 'sports'
        },
        {
          label: '睡眠',
          name: 'sleep'
        },
        {
          label: '位置',
          name: 'location'
        },
        // {
        //   label: '脉搏',
        //   name: 'pulse'
        // },
        {
          label: '血糖',
          name: 'bloodsugar'
        },
        {
          label: '血压',
          name: 'bloodpressure'
        },
        // {
        //   label: '血酮',
        //   name: 'urineketones'
        // },
        {
          label: '尿酸',
          name: 'uricacid'
        },
        {
          label: '血氧',
          name: 'bloodoxygen'
        },
        {
          label: '体温',
          name: 'temperature'
        },
        // {
        //   label: '血脂',
        //   name: 'bloodfat'
        // },
        {
          label: '压力',
          name: 'pressureValue'
        },
        {
          label: '周报',
          name: 'report'
        },
      ]
    };
  },
  computed: {
    _statusOut() {
      return (status) => {
        const statusOption = {
          "ONLINE": '在线'
        }
        return status ? statusOption[status] || '--' : '--'
      }
    },
    currentTabComponent() {
      const tabs = {
        heartRate: Heartrate,
        afib: AtrialFibrillation,
        ecg: Electrocardiogram,
        sports: Sports,
        sleep: Sleep,
        location: Location,
        pulse: Pulse,
        bloodsugar: BloodSugar,
        bloodpressure: Pressure,
        temperature: Temperature,
        overview: Overview,
        bloodoxygen: Bloodoxygen,
        uricacid: Uricacid,
        urineketones: Urineketones,
        pressureValue:PressureValue,
        report:Report


      }
      return tabs[this.activeTab] || ''
    }
  },
  created() {
    this.fetchDeviceDetails();
  },
  methods: {
    handleSwitchChange(value) {
      // 切换详情类型时触发
      this.$nextTick(() => {
        const currentComponentRef = this.$refs[this.currentTabComponent];
        // if (currentComponentRef && typeof currentComponentRef.getDetailsData === 'function') {
        //   currentComponentRef.getDetailsData();
        // }
        if (currentComponentRef) {
          if (value) {
            // 列表详情：调用子组件的方法来获取列表数据
            if (typeof currentComponentRef.getDataPage === 'function') {
              currentComponentRef.getDataPage();
            }
          } else {
            // 图表详情：调用子组件的方法来获取图表数据
            if (typeof currentComponentRef.getDetailsData === 'function') {
              currentComponentRef.getDetailsData();
            }
          }
        }

      });
    },
    getRealtimeLocation(){
      realtimeLocation({deviceNumber:this.deviceId});
    },
    // 打开基本信息弹窗
    handleOpenEdit() {
      // this.getUserinfo(this.deviceDetails.deviceNumber)
      this.$refs.BaseInfoDialog.handleUpdate(this.userInfo);
    },
    async fetchDeviceDetails() {
      try {
        const deviceId = this.$route.params.deviceId; // 从路由中获取 deviceId
        const response = await getDeviceInfo(deviceId);
        this.deviceDetails = response.data;
        this.deviceId = this.deviceDetails.deviceNumber;
        // console.log("获取", this.deviceId)
        // 请求到设备信息后，再请求用户信息
        this.getUserinfo(this.deviceDetails.deviceNumber);
        // 获取心率数据
        // this.getHeartRateData(this.deviceDetails.deviceNumber);
        // 获取基本数据
        this.getWatchData(this.deviceDetails.deviceNumber);
        //获取概况
        this.$nextTick(() => {
          this.$refs[this.currentTabComponent].getDetailsData();
        })
        //获取实时定位
        this.getRealtimeLocation();
      } catch (error) {
        console.error("获取数据失败:", error);
      }
    },

    async getWatchData(deviceId) {
      try {
        const response = await getWatchData(deviceId);
        if (response && response.data) {
          this.basicInfo = response.data; // 确保数据被正确赋值
          if (moment(this.basicInfo.createTime).format("YYYY-MM-DD") !== this.currentDate){
            this.basicInfo.steps = null;
          }
          // console.log("基本数据:", this.userInfo);
        } else {
          console.warn("基本数据返回为空或格式不正确:", response);
        }
      } catch (error) {
        console.error("获取基本数据失败:", error);
      }
    },

    // async getHeartRateData(deviceId) {
    //   try {
    //     const response = await getHeartRateData(deviceId);
    //     if (response && response.data) {
    //       this.heartRateData = response.data; // 确保数据被正确赋值
    //     } else {
    //       console.warn("心率信息返回为空或格式不正确:", response);
    //     }
    //   } catch (error) {
    //     console.error("获取心率信息失败:", error);
    //   }
    // },

    /**
     * 获取用户信息
     * @param deviceId
     */
    async getUserinfo(deviceId) {
      try {
        const userId = this.$route.params.userId;
        const selectType = this.$route.params.selectType;
        const response = await getUser({deviceId:deviceId,userId:userId,selectType});
        if (response && response.data) {
          this.userInfo = response.data; // 确保数据被正确赋值
          this.userInfo.userId = userId;
          // console.log("用户信息:", this.userInfo);
        } else {
          console.warn("用户信息返回为空或格式不正确:", response);
        }
      } catch (error) {
        console.error("获取用户信息失败:", error);
      }
    },
    async handleTabClick(tab) {
      // this.$nextTick(() => {
      //   this.$refs[this.currentTabComponent].getDetailsData();
      // });

      await this.$nextTick();
      const currentComponentRef = this.$refs[this.currentTabComponent];
      if (currentComponentRef && typeof currentComponentRef.getDetailsData === 'function') {
        currentComponentRef.getDetailsData();
      } else {
        console.warn(`Component ${this.currentTabComponent} is not found or does not have a getDetailsData method.`);
      }
    },
    // 初始化地图
    initMap() {

    }
  },
};
</script>


<style scoped lang="scss">
@mixin u-flex($flexD, $alignI, $justifyC) {
  display: flex;
  flex-direction: $flexD;
  align-items: $alignI;
  justify-content: $justifyC;
}

::v-deep {
  .tabs .el-tabs__item {
    padding: 0 20px !important;
  }

  .el-tabs__nav-wrap::after {
    height: 1px;
  }

  .el-tabs__item {
    height: 45px;
    line-height: 45px;
  }
}

.app-container {
  min-height: calc(100vh - 110px);
  padding: 0 20px;
}

.aside-box {
  background: #fff;
  padding: 0 20px 0 0;
  color: #5b5e65;
  font-size: 12px;
  border-right: 1px solid #f0f2f5;
  margin-bottom: 0;

  &-user {
    @include u-flex(row, flex-start, flex-start);
    border-bottom: 1px dashed #e5e5e5;
    padding-bottom: 20px;
    margin-bottom: 12px;

    &-avatar {
      flex-shrink: 0;
      margin-top: 10px;
    }

    &-right {
      flex: 1;
      padding-left: 10px;
      color: #343434;
      font-size: 14px;

      i {
        margin-left: 4px;
      }
    }

    &-phone {
      color: #727272;
      font-size: 12px;
    }
  }

  &-bodyinfo {
    height: 40px;
    @include u-flex(row, center, space-between);
  }

  &-equipment {
    border-top: 1px dashed #e5e5e5;
    border-bottom: 1px dashed #e5e5e5;
    padding-bottom: 20px;

    &-title {
      color: #999;
      line-height: 12px;
    }

    &-num {
      font-size: 14px;
      color: #343434;
      line-height: 14px;
      margin-top: 15px;
    }
  }

  .equipment {
    &-box {
      padding: 20px 0;
    }

    &-body {
      padding: 10px;
      @include u-flex(row, center, flex-start);
      border-radius: 4px;
      background: #ebeeee;

      &-img {
        height: 52px;
        width: 52px;
        margin-right: 7px;
        flex-shrink: 0;

        img {
          height: 100%;
          width: none;
          object-fit: contain;
        }
      }

      &-name {
        color: #2284ff;
        font-size: 14px;
      }

      &-other img {
        width: 16px;
        height: 10px;
      }
    }

    &-day {
      margin: 15px 0;

      span {
        color: #2284ff;
      }
    }

    &-btn {
      @include u-flex(row, center, space-between);
    }
  }
}

.el-main {
  background-color: #fff;
  color: #333;
  // line-height: 160px;
  padding: 0;
}
::v-deep .el-main::-webkit-scrollbar {
    width: 0;
    display: none;  /* Chrome, Safari and Opera */
  }

body>.el-container {
  margin-bottom: 40px;
}

.el-container:nth-child(5) .el-aside,
.el-container:nth-child(6) .el-aside {
  line-height: 260px;
}

.el-container:nth-child(7) .el-aside {
  line-height: 320px;
}

.device-details {
  padding: 20px;
}

.main-container {
  display: flex;
}

.basic-info {
  padding-right: 20px;
}

.details {
  flex: 1;
}

.bold-text {
  font-family: Anton-Regular;
  font-size: 20px;
}

.tab-content {
  margin-top: 20px;

  &-navitem {
    border-radius: 4px;
    min-height: 70px;
    box-shadow: 0 0 10px rgba(1, 24, 54, 0.1);
    font-size: 14px;
    color: #606165;
    padding: 6px 10px 5px 10px;

    &-title {
      line-height: 16px;
      margin-right: 10px;
      padding-left: 15px;
      border-left: 4px solid #2284ff;
      margin-bottom: 13px;
    }

    &-con {
      display: flex;
      flex-direction: row;
      align-items: center;
      justify-content: space-between;
    }

    &-icon {
      width: 40px;
      height: 40px;
    }
  }

  &-map {
    width: calc(100% - 20px);
    height: 500px;
  }
}

.overview-content {
  text-align: left;
  /* 左对齐 */
  margin-left: 20px;
  /* 为了不紧贴左边缘，添加一些内边距 */
}

/* .chart-container { */
/* width: 100%; */
/* 设置宽度为 100% */
/* height: 400px; */
/* 设置高度为 400px，您可以根据需要调整 */
/* margin-top: 20px; */
/* } */

.chart-container {
  width: 100%;
  height: 400px;
  /* 确保足够空间显示标签 */
}

.data-summary-label {
  margin-right: 10px;
  /* 适当调整右边距以创建所需的空间 */
}

.tab-content-title {
  height: 50px;
  font-size: 16px;
  color: #2284ff;
  letter-spacing: 0;
  line-height: 50px;
  font-weight: 700;
  background-color: #fff;
  padding-left: 15px;
  display: flex;
  align-items: center;

  &-date {
    margin-left: 20px;
  }

  &-icon {
    width: 13px;
    height: 20px;
    margin-right: 10px;
  }

  &-left {
    display: flex;
    align-items: center;
  }

  &-right {
    font-size: 14px;
    color: #999;
    width: 28px;
    height: 28px;
    text-align: center;
    line-height: 28px;
    cursor: pointer;
  }
}

.switch-container {
  position: absolute;
  top: 23px; /* 可根据需求调整 */
  right: 27px; /* 可根据需求调整 */
  z-index: 1000; /* 确保在其他元素上方 */
}

</style>
