<style lang="less">
page {
    background-color: #ebf5fa;
}

.page-container {
    width: 100%;
    // height: 100%;
    box-sizing: border-box;
    padding: 0 48rpx;
    position: relative;
    font-family: PingFang SC;
    font-size: 24rpx;
    .portraitTop {
        position: fixed;
        display: flex;
        width: 40px;
        height: 32px;
        align-items: center;
        font-size: 22px;
        padding-left: 5px;
        .leftvan {
        }
    }
    .energyHead {
        padding-top: 48rpx;
        padding-bottom: 48rpx;
        display: flex;
        justify-content: space-between;
        align-items: center;
        .totalEnergy {
            display: flex;
            flex-direction: column;
            justify-content: flex-end;
            line-height: 1;
            .name {
                font-family: PingFang SC;
                font-size: 28rpx;
                font-weight: 400;
                line-height: 44rpx;
                color: #626c78;
            }
            .value_box {
                display: flex;
                align-items: center;
                .value {
                    font-family: Persagy2.0;
                    font-size: 64rpx;
                    font-weight: 600;
                    line-height: 80rpx;
                    color: #1b2129;
                }
                .imgst {
                    width: 32rpx;
                    height: 32rpx;
                    margin-left: 8rpx;
                }
            }
        }
        .rightFloat {
            line-height: 1;
            display: flex;
            flex-direction: row;
            align-items: flex-end;
            .todayAdd {
                margin-right: 44rpx;
            }
            .ranking {
            }
            .name {
                font-family: PingFang SC;
                font-size: 28rpx;
                font-weight: 400;
                line-height: 44rpx;
                color: #626c78;
            }
            .value {
                display: flex;
                align-items: center;
                font-family: Persagy2.0;
                font-size: 32rpx;
                font-weight: 600;
                line-height: 48rpx;
                color: #000;
                .headArrow {
                    width: 32rpx;
                    height:32rpx;
                    margin-left: 8rpx;
                }
            }
        }
    }
    .quotaCard {
        background: #fff;
        width: 100%;
        box-sizing: border-box;
        height: 270rpx;
        padding: 36rpx 36rpx 0 36rpx;
        border-radius: 15rpx;
        margin-bottom: 36rpx;
        .headTitle {
            display: flex;
            justify-content: space-between;
            align-items: baseline;
            .text {
                font-weight: 600;
                font-size: 32rpx;
                color: #000;
            }
            .recordButton {
                font-size: 22rpx;
                height: 22px;
                color: #4d5262;
                display: flex;
                align-items: center;
            }
        }
        .quotaCont {
            height: 190rpx;
            // padding-right: 30rpx;
            display: flex;
            justify-content: space-between;
            align-items: center;
            .eachItem {
                // width: 32%;
                .name {
                    display: flex;
                    align-items: center;
                    font-size: 26rpx;
                    font-weight: 400;
                    line-height: 40rpx;
                    color: #8B949E;
                }
                .bottomValue {
                    margin-top: 8rpx;
                    line-height: 1;
                    display: flex;
                    align-items: flex-start;
                    .value {
                        font-family: Persagy2.0;
                        font-size: 32rpx;
                        font-weight: 600;
                        line-height: 48rpx;
                        color: #1B2129;
                    }
                    .unit {
                        margin-left: 6rpx;
                        font-family: PingFang SC;
                        font-size: 18rpx;
                        font-weight: 400;
                        line-height: 32rpx;
                        color: #8B949E;
                    }
                }
            }
        }
        .lightQuotaCont {
            justify-content: center;
            .firstLightItem {
                margin-right: 70px;
            }
        }
    }
    .lightCard {
        margin-bottom: 26rpx;
    }
    .chartCard {
        .header {
            height: 34px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            color: #4d5262;
            .chartTitle {
                display: flex;
                align-items: center;
                font-size: 20rpx;
                color: #626C78;
                .cpic {
                    width: 20rpx;
                    height: 6rpx;
                    border-radius: 6rpx;
                    margin-right: 6px;
                }
                .cpic:nth-of-type(n + 2) {
                    margin-left: 20px;
                }
                .highPic {
                    background-color: #e5574f;
                }
                .lowPic {
                    background-color: #5e8bcf;
                }
                .comfortPic {
                    height: 10rpx;
                    width: 10rpx;
                    border-radius: 4rpx;
                    background: #3DCBCC;
                }
                .otherPic {
                    background-color: #e89e32;
                }
            }
            .recordButton {
                display: flex;
            }
            .seasonChange {
                display: flex;
                align-items: center;
                background: rgba(196, 196, 196, 0.2);
                border-radius: 34rpx;
                //color: #9fb7cd;
                color: #626C78;
                font-size: 25rpx;
                .seasonItem {
                    width: 120rpx;
                    height: 68rpx;
                    line-height: 68rpx;
                    text-align: center;
                }
                .sel {
                    background: #fff;
                    border-radius: 34rpx;
                    color: #000000;
                }
            }
        }
        .chartBox {
            width: 100%;
            height: 440rpx;
            position: relative;
            z-index: 2;
            overflow: hidden;
            movable-area {
                width: 100%;
                height: 100%;
                position: relative;
            }
            movable-view {
                width: 200%;
                height: 100%;
                color: #fff;
                .shiUl {
                    width: 100%;
                    color: black;
                    display: flex;
                    .shili {
                        width: 100px;
                        height: 60px;
                    }
                }
                .f2-chart {
                    width: 100%;
                    height: 440rpx;
                }
            }
        }
    }
    .temperatureCard {
        padding: 32rpx 0 0 42rpx;
        background: #22459d;
        box-sizing: border-box;
        height: 250rpx;
        border-radius: 15rpx;
        margin-top: 6rpx;
        margin-bottom: 40rpx;
        position: relative;
        color: #fff;
        &.nocomfortType {
            padding: 0;
            line-height: 250rpx;
            text-align: center;
            font-size: 44rpx;
        }
        &.good {
            background: #5bcaea;
        }
        &.heat {
            background: #c0c0a4;
        }
        .headTitle {
            font-size: 22rpx;
        }
        .tempValue {
            font-size: 47rpx;
            font-weight: 600;
            margin-top: 4rpx;
            font-family: Montserrat;
        }
        .firstText {
            font-size: 24rpx;
            margin-top: 24rpx;
        }
        .secondText {
            font-size: 24rpx;
            color: #fff;
            font-weight: 600;
            margin-top: 10rpx;
        }
        .bearImg {
            position: absolute;
            bottom: 0;
            right: -20rpx;
            width: 270rpx;
            height: 250rpx;
        }
    }
    .zero {
        background: #9fb7cd;
        .bearImg {
            position: absolute;
            top: 10rpx;
            right: 35rpx;
            width: 192rpx;
            height: 230rpx;
        }
    }
    .dialogWrap {
        width: 100%;
        margin: 0 auto;
        padding-top: 30px;
        font-size: 34rpx;
        background: #fff;
        .title {
            text-align: center;
            color: #000;
        }
        .center {
            padding: 18px 0 24px 42px;
            color: rgba(0, 0, 0, 0.5);
            font-size: 28rpx;
            line-height: 22px;
        }
        .bottom {
            text-align: center;
            height: 55px;
            line-height: 55px;
            border-top: 1px solid rgba(0, 0, 0, 0.1);
            color: #000;
        }
    }
    .logo-text {
        display: flex;
        justify-content: center;
        width: 100%;
        height: 24rpx;
        padding: 98rpx 0 80rpx;
        margin-top: 240rpx;
    }
}
</style>

<template>
    <div
        class="page-container"
        style="padding-top:{{topBarHeight}}px;"
    >
        <div class="energyHead">
            <div
                class="totalEnergy"
                @tap="showAllEnergy"
            >
                <div class="name">我的{{ carbonCreditText }}</div>
                <div class="value_box">
                    <div class="value">{{energyHeadData.totalPoints||energyHeadData.totalPoints==0?energyHeadData.totalPoints:'--'}}</div>
                    <image
                        class="imgst"
                        src="{{h5StaticPath}}/icon-arrow-right.svg"
                    />
                </div>
            </div>
            <div class="rightFloat">
                <div
                    class="todayAdd"
                    @tap="showTodayEnergy"
                >
                    <div class="name">今日新增</div>
                    <div class="value"><span>+</span>{{energyHeadData.intergral||energyHeadData.intergral==0?energyHeadData.intergral:'--'}}
                        <image
                        class="headArrow"
                        src="{{h5StaticPath}}/icon-arrow-right.svg"
                    />
                    </div>
                </div>
                <div
                    class="ranking"
                    @tap="showRanking"
                >
                    <div class="name">排名</div>
                    <div class="value">{{energyHeadData.level||energyHeadData.level==0?energyHeadData.level:'--'}}
                        <image
                        class="headArrow"
                        src="{{h5StaticPath}}/icon-arrow-right.svg"
                    />
                    </div>
                </div>
            </div>
        </div>
        <block v-if="portraitModule.airConditioner">
            <div
                class="quotaCard"
                id="tempCard"
            >
                <div class="headTitle">
                    <div class="text">温度调节统计</div>
                    <!--此功能暂时不要了 <div
                        class="recordButton"
                        @tap="showAjustRecord('temp')"
                    ><span>调节记录</span>
                        <van-icon name="arrow" />
                    </div> -->
                </div>
                <div class="quotaCont">
                    <div class="eachItem">
                        <div class="name">累计开关</div>
                        <div class="bottomValue">
                            <span class="value">{{(tempTotal.adjustTotalNum||tempTotal.adjustTotalNum==0)?tempTotal.adjustTotalNum:'--'}}</span>
                            <span class="unit">次</span></div>
                    </div>
                    <div class="eachItem">
                        <div class="name">累计调高</div>
                        <div class="bottomValue">
                            <span class="value">{{(tempTotal.adjustUpNum||tempTotal.adjustUpNum==0)?tempTotal.adjustUpNum:'--'}}</span>
                            <span class="unit">次</span></div>
                    </div>
                    <div class="eachItem">
                        <div class="name">累计调低</div>
                        <div class="bottomValue">
                            <span class="value">{{(tempTotal.adjustDownNum||tempTotal.adjustDownNum==0)?tempTotal.adjustDownNum:'--'}}</span>
                            <span class="unit">次</span></div>
                    </div>
                    <div class="eachItem">
                        <div
                            class="name"
                            @click="showQuestion"
                        >
                            <span>空调节能</span>
                            <van-icon name="question-o" />
                        </div>
                        <div class="bottomValue">
                            <span class="value">{{(tempTotal.economizeEnergy||tempTotal.economizeEnergy==0)?tempTotal.economizeEnergy:'--'}}</span>
                            <span class="unit">kWh</span></div>
                    </div>
                </div>
            </div>
            <div class="chartCard">
                <div class="header">
                    <div class="chartTitle">
                        <div class="highPic cpic"></div><span>调高</span>
                        <div class="lowPic cpic"></div><span>调低</span>
                        <div class="comfortPic cpic"></div><span>舒适温度</span>
                    </div>
                    <div
                        class="seasonChange"
                        @click="seasonChange"
                    >
                        <div
                            class="seasonItem"
                            :class="{'sel':seasonType == 'Cooling'}"
                        >供冷季</div>
                        <div
                            class="seasonItem"
                            :class="{'sel':seasonType == 'Warm'}"
                        >供暖季</div>
                    </div>
                </div>
                <div
                    class="chartBox"
                    @click.stop=""
                >
                    <ff-canvas
                        class="f2-chart"
                        onInit="{{onInitChart}}"
                        v-if="tempChartDataLength"
                    ></ff-canvas>
                </div>
            </div>
            <div
                class="temperatureCard zero"
                v-if="comfortType=='zero'||comfortType=='little'"
            >
                <div class="headTitle">您的调节记录</div>
                <div class="tempValue"><span>{{adjustNum}}</span></div>
                <div class="firstText">{{comfortTextObj.firstLine}}</div>
                <div>
                    <image
                        class="bearImg"
                        :src="comfortTextObj.img"
                        mode="widthFix"
                    />
                </div>
            </div>
            <div
                class="temperatureCard"
                :class="{'good':comfortType=='good','heat':comfortType=='heat'}"
                v-else
            >
                <div class="headTitle">您的舒适温度</div>
                <div
                    class="tempValue"
                    v-if="!highComfortTemp&&!lowComfortTemp"
                ><span>--</span></div>
                <div
                    class="tempValue"
                    v-else
                ><span v-if="lowComfortTemp">{{lowComfortTemp}}</span><span v-if="lowComfortTemp">℃</span><span v-if="highComfortTemp&&lowComfortTemp">-</span><span v-if="highComfortTemp">{{highComfortTemp}}</span>
                    <span v-if="highComfortTemp">℃</span></div>
                <div class="firstText">{{comfortTextObj.firstLine}}</div>
                <div class="secondText">{{comfortTextObj.secondLine}}</div>
                <div>
                    <image
                        class="bearImg"
                        :src="comfortTextObj.img"
                        mode="widthFix"
                    />
                </div>
            </div>
        </block>
        <block v-if="portraitModule.light">
            <div
                class="quotaCard lightCard"
                id="lightCard"
            >
                <div class="headTitle">
                    <div class="text">开关照明统计</div>
                    <div
                        class="recordButton"
                        @tap="showAjustRecord('light')"
                    ><span>调节记录</span>
                        <van-icon name="arrow" />
                    </div>
                </div>
                <div class="quotaCont lightQuotaCont">
                    <div class="eachItem firstLightItem">
                        <div class="name">累计开启</div>
                        <div class="bottomValue">
                            <span class="value">{{(lightTotal.openNum||lightTotal.openNum==0)?lightTotal.openNum:'--'}}</span>
                            <span class="unit">次</span></div>
                    </div>
                    <div class="eachItem">
                        <div class="name">累计关闭</div>
                        <div class="bottomValue">
                            <span class="value">{{(lightTotal.closeNum||lightTotal.closeNum==0)?lightTotal.closeNum:'--'}}</span>
                            <span class="unit">次</span></div>
                    </div>
                    <!-- <div class="eachItem">
                    <div class="name">照明节能</div>
                    <div class="bottomValue">
                        <span class="value">{{lightTotal.openNum}}</span>
                        <span class="unit">kWh</span></div>
                </div> -->
                </div>
            </div>
            <div class="chartCard">
                <div
                    class="header"
                    style="display:none"
                >
                    <div class="chartTitle">
                        <div class="highPic cpic"></div><span>开灯</span>
                        <div class="lowPic cpic"></div><span>关灯</span>
                        <div class="otherPic cpic"></div><span>关闭其他</span>
                    </div>

                </div>
                <div class="chartBox">
                    <!-- <movable-area scale-area="true">
                    <movable-view
                        direction="horizontal"
                        inertia="true"
                        out-of-bounds="false"
                        scale="false"
                        scale-value="1"
                    >
                        <ff-canvas
                            class="f2-chart"
                            onInit="{{onInitChart2}}"
                        ></ff-canvas>
                    </movable-view>
                </movable-area> -->
                    <ff-canvas
                        class="f2-chart"
                        onInit="{{onInitChart2}}"
                    ></ff-canvas>
                </div>
            </div>
        </block>
        <!-- <image
            class="logo-text"
            src="{{h5StaticPath}}/page-home/tenatslink.svg"
        ></image> -->
        <van-popup
            overlay-style="background: rgba(0, 0, 0, 0.4)"
            custom-style="width: 85%"
            round
            :show="dialogShow"
            @close="dialogClose"
        >
            <div class="dialogWrap">
                <div class="title">空调节能</div>
                <div class="center">
                    <p>夏季设定值调高一度，冬季调低两度；</p>
                    <p>相当于省电20%；</p>
                    <p>如果夏季空调温度都设定在26℃以上；</p>
                    <p>如果冬季空调温度都设定在21℃以下；</p>
                    <p>节省的电力是相当可观的</p>
                </div>
                <div
                    class="bottom"
                    @click="dialogClose"
                >我知道了</div>
            </div>

        </van-popup>
    </div>
</template>

<script>
var _ = require('lodash')
import wepy from '@wepy/core'
import store from '@/store'
import config from '@/config'
import moment from 'moment'
import { mapState } from '@wepy/x'
import { queryTotalIntegral, queryTotalPortraitLight, queryPortraitLightUser, queryPortraitTempUserTotal, queryPortraitTempUserDetail, getSeasonBySeasonDate } from '@/packagesEnv/api/portrait'
import { saveCompanyConfig } from '@/service/companyConfig'
import { carbonCredit } from '../common.js'

var tempChartData = []
var highComfortTemp = null
var lowComfortTemp = null
function onInitChart(F2, config) {
  var chart = new F2.Chart({ ...config,
        // appendPadding: [20, 30, 15, 5]
    padding: [20, 20, 30, 22]
        // pixelRatio: window.devicePixelRatio
  })
  var data = [{
    temperature: '8',
    num: 15,
    type: 'up'
  }, {
    temperature: '8',
    num: -3,
    type: 'down'
  }, {
    temperature: '18.5',
    num: 12,
    type: 'up'
  }, {
    temperature: '18.5',
    num: -3,
    type: 'down'
  }, {
    temperature: '19',
    num: 15,
    type: 'up'
  }, {
    temperature: '19',
    num: -5,
    type: 'down'
  }, {
    temperature: '19.5',
    num: 11,
    type: 'up'
  }, {
    temperature: '19.5',
    num: -5,
    type: 'down'
  }, {
    temperature: '24',
    num: -2,
    type: 'down'
  }]
  chart.clear() // 清除
  chart.source(tempChartData, {
    temperature: {
            // type: 'linear',
            // tickInterval: 0.5 // 坐标 间隔0.5
    },
    num: {
      type: 'linear',
            // tickInterval: 15,
      min: 0
            // formatter: function formatter(val) {
            //     return Math.ceil(val);
            // }
    }
  })
    // 坐标轴
  var lastLabel = null
  chart.axis('num', {
    grid: {
      lineDash: null,
      lineWidth: 1,
      stroke: 'rgba(196, 196, 196, 0.6)'
    },
        // labelOffset: 12, // 偏移量
        // position: 'left',
    label: (text, index, total) => {
      console.log('label', text, index, total)
      const cfg = {
        fill: '#4D5262'
      }
      if (text == 'num') {
        cfg.text = ''
      }
      lastLabel = text
      return cfg
    }
  })
  console.log('highComfortTemp,lowComfortTemp', highComfortTemp, lowComfortTemp)
    // 坐标轴
  chart.axis('temperature', {
        // position: 'bottom',
    grid: (text, index, total) => {
      if (text == highComfortTemp) { // 20 处的栅格线着重显示
        return {
          lineWidth: 2,
          stroke: '#3DCBCC'
        }
      }
      if (text == lowComfortTemp) { // 22 处的栅格线着重显示
        return {
          lineWidth: 2,
          stroke: '#3DCBCC'
        }
      }
    },
    label: (text, index, total) => {
      const cfg = {
        fill: '#4D5262'
      }
      if (text == 'temperature') {
        cfg.text = ''
      }
      return cfg
    }
  })
  chart.legend(false)
  chart.tooltip(false) // 关闭 tooltip
  chart.interval().position('temperature*num').color('type', function (val) {
    if (val == 'up') { // 如果是上调 是这个颜色
      return '#e5574f'
    } else { // 如果是下调 是这个颜色
      return '#5e8bcf'
    }
  }).style('num', {// 柱图的样式
    radius: function radius(val) {
      return val > 0 ? [4, 4, 0, 0] : [0, 0, 4, 4]
    }
  }).adjust('stack').size(8)
  chart.guide().text({
    top: false,
    limitInPlot: true,
    position: ['max', 'min'], // 文本的起始位置，值为原始数据值，支持 callback
    content: '温度', // 显示的文本内容
    style: {
      fill: '#C4C4C4', // 文本颜色
      fontSize: '10' // 文本大小
            // fontWeight: 'bold' // 文本粗细
            // rotate: Math.PI / 4 // 文本旋转，以弧度为单位
    }, // 文本的图形样式属性
    offsetX: 10, // x 方向的偏移量
    offsetY: 12 // y 方向偏移量
  })
  chart.guide().text({
        // position: ['min', 'max'], // 文本的起始位置，值为原始数据值，支持 callback
    position: function (xScale, yScale) {
      console.log('position', xScale, yScale)
      return ['0%', '0%']
    },
    content: '次数', // 显示的文本内容
    style: {
      fill: '#C4C4C4', // 文本颜色
      fontSize: '10' // 文本大小
            // fontWeight: 'bold' // 文本粗细
            // rotate: Math.PI / 4 // 文本旋转，以弧度为单位
    }, // 文本的图形样式属性
    offsetX: -10, // x 方向的偏移量
    offsetY: -13// y 方向偏移量
  })
  if (tempChartData.length == 0) {
    chart.guide().text({
            // position: ['min', 'max'], // 文本的起始位置，值为原始数据值，支持 callback
      position: function (xScale, yScale) {
        console.log('position', xScale, yScale)
        return ['50%', '50%']
      },
      content: '暂无数据', // 显示的文本内容
      style: {
        fill: '#C4C4C4', // 文本颜色
        fontSize: '16' // 文本大小
                // fontWeight: 'bold' // 文本粗细
                // rotate: Math.PI / 4 // 文本旋转，以弧度为单位
      }, // 文本的图形样式属性
      offsetX: -10, // x 方向的偏移量
      offsetY: -13// y 方向偏移量
    })
  }

  chart.render()
  return chart
};
var lightChartData = []
var originDates = []

// const Pan = require('@antv/f2/lib/interaction/pan');
function onInitChart2(F2, config) {
    // 第二步：注册交互行为Pan
    // F2.Chart.registerInteraction('wxPan', Pan);
    // console.log('pan', Pan);
  var chart = new F2.Chart({
    ...config,
        // appendPadding: [20, 30, 15, 5]
    padding: [46, 20, 40, 20]
        // pixelRatio: window.devicePixelRatio
  })

    // var data = [];
    // for (var i = 1; i < 24; i++) {
    //      var date = i < 10 ? ('0' + i) : i;
    //     var baseData = [{
    //         date: date,
    //         num: 15,
    //         type: 'open'
    //     }, {
    //         date: date,
    //         num: 12,
    //         type: 'close'
    //     }, {
    //         date: date,
    //         num: 10,
    //         type: 'other'
    //     }];

    //     data.push(...baseData);
    // }
    // console.log('data:', data);

  chart.source(lightChartData, {
    date: {
            // values: originDates,
            // type: 'timeCate',
            //   mask: 'DD'
            // type: 'linear',
            // tickInterval: 3,
            // //tickCount: 8,
            // min: 0,
            // max: 23,
            // formatter: function formatter(val) {
            //     val = val < 10 ? ('0' + val) : val;
            //     if (val == 24) {
            //         return null;
            //     } else {
            //         return val + ':00';
            //     }
            // }
    },
    num: {// 次数
      formatter: function formatter(val) {
        return Math.ceil(val)// 取整
      }
    }
  })
    // 坐标轴
  chart.axis('num', {
    grid: {
      lineDash: null,
      lineWidth: 1,
      stroke: 'rgba(196, 196, 196, 0.6)'
    },
        // labelOffset: 12, // 偏移量
    label: (text, index, total) => {
      const cfg = {
        fill: '#4D5262'
      }
      if (text == 'num') {
        cfg.text = ''
      }
      return cfg
    }
  })
    // 坐标轴
  chart.axis('date', {
    labelOffset: 8, // 偏移量
    label: (text, index, total) => {
      const cfg = {
        fill: '#4D5262',
        textAlign: 'start',
        rotate: Math.PI / 3
      }
            // 第一个点左对齐，最后一个点右对齐，其余居中，只有一个点时左对齐
            // if (index === 0) {
            //     cfg.textAlign = 'start';
            // }
            // if (index > 0 && index === total - 1) {
            //     cfg.textAlign = 'end';
            // }
            // text = text < 10 ? ('0' + text) : text;
            // cfg.text = text + ':00';
            // if (text == 24 || text == 'date') { cfg.text = ''; }
      if (text == 'date') {
        cfg.text = ''
      }
      return cfg
    }
  })

    // chart.legend(false);
  chart.legend({ position: 'top', align: 'center', marker: { symbol: 'square', radius: 4 } })

  chart.interval().position('date*num').color('type', function (val) {
    if (val == '开灯') { // 如果是上调 是这个颜色
      return '#E5574F'
    } else if (val == '关灯') { // 如果是下调 是这个颜色
      return '#5E8BCF'
    } else { // 如果是下调 是这个颜色
      return '#E89E32'
    }
  }).style('num', {// 柱图的样式
    radius: function radius(val) {
      return [0, 0, 0, 0]
            // return val > 0 ? [4, 4, 0, 0] : [0, 0, 4, 4];
    }
  }).adjust({ type: 'dodge', marginRatio: 0.2 }).size(4)// stack 是指堆积柱
    // .adjust({ type: 'stack', }).size(7);

    // chart.guide().text({
    //     top: false,
    //     limitInPlot: true,
    //     position: ['max', 'min'], // 文本的起始位置，值为原始数据值，支持 callback
    //     content: '日期', // 显示的文本内容
    //     style: {
    //         fill: '#C4C4C4', // 文本颜色
    //         fontSize: '10' // 文本大小
    //     }, // 文本的图形样式属性
    //     offsetX: 20, // x 方向的偏移量
    //     offsetY: 12 // y 方向偏移量
    // });
  chart.guide().text({
    position: ['min', 'max'], // 文本的起始位置，值为原始数据值，支持 callback
    content: '次数', // 显示的文本内容
    style: {
      fill: '#C4C4C4', // 文本颜色
      fontSize: '10' // 文本大小
    }, // 文本的图形样式属性
    offsetX: -10, // x 方向的偏移量
    offsetY: -13// y 方向偏移量
  })
  if (lightChartData.length == 0) {
    chart.guide().text({
            // position: ['min', 'max'], // 文本的起始位置，值为原始数据值，支持 callback
      position: function (xScale, yScale) {
        console.log('position', xScale, yScale)
        return ['50%', '50%']
      },
      content: '暂无数据', // 显示的文本内容
      style: {
        fill: '#C4C4C4', // 文本颜色
        fontSize: '16' // 文本大小
                // fontWeight: 'bold' // 文本粗细
                // rotate: Math.PI / 4 // 文本旋转，以弧度为单位
      }, // 文本的图形样式属性
      offsetX: -10, // x 方向的偏移量
      offsetY: -13// y 方向偏移量
    })
  }
    // chart.tooltip(false); // 关闭 tooltip
    // chart.tooltip({
    //     // offsetX: 0, // x 方向的偏移
    //     offsetY: 0, // y 方向的偏移
    //     alwaysShow: true,
    //     triggerOn: ['touchstart', 'touchmove'], // tooltip 出现的触发行为，可自定义，用法同 legend 的 triggerOn
    //     triggerOff: 'touchend', // 消失的触发行为，可自定义
    //     showTitle: false, // 是否展示标题，默认不展示
    //     showCrosshairs: false, // 是否显示辅助线，点图、路径图、线图、面积图默认展示
    //     // crosshairsStyle: { stroke: 'rgba(0, 0, 0, 0.25)', lineWidth: 2 }, // 配置辅助线的样式
    //     // showTooltipMarker: true, // 是否显示 tooltipMarker
    //     tooltipMarkerStyle: { fill: '#fff' }, // 设置 tooltipMarker 的样式
    //     background: { radius: 2, fill: '#fff', padding: [6, 10] }, // tooltip 内容框的背景样式
    //     titleStyle: { fontSize: 20, fill: '#4d5262', textAlign: 'start', textBaseline: 'top' }, // tooltip 标题的文本样式配置，showTitle 为 false 时不生效
    //     nameStyle: { fontSize: 14, fill: '#4d5262', }, // tooltip name 项的文本样式配置
    //     valueStyle: { fontSize: 14, fill: '#4d5262', }, // tooltip value 项的文本样式配置
    //     showItemMarker: true, // 是否展示每条记录项前面的 marker
    //     itemMarkerStyle: { radius: 5, symbol: 'circle', lineWidth: 0, stroke: '#fff' }, // 每条记录项前面的 marker 的样式配置
    //     custom: false, // 是否自定义 tooltip 提示框
    //     onShow(obj) { // obj: { x, y, title, items }
    //     }, // tooltip 显示时的回调函数
    //     onHide(obj) { // obj: { x, y, title, items }
    //     }, // tooltip 隐藏时的回调函数
    //     onChange(obj) { // obj: { x, y, title, items }
    //     }, // tooltip 内容发生改变时的回调函数
    //     // crosshairsType: {String}, // 辅助线的种类
    //     // showXTip: {Boolean}, // 是否展示 X 轴的辅助信息
    //     // showYTip: {Boolean}, // 是否展示 Y 轴的辅助信息
    //     // xTip: {Object}/{Function}, // X 轴辅助信息的文本内容
    //     // yTip: {Object}/{Function, // Y 轴辅助信息的文本内容
    //     // xTipBackground: {Object}, // X 轴辅助信息的背景框样式
    //     // yTipBackground: {Object}, // Y 轴辅助信息的背景框样式
    //     //  xTipTextStyle: {Object}, // X 轴辅助信息的文本样式 {fontSize: 12, fill: '#fff',}
    //     //  yTipTextStyle: {Object}, // Y 轴辅助信息的文本样式 snap: {Boolean} // 是否将辅助线准确定位至数据点
    // });
  chart.tooltip({
    custom: true, // 自定义 tooltip 内容框
    onChange: function onChange(obj) {
            // debugger;
      const legend = chart.get('legendController').legends.top[0]
      const tooltipItems = obj.items
      const legendItems = legend.items
      console.log('tooltipItems', tooltipItems)
      console.log('legendItems', legendItems)
      const map = {}
      legendItems.forEach(function (item) {
        map[item.name] = _.clone(item)
      })
      tooltipItems.forEach(function (item) {
        const name = item.name
        const value = item.value
        if (map[name]) {
          map[name].value = value
        }
      })
      legend.setItems(_.values(map))
    },
    onHide: function onHide() {
      const legend = chart.get('legendController').legends.top[0]
      legend.setItems(chart.getLegendItems().country)
    }
  })
    // 定义进度条
    // chart.scrollBar({
    //     mode: 'x',
    //     xStyle: {
    //         backgroundColor: '#e8e8e8',
    //         fillerColor: '#808080',
    //         offsetY: -2
    //     }
    // });
    // chart.interaction('pan');

    // chart.interaction('wxPan');
  chart.render()
  return chart
};
wepy.page({
  store,
  data: {
    h5StaticPath: config.h5StaticPath + '/page-portrait',
    carbonCreditText: '',
    topBarHeight: 0,
    option1: [
            { text: '默认排序', value: 'a' },
            { text: '好评排序', value: 'b' },
            { text: '销量排序', value: 'c' }
    ],
    value1: 'a',
    onInitChart: onInitChart,
    onInitChart2: onInitChart2,
    headData: {},
    dialogShow: false,
    lightTotal: {},
    tempTotal: {},
    seasonType: '',
    comfortType: null, // 舒适类型 hardy good heat
    comfortTextObj: {},
    showTitle: '', // 随遇而安
    highComfortTemp: null,
    lowComfortTemp: null,
    tempChartDataLength: false,
    adjustNum: '',
    options: {}
  },
  computed: {
    ...mapState({ token: state => state.user.token,
      userInfo: state => state.user.userInfo,
      projectId: state => state.company && state.company.companyConfig && state.company.companyConfig.sagacareProjectId,
      energyHeadData: state => state.portrait.energyHeadData,
      portraitModule: state => state.portrait.portraitModule })
  },
  onLoad(options) {
    var _this = this
    this.queryCurrentSeason().then(function (res) {
            // console.log('queryCurrentSeason.then', res);
      _this.queryPortraitTempDetail()
    })
    this.queryTotalPortraitLight()
    this.queryPortraitLightChart()

    this.queryPortraitTempTotal()
    console.log('portraitModule', this.portraitModule)
    this.options = options
    this.carbonCreditText = carbonCredit(this.projectId)
  },
  onReady() {
    var query = wx.createSelectorQuery()
    query.select('#tempCard').boundingClientRect()
    query.select('#lightCard').boundingClientRect()
    var _this = this
    query.exec((res) => {
      console.log('query select', res, this.options)
      if (this.options.sel == 'temp') {
        var top = (res[0] && res[0].top) || 0
        wx.pageScrollTo({
          scrollTop: top,
          duration: 0
        })
      } else if (this.options.sel == 'light') {
        var top = (res[1] && res[1].top) || 0
        wx.pageScrollTo({
          scrollTop: top,
          duration: 0
        })
      }
    })
  },
  methods: {
    goPre() {
      wx.navigateBack()
    },
    setTopBarHeight(height) {
      this.topBarHeight = height
    },
    seasonChange() {
      wx.uma.trackEvent('portrait_energypoint_temptime', { key: '使用统计-节能分卡片-空调月份切换' })
      if (this.seasonType == 'Cooling') {
        this.seasonType = 'Warm'
      } else {
        this.seasonType = 'Cooling'
      }
      this.queryPortraitTempDetail()
    },
    queryCurrentSeason() {
      var param = {
        dateTime: moment().format('YYYYMMDD')
      }
      return getSeasonBySeasonDate(param).then((res) => {
        console.log('queryCurrentSeason 111', res.content[0])
        var type = (res.content[0] || {}).type
        if (type == 1 || type == 3) {
          this.seasonType = 'Cooling'
        } else {
          this.seasonType = 'Warm'
        }
        return this.seasonType
      })
    },
    queryPortraitTempTotal() { // 空调调节的统计接口
      var _this = this
      queryPortraitTempUserTotal().then((res) => {
        this.tempTotal = res.data || {}
                // this.tempTotal.totalNum = this.tempTotal.adjustDownNum + this.tempTotal.adjustUpNum;
      })
    },
    queryPortraitTempDetail() { // 空调调节的统计接口
      var _this = this
            // await this.queryCurrentSeason();
      var param = {
        criteria: {
          'seasonType': this.seasonType
        }
      }
      this.tempChartDataLength = false
      queryPortraitTempUserDetail(param).then((res) => {
        var resData = res.data || {}
        var adjustDetails = resData.adjustDetails || []

        highComfortTemp = resData.highComfortTemp || ''
        lowComfortTemp = resData.lowComfortTemp || ''
        _this.highComfortTemp = highComfortTemp
        _this.lowComfortTemp = (lowComfortTemp == highComfortTemp) ? null : lowComfortTemp

        var comfortTemp = null

        if (highComfortTemp && lowComfortTemp) {
          comfortTemp = (highComfortTemp + lowComfortTemp) / 2
        } else if (highComfortTemp && !lowComfortTemp) {
          comfortTemp = highComfortTemp
        } else if (!highComfortTemp && lowComfortTemp) {
          comfortTemp = lowComfortTemp
        }

        var chartList = []
        var adjustNum = 0
        adjustDetails.forEach(function (item) {
          if (item.temperature == 0) {
            return
          }
          var baseData = [{
            temperature: (item.temperature || 0).toString(),
            num: item.adjustUpNum,
            type: 'up'
          }, {
            temperature: (item.temperature || 0).toString(),
            num: -item.adjustDownNum,
            type: 'down'
          }]
          adjustNum = adjustNum + item.adjustUpNum + item.adjustDownNum
          chartList.push(...baseData)
        })

        var comfortType = ''
        var showTitle = ''
        var comfortTextObj = {}
                // adjustNum = 9;
                // comfortTemp=16;
        if (adjustNum == 0) {
          _this.showNum = 0
          comfortType = 'zero'
          comfortTextObj = {
            firstLine: '温度关键词 无动于衷',
                        // img: '/static/zero.png'
            img: this.h5StaticPath + '/zero.png'
          }
        } else if (adjustNum > 0 && !comfortTemp) { // 不存在舒适温度
          _this.showNum = adjustNum
          comfortType = 'little'
          comfortTextObj = {
            firstLine: '温度关键词 随遇而安',
            img: this.h5StaticPath + '/littleBest.png'
          }
        } else { // 获取舒适程度
          if (this.seasonType == 'Warm') { // 冬天
            if (comfortTemp <= 18) { // 说明耐冻
              comfortType = 'hardy'
              comfortTextObj = {
                firstLine: '耐寒能力堪比 北极熊',
                secondLine: '「落雪的日子，吃支雪糕去去火」',
                img: this.h5StaticPath + '/bear.svg'
                                // img: '/static/bear.svg'
              }
            } else if (comfortTemp > 18 && comfortTemp < 24) {
              comfortType = 'good'
              comfortTextObj = {
                firstLine: '温度适宜，享受当下',
                secondLine: '「唯独工作可以带来快乐」',
                img: this.h5StaticPath + '/duck.svg'
              }
            } else if (comfortTemp >= 24) { // 说明耐热
              comfortType = 'heat'
              comfortTextObj = {
                firstLine: '耐高温能力堪比双驼峰',
                secondLine: '「阳光海滩，喝杯奶茶添点甜」',
                img: this.h5StaticPath + '/camel.svg'
              }
            }
          } else { // 夏天
            if (comfortTemp <= 23) { // 说明耐冻
              comfortType = 'hardy'
              comfortTextObj = {
                firstLine: '耐寒能力堪比 北极熊',
                secondLine: '「落雪的日子，吃支雪糕去去火」',
                img: this.h5StaticPath + '/bear.svg'
              }
            } else if (comfortTemp > 23 && comfortTemp < 27) {
              comfortType = 'good'
              comfortTextObj = {
                firstLine: '温度适宜，享受当下',
                secondLine: '「唯独工作可以带来快乐」',
                img: this.h5StaticPath + '/duck.svg'
              }
            } else if (comfortTemp >= 27) { // 说明耐热
              comfortType = 'heat'
              comfortTextObj = {
                firstLine: '耐高温能力堪比双驼峰',
                secondLine: '「阳光海滩，喝杯奶茶添点甜」',
                img: this.h5StaticPath + '/camel.svg'
              }
            }
          }
        }
        _this.adjustNum = adjustNum
        _this.comfortType = comfortType
        _this.comfortTextObj = comfortTextObj

                // tempChartData = [{
                //     temperature: '26',
                //     num: 0,
                // }];
        tempChartData = chartList
        this.tempChartDataLength = true
      })
    },
    queryTotalPortraitLight() { // 开关照明的统计接口
      var _this = this
      queryTotalPortraitLight().then((res) => {
        this.lightTotal = res.data || {}
      })
    },
    queryPortraitLightChart() { // 开关照明的详情接口
      var _this = this
      queryPortraitLightUser().then(function (res) {
        var resList = res.content || []
        var chartList = []
        resList.sort(function (a, b) { return a.hour - b.hour })
        resList.forEach(function (item, index) {
          item.hour = item.hour < 10 ? ('0' + item.hour + ':00') : (item.hour + ':00')
          var baseData = [{
            date: item.hour,
            num: item.openNum,
            type: '开灯'
          }, {
            date: item.hour,
            num: item.closeNum,
            type: '关灯'
          }, {
            date: item.hour,
            num: item.closeOthersNum,
            type: '关闭其他'
          }]
          if (index < 5) {
            originDates.push(item.hour)
          }
          chartList.push(...baseData)
        })
        lightChartData = chartList
      })
    },

    showQuestion() {
      wx.uma.trackEvent('portrait_energypoint_clickquestion', { key: '使用统计-节能分卡片-点击问号' })
      this.dialogShow = true
    },
    dialogClose() {
      this.dialogShow = false
    },
        // queryUserIntegral() {
        //     var _this = this;
        //     var today = moment().format('YYYYMMDD');
        //     var lastMonth = moment().subtract(1, 'month').format("YYYYMM");
        //     queryTotalIntegral({
        //         date: today,
        //         month: lastMonth
        //     }).then(function (res) {
        //         console.log('queryUserIntegral', res);
        //         _this.headData = res || {};

        //     })
        // },
    showAllEnergy() { // 跳转到所有节能积分列表
      wx.uma.trackEvent('portrait_energypoint_showpoint', { key: '使用统计-节能分卡片-节能分' })
      wx.navigateTo({
        url: './energyPoint'
      })
    },
    showAjustRecord(param) { // 跳转到调节记录
      if (param == 'light') {
        wx.uma.trackEvent('portrait_energypoint_lightRecord', { key: '使用统计-节能分卡片-照明调节记录' })
      } else {
        wx.uma.trackEvent('portrait_energypoint_tempRecord', { key: '使用统计-节能分卡片-空调调节记录' })
      }

      wx.navigateTo({
        url: `./ajustRecord?from=${param}`
      })
    },
    showTodayEnergy() {
      wx.uma.trackEvent('portrait_energypoint_todayadd', { key: '使用统计-节能分卡片-今日新增' })
      wx.navigateTo({
        url: './todayPoint'
      })
    },
    showRanking() { // 跳转到排行
      wx.uma.trackEvent('portrait_energypoint_ranking', { key: '使用统计-节能分卡片-排行榜' })
      wx.navigateTo({
        url: './pointRanking'
      })
    }
  }
})
</script>

<config>
{
   
    'navigationBarBackgroundColor': '#EBF5FA',
     backgroundColor: '#EBF5FA',
    enablePullDownRefresh:false,
    'navigationBarTitleText': '',
     usingComponents: {
          "van-icon": "module:@vant/weapp/dist/icon",
          "ff-canvas": "../../vendor/antv/wx-f2",
          "van-popup": "module:@vant/weapp/dist/popup",

    },
  
}
</config>
