<template>
  <div>
    <div class="box-header">
      <div class="box-title boldtext">
        心率 <span style="margin-left: 14px">{{ currentDate }}</span>
      </div>
      <div>
        <el-button @click="exportData" size="small" style="margin-right: 20px"
          >导出</el-button
        >
        <el-date-picker
          size="small"
          v-model="currentDatePicker"
          type="date"
          placeholder="选择日期"
          value-format="yyyy-MM-dd"
          @change="datePickerchange"
        >
        </el-date-picker>
      </div>
    </div>
    <!-- 根据 detailsType 控制图表或列表的展示 -->
    <div v-show="!detailsType" style="min-width: 841px; height: 320px; width: 100%;">
      <!-- 图表展示 -->
      <div ref="heartrateChart" style="width: 100%; height: 100%;"></div>
      <div class="heartrate-data">
      <div class="heartrate-data-item" style="background-color: #f8fbff">
        <div class="heartrate-data-imgbox">
          <img src="@/assets/images/watchApi/xl.png" />
        </div>
        <div class="heartrate-data-right">
          <!-- <div class="heartrate-data-num">-</div> -->
          <div class="heartrate-data-num" style="color: #00bc98;">{{ avgBpm || '-'}} </div>
          <div>平均心率(bpm)</div>
        </div>
      </div>
      <div class="heartrate-data-item" style="background-color: #ffefef">
        <div class="heartrate-data-imgbox">
          <img src="@/assets/images/watchApi/xl.png" />
        </div>
        <div class="heartrate-data-right">
          <div class="heartrate-data-num">{{ maxBpm || '-'}}</div>
          <div>最大心率(bpm)</div>
        </div>
      </div>
      <div class="heartrate-data-item" style="background-color: #fff8f7">
        <div class="heartrate-data-imgbox">
          <img src="@/assets/images/watchApi/xl.png" />
        </div>
        <div class="heartrate-data-right">
          <div class="heartrate-data-num">{{ minBpm || '-'}}</div>
          <div>最小心率(bpm)</div>
        </div>
      </div>
    </div>
    </div>


    <div v-show="detailsType" class="heartrate-data">
      <!-- 列表展示 -->
      <el-table v-loading="loading" :data="dataList">
        <el-table-column type="index" label="序号" align="center"/>
        <el-table-column label="平均心率" align="center" prop="avgBpm" />
        <el-table-column label="最大心率" align="center" prop="maxBpm" />
        <el-table-column label="最小心率" align="center" prop="minBpm" />
        <el-table-column label="状态" align="center" prop="status" :formatter="statusFormatter"/>
        <el-table-column label="时间" align="center" prop="createTime" />
      </el-table>
      
    </div>
    <pagination
      v-show="(total>0) && detailsType"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getDataPage"
    />


    
    
  </div>
</template>

<script>
import * as echarts from "echarts";
import { queryByDate, exportHeartDate,queryPageByDate } from "@/api/watch/deviceInfo";
export default {
  props: {
    deviceId: {
      type: String || Number,
      default: "",
    },
    detailsType: { type: Boolean, default: false },  // 接收 detailsType 作为 prop
  },
  data() {
    return {
    // 总条数
      total: 0,
      queryParams:{
        pageNum: 1,
        pageSize: 10,
        deviceId:"",
        startTime:"",
        endTime:""
      },
        
      loading: false,// 遮罩层
      dataList:[],
      avgBpm:'',
      maxBpm:'',
      minBpm:'',
      currentDate: this.parseTime(new Date(), "{y}-{m}-{d}"),
      currentDatePicker: "",
      exportLoading: false,
      chart: null,
      chartOptions: {
        tooltip: {
          trigger: "axis",
          axisPointer: {
            label: {
              backgroundColor: "#FFFFFF",
            },
            lineStyle: {
              color: "#DE5D36",
              width: 1,
            },
          },
          backgroundColor: "rgba(255, 140, 106, 1)",
          borderColor: "#EC3B2C",
          borderWidth: 1,
          textStyle: {
            color: "#FFFFFF",
          },
          extraCssText: "box-shadow: 0 0 5px rgba(0, 0, 0, 0.3);",
          formatter: (params)=> {
            if (params[0].value != undefined) {
              return this.parseTime(params[0].value[0], "{h}:{i}") + " " + params[0].value[1] + "bpm";
            }
          },
        },
        grid: {
          bottom: "10%",
          left: "8%",
          top: "10",
        },
        xAxis: {
          type: "time",
          // min: new Date(this.currentDate + " 00:00:00").getTime(),
          // max: new Date(this.currentDate + " 23:59:59").getTime(),
          splitNumber: 6,
          // interval: 1000 * 60 * 60 * 4, // 每4小时一个标签
          axisLine: {
            show: false,
          },
          axisTick: {
            show: false,
          },
          splitLine: {
            show: false,
          },
          axisLabel: {
            color: "#999999",
            margin: 20,
            // fontSize: 14,
            fontWeight: "bold",
            formatter: (value) => {
              return this.parseTime(value, "{h}:{i}");
            },
          },
        },
        yAxis: {
          type: "value",
          min: 0,
          max: 200,
          splitNumber: 10,
          axisLine: {
            show: false,
          },
          splitLine: {
            show: true,
            lineStyle: {
              type: "dashed",
            },
          },
          axisTick: {
            show: false,
          },
          axisLabel: {
            color: "#999999",
            verticalAlign: "middle",
            align: "left",
            margin: 30,
            // fontSize: 14,
            fontWeight: "bold",
          },
        },
        series: [
          {
            data: [],
            type: "line",
            smooth: true,
            symbol: "none",
            lineStyle: {
              color: "#de5d36", //改变折线颜色
            },
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: "rgba(255, 148, 113, 1)" },
                { offset: 1, color: "rgba(255, 252, 251, 1)" },
              ]),
            },
            emphasis: {
              focus: "series",
            },
          },
        ],
      },
      sportChart: null,
      sportChartOption: {
        tooltip: {
          trigger: "item",
        },
        series: [
          {
            name: "运动心率",
            type: "pie",
            radius: ["40%", "60%"],
            avoidLabelOverlap: false,
            padAngle: 2,
            label: {
              show: false,
              position: "center",
            },
            emphasis: {
              label: {
                show: true,
                fontSize: 20,
                fontWeight: "bold",
                color: ""
              },
            },
            labelLine: {
              show: false,
            },
            data: [
              { value: 1048, name: "常规",itemStyle: {color:"#00bc98"}},
              { value: 735, name: "热身",itemStyle: {color:"#0286ff"} },
              { value: 580, name: "燃脂",itemStyle: {color:"#20fef5"} },
              { value: 484, name: "有氧",itemStyle: {color:"#8e80f2"} },
              { value: 300, name: "无氧",itemStyle: {color:"#fe9b52"} },
            ],
          },
        ],
      },
    };
  },
  methods: {
    getDataPage(){
      this.loading = true;
      this.queryParams.deviceId = this.deviceId;
      this.queryParams.startTime = this.currentDate + " 00:00:00";
      this.queryParams.endTime = this.currentDate + " 23:59:59";
      queryPageByDate(this.queryParams)
        .then((response) => {
          if (response) {
            this.dataList = response.rows;
            this.total = response.total;
            this.loading = false;
          } else {
            console.warn("心率分页数据返回为空或格式不正确:", response);
          }
        })
        .catch((error) => {
          console.error("获取心率分页数据失败:", error);
        });
    },
    statusFormatter(row, column, cellValue) {
      // 如果状态为0，则显示"正常"，否则显示其他状态
      return cellValue === 0 ? '正常' : '异常'; // 你可以根据需求修改 "异常" 为其他状态
    },
    datePickerchange() {
      this.currentDate = this.currentDatePicker || this.parseTime(new Date(), "{y}-{m}-{d}");
      if(this.detailsType){
        this.getDataPage();
        } else{
        this.getDetailsData();
      }
    },
    initChart() {
      const chartElement = this.$refs.heartrateChart;
      const sportChartElement = this.$refs.sportHeartrate;
      if (chartElement) {
        this.chart = echarts.init(chartElement);
        this.chartOptions.xAxis.min = this.currentDate + ' 00:00:00'
        this.chartOptions.xAxis.max = this.currentDate + ' 23:59:59'
        this.chart.setOption(this.chartOptions);
      }
      if (sportChartElement) {
        this.sportChart = echarts.init(sportChartElement);
        this.sportChart.setOption(this.sportChartOption);
      }
    },
    // 获取心率折线图
    getDetailsData() {
      queryByDate(this.currentDate, this.deviceId)
        .then((response) => {
          if (response && response.data) {
            // this.dataList = response.data.list
            //更新平均最大最小心率
            this.avgBpm = response.data.avg;
            this.maxBpm = response.data.max;
            this.minBpm = response.data.min;

            const data = response.data.list.map((item) => ({
              name: item.createTime,
              value: [
                new Date(item.createTime).getTime(), // 确保时间为毫秒时间戳
                item.avgBpm,
              ],
            }));
            
            // 更新 chartOptions.series 数据
            this.chartOptions.series[0].data = data;
            // 更新图表
            if (this.detailsType == false) {
              this.initChart()
            }
            
          } else {
            console.warn("心率数据返回为空或格式不正确:", response);
          }
        })
        .catch((error) => {
          console.error("获取心率数据失败:", error);
        });
    },
    // 导出数据逻辑
    exportData() {
      this.$confirm("是否确认导出所有用户数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.exportLoading = true;
          return exportHeartDate(this.currentDate, this.deviceId);
        })
        .then((response) => {
          this.download(response.msg);
          this.exportLoading = false;
        })
        .catch(() => {});
    },
  },
};
</script>

<style lang="scss" scoped>
@mixin u-flex($flexD, $alignI, $justifyC) {
  display: flex;
  flex-direction: $flexD;
  align-items: $alignI;
  justify-content: $justifyC;
}
.fz15 {
  font-size: 15px !important;
}
.boldtext {
  font-size: 16px;
  color: #292929;
  line-height: 30px;
  font-weight: 700;
}
.box-header {
  padding: 0 15px;
  @include u-flex(row, center, space-between);
  height: 50px;
}
.box-title {
  color: #292929;
  font-size: 16px;
  font-family: PingFang SC-Medium;
  padding-left: 10px;
  border-left: 4px solid #2284ff;
  line-height: 13px;
}
.heartrate-data {
  @include u-flex(row, center, space-around);
  margin-top: 30px;
  &-item {
    height: 60px;
    width: 196px;
    border-radius: 4px;
    box-shadow: 0 0 10px rgba(1, 24, 54, 0.1);
    overflow: hidden;
    @include u-flex(row, center, flex-start);
    img {
      height: 41px;
      width: 41px;
    }
  }
  &-imgbox {
    flex-shrink: 0;
    height: 60px;
    width: 60px;
    @include u-flex(row, center, center);
  }
  &-right {
    flex: 1;
    text-align: center;
    font-size: 13px;
    color: #606165;
    font-family: PingFang SC-Medium;
    background: #fff;
    height: 60px;
  }
  &-num {
    font-size: 22px;
    color: #2c2c3b;
    line-height: 38px;
  }
}
.heartrate-sport {
  @include u-flex(row, flex-start, flex-start);
  margin-top: 20px;
  &-l {
    width: 490px;
    flex-shrink: 0;
  }
  &-r {
    flex: 1;
    max-width: 720px;
  }
  &-lechart {
    width: 490px;
    height: 300px;
  }
  &-rechart {
    width: 100%;
    @include u-flex(row, center, center);
  }
}
</style>