<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>
      <div v-show="!detailsType" ref="heartrateChart" style="width: 841px; height: 320px"></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" 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 class="heartrate-sport">
        <div class="heartrate-sport-l" style="margin-left: 15px">
          <div class="box-title fz15">运动心率</div>
          <div class="heartrate-sport-lechart">
            <div ref="sportHeartrate" style="width: 100%;height: 100%;"></div>
          </div>
        </div>
        <div class="heartrate-sport-r" style="margin-left: 15px">
          <div class="box-title fz15">异常心率</div>
          <div class="heartrate-sport-rechart">
            <el-empty description="暂无数据" image-size="70" v-if="sportChartOption.series[0].data.length == 0"></el-empty>
            <div v-else>tu</div>
          </div>
        </div>
      </div> -->
      <!-- 列表展示 -->
      <div v-show="detailsType">
        <el-table :data="dataList">
          <el-table-column type="index" label="序号" align="center"/>
          <el-table-column label="时间" align="center" prop="time" />
          <el-table-column label="脉搏" align="center" prop="pulseRate" />
        </el-table>
        <pagination v-show="(dataListTotal > 0) && detailsType" :total="dataListTotal" :page.sync="tqueryParams.pageNum" :limit.sync="tqueryParams.pageSize" @pagination="getTableList"/>
      </div>
    </div>
  </template>
  
  <script>
  import * as echarts from "echarts";
  import { queryPulseDate } from "@/api/watch/deviceInfo";
  export default {
    props: {
      deviceId: {
        type: String || Number,
        default: "",
      },
      detailsType: { 
        type: Boolean,
        default: false
      }
    },
    data() {
      return {
        dataList:[],
        tqueryParams: {
          pageNum: 1,
          pageSize: 10,
        },
        dataListTotal: 0,
        avgBpm:'',
        maxBpm:'',
        minBpm:'',
        currentDate: this.parseTime(new Date(), "{y}-{m}-{d}"),
        currentDatePicker: "",
        exportLoading: false,
        chart: null,
        chartOptions: {
          tooltip: {
            trigger: "axis",
            axisPointer: {
              type: "line",
            },
          },
          grid: {
            top: "5%",
            left: "7%",
            bottom: "10%",
            right: "7%"
          },
          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: {
              fontWeight: "bold",
              color: "#999999",
              formatter: (value) => {
                return this.parseTime(value, "{h}:{i}");
              },
            },
          },
          yAxis: {
            type: "value",
            min: 0,
            max: 200,
            interval: 20,
            axisLine: {
              show: false,
            },
            splitLine: {
              show: true,
              lineStyle: {
                type: "dashed",
              },
            },
            axisTick: {
              show: false,
            },
            axisLabel: {
              color: "#999999",
              fontWeight: "bold",
            },
          },
          series: [
            {
              data: [],
              type: "line",
              smooth: true,
              symbol: "none",
              lineStyle: {
                color: "#de5d36", //改变折线颜色
              },
              areaStyle: {
                opacity: 0.8,
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  {
                    offset: 0,
                    color: "#ffd2c3",
                  },
                  {
                    offset: 1,
                    color: "#fff",
                  },
                ]),
              },
            },
          ],
        },
        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: {
      datePickerchange() {
        this.currentDate = this.currentDatePicker || this.parseTime(new Date(), "{y}-{m}-{d}");
        this.getDetailsData()
      },
      initChart() {
        const chartElement = this.$refs.heartrateChart;
        const sportChartElement = this.$refs.sportHeartrate;
        if (chartElement) {
          this.chart = echarts.init(chartElement);
          this.seChartOptions()
        }
        if (sportChartElement) {
          this.sportChart = echarts.init(sportChartElement);
          this.sportChart.setOption(this.sportChartOption);
        }
      },
      seChartOptions() {
        this.chartOptions.xAxis.min = this.currentDate + ' 00:00:00'
        this.chartOptions.xAxis.max = this.currentDate + ' 23:59:59'
        this.chart.setOption(this.chartOptions);
      },
      // 获取脉搏折线图
      getDetailsData() {
        queryPulseDate(this.currentDate, this.deviceId)
          .then((response) => {
            if (response && response.data) {
              // console.log("------------------" + JSON.stringify(response.data, null, 2) )
              const data = response.data.map((item) => ({
                name: item.time,
                value: [
                  new Date(item.time).getTime(), // 确保时间为毫秒时间戳
                  item.pulseRate,
                ],
              }));
              
              // 更新 chartOptions.series 数据
              this.chartOptions.series[0].data = data;
              this.getTableList()
              // 更新图表
              if (this.detailsType == false) {
                this.initChart()
              }
            } else {
              console.warn("心率数据返回为空或格式不正确:", response);
            }
          })
          .catch((error) => {
            console.error("获取心率数据失败:", error);
          });
      },
      getTableList() {
        let list = this.chartOptions.series[0].data.map(item=>({
          time: item.name,
          pulseRate: item.value[1]
        }))

        this.dataListTotal = list.length
        const start = (this.tqueryParams.pageNum - 1) * this.tqueryParams.pageSize;
        const end = start + this.tqueryParams.pageSize;
      
        this.dataList = list.slice(start, end);
      },
    },
  };
  </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;
    }
    &-lechart {
      width: 490px;
      height: 300px;
    }
    &-rechart {
      width: 100%;
      @include u-flex(row, center, center);
    }
  }
  </style>