<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">
      <div class="sleep-time">{{ sleepHours + '小时' + sleepMinute + '分钟' }}</div>
      <div class="sleep-echarts">
        <div class="sleep-echarts-box">
          <div ref="sleepChart" style="width: 100%; height: 100% ;min-width: 783px;"></div>
        </div>
      </div>
      <div class="sleep-heart">
        <div class="sleep-heart-left">
          <div class="box-header">
            <div class="box-title fz15"></div>
            <div class="sleep-heart-num">
              {{ sleepInfo.score || '-' }}<span style="font-size: 12px">分</span>
            </div>
          </div>
          <div class="sleep-heart-echarts">
            <div ref="sportHeartrate" style="width: 100%; height: 100%"></div>
          </div>
        </div>
        <div class="sleep-heart-right">
          <div class="sleep-heart-comment">
            您的睡眠得分是:{{ sleepInfo.score || '-' }}分,请保持好的睡眠习惯哦!
          </div>
          <div class="list">
            <div class="list-item">
              <div class="list-item-row1">
                <div class="list-item-row1-left">
                  <span class="list-item-row1icon" style="background-color: #93c0fa"></span>
                  <span>浅睡</span>
                </div>
                <div>参考值:10%-40%</div>
              </div>
              <div class="list-item-row2">
                <div class="list-item-row2-left">
                  <span>{{ convertMinutes(sleepInfo.light_sleep)[0] }}</span>小时<span>{{
                    convertMinutes(sleepInfo.light_sleep)[1] }}</span>分钟
                </div>
                <div class="list-item-row2-right">偏低</div>
              </div>
            </div>
            <div class="list-item">
              <div class="list-item-row1">
                <div class="list-item-row1-left">
                  <span class="list-item-row1icon" style="background-color: #93c0fa"></span>
                  <span>深睡</span>
                </div>
                <div>参考值:10%-40%</div>
              </div>
              <div class="list-item-row2">
                <div class="list-item-row2-left">
                  <span>{{ convertMinutes(sleepInfo.deep_sleep)[0] }}</span>小时<span>{{
                    convertMinutes(sleepInfo.deep_sleep)[1] }}</span>分钟
                </div>
                <div class="list-item-row2-right">偏低</div>
              </div>
            </div>
            <div class="list-item">
              <div class="list-item-row1">
                <div class="list-item-row1-left">
                  <span class="list-item-row1icon" style="background-color: #fadeaf"></span>
                  <span>清醒</span>
                </div>
                <div>参考值:10%-40%</div>
              </div>
              <div class="list-item-row2">
                <div class="list-item-row2-left">
                  <span>{{ convertMinutes(sleepInfo.weak_sleep)[0] }}</span>小时<span>{{
                    convertMinutes(sleepInfo.weak_sleep)[1] }}</span>分钟
                </div>
                <div class="list-item-row2-right">偏低</div>
              </div>
            </div>
            <div class="list-item">
              <div class="list-item-row1">
                <div class="list-item-row1-left">
                  <span class="list-item-row1icon" style="background-color: #9899f5"></span>
                  <span>快速眼动</span>
                </div>
                <div>参考值:10%-40%</div>
              </div>
              <div class="list-item-row2">
                <div class="list-item-row2-left">
                  <span>{{ convertMinutes(sleepInfo.eyemove_sleep)[0] }}</span>小时<span>{{
                    convertMinutes(sleepInfo.eyemove_sleep)[1] }}</span>分钟
                </div>
                <div class="list-item-row2-right">偏低</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 列表展示 -->
    <div v-show="detailsType">
      <el-table :data="dataList" style="width: 100%">
        <el-table-column prop="start" label="开始时间" />
        <el-table-column prop="end" label="结束时间" />
        <el-table-column label="类型">
          <template slot-scope="scope">
            <span v-if="scope.row.type === 3">深睡</span>
            <span v-if="scope.row.type === 4">浅睡</span>
            <span v-if="scope.row.type === 6">清醒</span>
            <span v-if="scope.row.type === 7">快速眼动</span>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="(total > 0) && detailsType" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getDataPage"/>
    </div> 
  </div>
</template>

<script>
import { querySleep, exportSleeptDate,querySleepPageByDate } from "@/api/watch/deviceInfo";
export default {
  props: {
    detailsType: { 
      type: Boolean,
      default: false
    },
    deviceId: {
      type: String || Number,
      default: "",
    },
  },
  data() {
    return {
      total:0,
      dataList:[],
      queryParams:{
        pageNum: 1,
        pageSize: 10,
        deviceId:"",
        date:"",
        // startTime:"",
        // endTime:""
      },
      chartData: [],
      sleepHours: '', //睡眠时间
      sleepMinute: '',
      currentDate: this.parseTime(new Date(), "{y}-{m}-{d}"),
      currentDatePicker: "",
      type: 1,
      startTime: "2024-08-04 20:58:00",
      endTime: "2024-08-05 00:27:00",
      sleepDefaultInfo: {
        4: { name: "浅睡", color: "#93c0fa", yValue: 7 },
        3: { name: "深睡", color: "#427ff7", yValue: 3 },
        6: { name: "清醒", color: "#fadeaf", yValue: 9 },
        7: { name: "快速眼动", color: "#9899f5", yValue: 12 },
      },
      sleepInfo: {
        score: '',
        light_sleep: '',
        deep_sleep: '',
        weak_sleep: '',
        eyemove_sleep: ''
      },
      chart: null,
      chartOption: {
        tooltip: {
          show: true,
          formatter: (params) => {
            return params.name;
          },
        },
        xAxis: {
          type: "time",
          splitLine: {
            show: false,
          },
          axisLabel: {
            showMaxLabel: true,
            showMinLabel: true,
            formatter: (value) => {
              return this.parseTime(value, "{h}:{i}");
            },
          },
        },
        yAxis: {
          max: 14,
          show: false,
        },
        series: [
          {
            type: "custom",
            renderItem: (params, api) => {
              let yValue = api.value(2);
              let start = api.coord([api.value(0), yValue]);
              let size = api.size([api.value(1) - api.value(0), yValue]);
              let style = api.style();
              return {
                type: "rect",
                shape: {
                  x: start[0],
                  y: start[1],
                  width: size[0],
                  height: size[1],
                },
                style: style,
              };
            },
            data: [],
          },
        ],
      },
      sportChart: null,
      sportChartOption: {
        tooltip: {
          trigger: "item",
        },
        legend: {
          bottom: "3%",
          left: "center",
        },
        series: [
          {
            name: "睡眠",
            type: "pie",
            radius: ['40%', '60%'],
            avoidLabelOverlap: false,
            padAngle: 2,
            label: {
              show: false,
              position: "center",
            },
            emphasis: {
              label: {
                show: true,
                fontSize: 26,
                fontWeight: "bold",
                color: "",
              },
            },
            labelLine: {
              show: false,
            },
            data: [
              { value: 0, name: "浅睡", itemStyle: { color: "#93c0fa" } },
              { value: 0, name: "深睡", itemStyle: { color: "#427ff7" } },
              { value: 0, name: "清醒", itemStyle: { color: "#fadeaf" } },
              { value: 0, name: "快速眼动", itemStyle: { color: "#9899f5" } },
            ],
          },
        ],
      },
    };
  },
  mounted() {
    this.initChart();
  },
  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";
      this.queryParams.date = this.currentDate;
      querySleepPageByDate(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);
        });
    },
    // 分钟转换成小时分
    convertMinutes(val) {
      if (val) {
        const seconds = val * 60
        const hours = Math.floor(seconds / 3600); // 3600秒等于1小时
        const minutes = Math.floor((seconds % 3600) / 60); // 余数部分除以60秒得到分钟数
        return [hours, minutes];
      } else {
        return [0, 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.sleepChart;
      const sportChartElement = this.$refs.sportHeartrate;
      if (chartElement) {
        this.chart = this.echarts.init(chartElement);
        this.seChartOptions();
      }
      if (sportChartElement) {
        this.sportChart = this.echarts.init(sportChartElement);
        this.sportChart.setOption(this.sportChartOption);
      }
    },
    seChartOptions() {
      this.chartOption.xAxis.min = this.startTime;
      this.chartOption.xAxis.max = this.endTime;
      // const chartData = [
      //   { start: "2024-08-04 20:58:00", end: "2024-08-04 22:00:00", type: "1" },
      //   { start: "2024-08-04 22:00:00", end: "2024-08-04 22:58:00", type: "2" },
      //   { start: "2024-08-04 22:58:00", end: "2024-08-04 23:28:00", type: "3" },
      //   { start: "2024-08-04 23:28:00", endt: "2024-08-04 23:58:00", type: "4" },
      //   { start: "2024-08-04 23:58:00", end: "2024-08-05 00:00:00", type: "3" },
      //   { start: "2024-08-05 00:00:00", end: "2024-08-05 00:27:00", type: "1" },
      // ].map((item, index)=> {
      //   return {
      //     name: this.sleepDefaultInfo[item.type] && this.sleepDefaultInfo[item.type].name,
      //     value: [
      //       new Date(item.start).getTime(),
      //       new Date(item.end).getTime(),
      //       this.sleepDefaultInfo[item.type] && this.sleepDefaultInfo[item.type].yValue,
      //     ],
      //     itemStyle: {
      //       color: this.sleepDefaultInfo[item.type] && this.sleepDefaultInfo[item.type].color,
      //     },
      //   };
      // });
      const chartData = this.chartData.map((item, index) => {
        return {
          name: this.sleepDefaultInfo[item.type] && this.sleepDefaultInfo[item.type].name,
          value: [
            new Date(item.start).getTime(),
            new Date(item.end).getTime(),
            this.sleepDefaultInfo[item.type] && this.sleepDefaultInfo[item.type].yValue,
          ],
          itemStyle: {
            color: this.sleepDefaultInfo[item.type] && this.sleepDefaultInfo[item.type].color,
          },
        };
      });
      this.chartOption.series[0].data = chartData
      this.chart.setOption(this.chartOption);
    },

    getDetailsData() {
      querySleep(this.currentDate, this.deviceId)
        .then((response) => {
          if (response && response.data) {
            // console.log("------------------" +  JSON.stringify(response.data, null, 2));

            //更新睡眠时间
            this.startTime = response.data.startTime;
            this.endTime = response.data.endTime;
            const time = this.convertMinutes(response.data.sleepTime)
            this.sleepHours = time[0];
            this.sleepMinute = time[1];


            //更新图表
            // const data = response.data.sleepSection.map((item) => ({
            //   name: item.createTime,
            //   value: [
            //     new Date(item.createTime).getTime(), // 确保时间为毫秒时间戳
            //     item.avgBpm,
            //   ],
            // }));
            if (response.data.sleepSection != null) {
              this.chartData = response.data.sleepSection;
            } else{
              this.chartData = [];
            }
            // 更新 chartOptions.series 数据
            // this.chartOptions.series[0].data = data;
            if (this.chart) {
              this.seChartOptions()
            }

            //统计
            this.sleepInfo.score = response.data.score==null?0:response.data.score;
            
            //浅睡
            if (response.data.lightSleep != null) {
              // this.sportChartOption.series[0].data[0] = { value: response.data.lightSleep, name: '浅睡', itemStyle: { color: "#93c0fa" } };
              this.sleepInfo.light_sleep = response.data.lightSleep;

            } else{
              // this.sportChartOption.series[0].data[0] = { value: response.data.lightSleep, name: '浅睡', itemStyle: { color: "#93c0fa" } };
              this.sleepInfo.light_sleep = 0;
            }
            this.sportChartOption.series[0].data[0] = { value: response.data.lightSleep, name: '浅睡', itemStyle: { color: "#93c0fa" } };

            //深睡
            if (response.data.deepSleep != null) {
              // this.sportChartOption.series[0].data[1] = { value: response.data.deepSleep, name: '深睡', itemStyle: { color: "#427ff7" } };
              this.sleepInfo.deep_sleep = response.data.deepSleep;

            } else{
              // this.sportChartOption.series[0].data[1] = { value: response.data.deepSleep, name: '深睡', itemStyle: { color: "#427ff7" } };
              this.sleepInfo.deep_sleep = 0;
            }
            this.sportChartOption.series[0].data[1] = { value: response.data.deepSleep, name: '深睡', itemStyle: { color: "#427ff7" } };
            //清醒
            if (response.data.weakSleep != null) {
              // this.sportChartOption.series[0].data[2] = { value: response.data.weakSleep, name: '清醒', itemStyle: { color: "#fadeaf" } };
              this.sleepInfo.weak_sleep = response.data.weakSleep;

            } else{
              // this.sportChartOption.series[0].data[2] = { value: response.data.weakSleep, name: '清醒', itemStyle: { color: "#fadeaf" } };
              this.sleepInfo.weak_sleep = 0;
            }
            this.sportChartOption.series[0].data[2] = { value: response.data.weakSleep, name: '清醒', itemStyle: { color: "#fadeaf" } };
            //快速眼动
            if (response.data.eyemoveSleep != null) {
              // this.sportChartOption.series[0].data[3] = { value: response.data.eyemoveSleep, name: '快速眼动', itemStyle: { color: "#9899f5" } };
              this.sleepInfo.eyemove_sleep = response.data.eyemoveSleep;

            } else{
              // this.sportChartOption.series[0].data[3] = { value: response.data.eyemoveSleep, name: '快速眼动', itemStyle: { color: "#9899f5" } };
              this.sleepInfo.eyemove_sleep = 0;
            }
            this.sportChartOption.series[0].data[3] = { value: response.data.eyemoveSleep, name: '快速眼动', itemStyle: { color: "#9899f5" } };
            // if (this.sportChart) {
            //   this.sportChart.setOption(this.sportChartOption);
            // }

          } else {
            this.defaultChart();
            console.warn("睡眠数据返回为空", response);
          }
          if (this.sportChart) {
              this.sportChart.setOption(this.sportChartOption);
          }
        })
        .catch((error) => {
          console.error("获取睡眠数据失败:", error);
        });
    },
    // 导出
    exportData() {
      this.$confirm("是否确认导出所有用户数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.exportLoading = true;
          return exportSleeptDate({date:this.currentDate, deviceId: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 {
  width: 100%;
  box-sizing: border-box;
  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;
}

.sleep-heart {
  @include u-flex(row, flex-start, flex-start);

  &-left {
    flex-shrink: 0;
    width: 490px;
  }

  &-num {
    color: #292929;
    font-size: 16px;
  }

  &-echarts {
    width: 490px;
    height: 250px;
  }

  &-right {
    flex: 1;
    max-width: 800px;
    color: #707070;
    font-size: 12px;
  }

  &-comment {
    background-color: #f4f4f4;
    color: #292929;
    padding: 10px;
    width: 100%;
    @include u-flex(row, center, center);
  }
}

.sleep-time {
  font-weight: 700;
  font-size: 16px;
  color: #292929;
  padding-left: 12px;
}

.sleep-echarts {
  margin-top: 20px;

  &-box {
    min-width: 773px;
    max-width: 1200px;
    height: 380px;
  }
}

.list {
  &-item {
    padding: 8px 12px;
    border-bottom: 1px solid #efefef;

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

    &-row1icon {
      width: 6px;
      height: 6px;
      border-radius: 50%;
      margin-right: 6px;
      margin-left: 20px;
      background-color: #93c0fa;
      display: inline-block;
    }

    &-row2 {
      margin-top: 6px;
      @include u-flex(row, center, space-between);

      &-left {
        margin-left: 32px;

        span {
          color: #292929;
          font-size: 14px;
          font-weight: 700;
        }
      }

      &-right {
        color: #707070;
        font-size: 14px;
      }
    }
  }
}
</style>