<style lang="less"  scoped>
page {
    background-color: #eceff4;
}
.page-container {
    width: 100%;
    height: 100%;
    box-sizing: border-box;
    padding: 30rpx 44rpx;
    font-family: PingFang SC;
}
.meeting-title {
    display: flex;
    justify-content: space-between;
    align-items: flex-end;
    .meeting-title-left {
        font-size: 48rpx;
        font-weight: 400;
        line-height: 68rpx;
        color: rgba(0, 0, 0, 1);
    }
    .meeting-title-right {
        display: flex;
        font-family: Montserrat;
        font-size: 26rpx;
        font-weight: 400;
        line-height: 36rpx;
        color: rgba(77, 82, 98, 1);
    }
}
.meeting-info {
    margin-top: 60rpx;
    display: flex;
    justify-content: space-between;
    height: 212rpx;
    width: 662rpx;
    border-radius: 16rpx;
    background: rgba(255, 255, 255, 1);
    padding: 60rpx 40rpx;
    box-sizing: border-box;
    .meeting-info-item {
        .info-title {
            font-size: 26rpx;
            font-weight: 400;
            line-height: 36rpx;
            color: rgba(196, 196, 196, 1);
        }
        .info-num {
            display: flex;
            padding-top: 14rpx;
            .info-num-value {
                font-family: Montserrat;
                font-size: 46rpx;
                font-weight: 400;
                line-height: 42rpx;
                color: rgba(0, 0, 0, 1);
                margin-right: 6rpx;
            }
            .info-num-unit {
                font-size: 18rpx;
                font-weight: 400;
                line-height: 26rpx;
                color: rgba(196, 196, 196, 1);
            }
        }
    }
}
.meeting-time {
    height: 320rpx;
    width: 100%;
    margin-top: 26rpx;
    .meeting-time-legend {
        display: flex;
        .legend-item {
            display: flex;
            align-items: center;
            margin-right: 40rpx;
            .legend-item-shape {
                height: 12rpx;
                width: 30rpx;
                border-radius: 6rpx;
                background: #5e8bcf;
                margin-right: 12rpx;
                &.grey {
                    background: #9fb7cd;
                }
            }
            .legend-item-text {
                font-size: 20rpx;
                font-weight: 400;
                line-height: 28rpx;
                color: #4d5262;
            }
        }
    }
}
.meeting-often-room {
    padding: 36rpx 40rpx;
    margin-top: 48rpx;
    // height: 268px;
    border-radius: 16rpx;
    background: rgba(255, 255, 255, 1);
    .often-toom-chart {
        height: 240rpx;
        width: 100%;
    }
}
.meeting-attend {
    padding: 36rpx 40rpx;
    margin-top: 30rpx;
    // height: 276px;
    border-radius: 16rpx;
    background: rgba(255, 255, 255, 1);
    .meeting-card-item {
        display: flex;
        align-items: center;
        margin-bottom: 30rpx;
        .meeting-card-item-pic {
            margin-right: 24rpx;
            height: 64rpx;
            width: 64rpx;
            border-radius: 50%;
        }
        .meeting-card-item-name {
            font-size: 22rpx;
            font-weight: 400;
            line-height: 30rpx;
            color: rgba(77, 82, 98, 1);
        }
        .meeting-card-item-num {
            display: flex;
            align-items: center;
            .meeting-card-item-line {
                height: 10rpx;
                width: 220rpx;
                background: rgba(166, 206, 227, 1);
                border-radius: 0px 6rpx 6rpx 0px;
                &.next-line {
                    background: #1f78b4;
                }
                &.last-line {
                    background: #b2df8a;
                }
            }
            .meeting-card-item-value {
                margin-left: 14rpx;
                font-family: Montserrat;
                font-size: 22rpx;
                font-weight: 500;
                line-height: 26rpx;
                color: rgba(77, 82, 98, 1);
            }
        }
    }
}
.meeting-card-ttile {
    margin-bottom: 34rpx;
    font-size: 34rpx;
    font-weight: 600;
    line-height: 48rpx;
    color: rgba(0, 0, 0, 1);
}
.meeting-card-text {
    font-size: 30rpx;
    font-weight: 400;
    line-height: 50rpx;
    color: rgba(77, 82, 98, 1);
    &.top40 {
        margin-top: 40rpx;
    }
}
.notNum {
    height: 800rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    .notNum-text {
        margin-top: 20rpx;
        font-family: PingFang SC;
        font-size: 34rpx;
        font-weight: 400;
        line-height: 48rpx;
        color: #c4c4c4;
    }
}
.logo-text {
    display: flex;
    justify-content: center;
    width: 100%;
    height: 24rpx;
    padding: 98rpx 0 80rpx;
}
</style>

<template>
    <div class="page-container">
        <div class="meeting-title">
            <div class="meeting-title-left">
                会议室使用统计
            </div>
            <div
                class="meeting-title-right"
                @click="changeMonth"
            >
                <span>{{yearMonthText}}</span>
                <div>
                    <image
                        style="height:36rpx;width:36rpx"
                        src="{{h5StaticPath}}/page-portrait/statistics-icon-down.svg"
                    >
                    </image>
                </div>
            </div>
        </div>
        <div
            class="notNum"
            v-if="!pageFlag"
        >
            <div style="text-align: center;">
                <image
                    style="height:200rpx;width:200rpx"
                    src="{{h5StaticPath}}/page-portrait/nodata.png"
                />
                <div class="notNum-text">
                    暂无数据
                </div>
            </div>

        </div>
        <div v-if="pageFlag">
            <div class="meeting-info">
                <div
                    class="meeting-info-item"
                    v-for="(item,idx) in infoArr"
                    :key="idx"
                >
                    <div class="info-title">{{item.title}}</div>
                    <div class="info-num">
                        <div class="info-num-value">{{item.value}}</div>
                        <div class="info-num-unit">{{item.unit}}</div>
                    </div>
                </div>
            </div>
            <div class="meeting-time">
                <div class="meeting-time-legend">
                    <div class="legend-item">
                        <div class="legend-item-shape"></div>
                        <div class="legend-item-text">预约</div>
                    </div>
                    <div class="legend-item">
                        <div class="legend-item-shape grey"></div>
                        <div class="legend-item-text">参与</div>
                    </div>
                </div>
                <ff-canvas
                    id="timeF2"
                    class="time-f2-chart"
                    :onInit="timeDataChar"
                    v-if="chartFlag"
                >

                </ff-canvas>
            </div>
            <div class="meeting-often-room">
                <div class="meeting-card-ttile">常用会议室</div>
                <div class="often-toom-chart">
                    <ff-canvas
                        id="oftenRoomF2"
                        class="oftenRoom-f2-chart"
                        :onInit="oftenRoomDataChar"
                        v-if="chartFlag"
                    >
                    </ff-canvas>
                </div>
                <div class="meeting-card-text top40">
                    本月您最喜欢使用的会议室是{{oftenRoomDataNow[0].meetingName}}，共使用{{oftenRoomDataNow[0].useNum}}次，用时{{oftenRoomDataNow[0].timeHour}}{{oftenRoomDataNow[0].timeMin&&oftenRoomDataNow[0].timeMin}}。
                </div>
            </div>
            <div class="meeting-attend">
                <div class="meeting-card-ttile">参会同事统计</div>
                <div
                    class="meeting-card-item"
                    v-for="(item,idx) in personArr"
                >
                    <div class="meeting-card-item-pic">
                        <image
                            v-if="item.imgFlag"
                            class="meeting-card-item-pic"
                            :src="item.headImgUrl"
                        ></image>
                        <div v-else>
                            <van-loading
                                style="padding-top: 4px;"
                                size="24"
                                type="spinner"
                            />
                        </div>
                    </div>
                    <div>
                        <div class="meeting-card-item-name">{{item.partUserName}}</div>
                        <div class="meeting-card-item-num">
                            <div
                                class="meeting-card-item-line {{item.bgcolor}}"
                                style="width:{{item.lineWidth}}px"
                            ></div>
                            <div class="meeting-card-item-value">{{item.meetNum}}</div>
                        </div>
                    </div>
                </div>
                <div
                    class="meeting-card-text"
                    v-if="personArr.length>0"
                >
                    本月与{{personArr[0].partUserName}}共同开会次数最多，共{{personArr[0].meetNum}}次，用时{{personArr[0].timeHour}}{{personArr[0].timeMin&&personArr[0].timeMin}}。
                </div>
                <div
                    class="meeting-card-text"
                    v-if="personArr.length==0"
                >
                    本月会议，未邀请参会同事
                </div>
            </div>
            <image
                class="logo-text"
                src="{{h5StaticPath}}/page-home/tenatslink.svg"
            ></image>
        </div>

        <van-popup
            custom-style="height: 50%"
            overlay-style="background: rgba(0, 0, 0, 0.4)"
            position="bottom"
            round
            @close="visible = false"
            :show="visible"
        >
            <div>
                <monthcom
                    @checkTime="checkTime"
                    :yearMonthText="yearMonthText"
                ></monthcom>
            </div>

        </van-popup>

    </div>
</template>

<script>
import wepy from '@wepy/core';
import store from '@/store';
import config from '@/config';
import moment from 'moment';
import { mapState } from '@wepy/x';
import { checkLogin } from '@/service/user';
// import { getCompmayUsers } from '@/api/user';
import { summaryHttp, queryComsHttp, portraitMeetingUserHttp } from '@/packagesEnv/api/portrait';
let chart = null;
let oftenRoomChart = null;
let oftenRoomData = [];
let resultData = {
  data: []
}
function timeDataChar(F2, config) {
  let data = resultData.data;
  let valueTimeArr = data.map(item => { return item.valueTime });
  let maxValuetime = Math.ceil(Math.max(...valueTimeArr));
  chart = new F2.Chart({ ...config, appendPadding: [20, 30, 15, 5] });
  chart.clear();
  chart.source(data, {
    'date': {
      type: 'linear',
      tickInterval: 2,
      min: 1,
      max: 31,
      formatter: function formatter(val) {
        val = val < 10 ? ('0' + val) : val;
        return val;
      }
    },
    'valueTime': {
      type: 'linear',
      tickCount: 5,
      min: 0,
      max: maxValuetime
    }
  });
  chart.tooltip(false);
  chart.interval()
        .position('date*valueTime')
        .adjust('stack')
    // .style('name', {
    //   radius: function radius(val) {
    //     return [4, 4, 0, 0];
    //   }
    // });
  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: -4, // x 方向的偏移量
    offsetY: -20 // y 方向偏移量
  });

  chart.render();
  return chart;
}
function oftenRoomDataChar(F2, config) {
  let data = oftenRoomData;
  oftenRoomChart = new F2.Chart({ ...config, width: 220, padding: [0, 'auto', 'auto', 0], appendPadding: [15, 15, 15, 0] });
  oftenRoomChart.clear();
  oftenRoomChart.source(data, {
    percent: {
      formatter: function formatter(val) {
        return val + '%';
      }
    }
  });
  oftenRoomChart.legend({
    position: 'right',
    itemWidth: '55px',
    itemMarginBottom: 4,
    clickable: false
  });
  oftenRoomChart.tooltip(false);
  oftenRoomChart.coord('polar', {
    transposed: true,
    innerRadius: 0.8,
    radius: 1
  });
  oftenRoomChart.axis(false);
  oftenRoomChart.interval()
        .position('a*percent')
        .color('meetingName', ['#A6CEE3', '#1F78B4', '#B2DF8A', '#33A02C', '#FB9A99'])
        .adjust('stack');
  oftenRoomChart.render();
  return oftenRoomChart;
}
wepy.page({
  store,
  data: {
    h5StaticPath: config.h5StaticPath,
    infoArr: [
            { id: 'sum', title: '累计使用', value: '--', unit: '次' },
            { id: 'totalTime', title: '使用时长', value: '--', unit: '小时' },
            { id: 'avgTime', title: '平均时长', value: '--', unit: '小时/天' }
    ],
    personArr: [
    ],
    chartFlag: false,
    timeDataChar,
    oftenRoomDataChar,
    lineWidth: 180,
    oftenRoomDataNow: [],
    yearMonth: moment().add(-1, 'months').format('YYYYMM'),
    yearMonthText: moment().add(-1, 'months').format('YYYY.MM'),
    visible: false,
    pageFlag: false
  },
  computed: {
    ...mapState({
      userInfo: state => state.user.userInfo,
      token: state => state.user.token,
      userData: state => state.portrait.userData
    })
  },
  watch: {
    oftenRoomDataNow(val) {
            //
      if (val.length > 0) {
        wx.hideLoading();
        this.pageFlag = true;
      } else {
        wx.hideLoading();
        this.pageFlag = false;
      }
    },
    userData(val) {
      if (val) {
        this.getUsersFace(); // 获取头像
      }
    },
    personArr(val) {
      if (val.length > 0) {
        this.getUsersFace(); // 获取头像
      }
    }
  },

  onLoad() {
    checkLogin().then(() => {
      this.getData();
    })
    
  },
  onReady() {
  },
    //   onUnload() {
    //     this.chartFlag = true;
    //   },
  methods: {
    checkTime(val) {
      wx.uma.trackEvent('portrait_meeting_card', { key: '会议室-月份切换' });
      this.visible = !this.visible;
      this.chartFlag = false;
      this.yearMonth = val;
      this.yearMonthText = moment(this.yearMonth).format('YYYY.MM');
      this.getData();
    },
    changeMonth() {
      this.visible = !this.visible;
    },

    async  getData() {
      wx.showLoading({
        mask: true,
        title: '加载中'
      })

      await this.getPortraitMeetingUser();
      await this.getQueryComs();
      await this.getSummary();

      this.chartFlag = true;
    },
    getUsersFace() {
            /*       getCompmayUsers().then(res => {
                    let arr = [];
                    let resData = res.data;
                    for (let key in resData) {
                      arr.push(...resData[key])
                    }
                    this.personArr.forEach((item, idx) => {
                      let a = arr.filter(j => j.id === item.partUserId);
                      item.headImgUrl = a[0].headImgUrl;
                      item.imgFlag = true;
                    })
                  }) */
      if (this.personArr.length === 0 || JSON.stringify(this.userData) === '{}') return;
      let arr = [];
      let resData = this.userData;
      for (let key in resData) {
        arr.push(...resData[key])
      }
      this.personArr.forEach((item, idx) => {
        let a = arr.filter(j => j.id === item.partUserId);
        item.headImgUrl = a[0].headImgUrl;
        item.imgFlag = true;
      })
    },
    getPortraitMeetingUser() {
      let porParams = {
        criteria: {
          userId: this.userInfo.userId,
          date: this.yearMonth,
          meetingId: 'all'
        },
        orders: [
          {
            column: 'meetNum',
            asc: false            // 备注：是否asc
          }
        ],
        page: 1,
        size: 3
      };
      return portraitMeetingUserHttp(porParams).then(res => {
        this.personArr = [];
        if (!res.content) { return }
        let meetNumFlag = res.content[0].meetNum;
        res.content.forEach((item, idx) => {
          let timeArr = this.dealTime(item.meetTime);
          item.timeHour = timeArr[0];
          item.timeMin = timeArr[1] ? timeArr[1] : '';
          if (idx == 0) {
            item.lineWidth = this.lineWidth;
          } else if (idx == 1) {
            item.lineWidth = String((item.meetNum) / meetNumFlag * this.lineWidth);
            item.bgcolor = 'next-line';
          } else {
            item.lineWidth = String((item.meetNum) / meetNumFlag * this.lineWidth);
            item.bgcolor = 'last-line';
          }
        });
        res.content.forEach(item => { item.headImgUrl = ''; item.imgFlag = false });
        if (res.content[1] && res.content[0].meetNum === res.content[1].meetNum) {
          this.personArr.push(res.content[0]);
        } else {
          this.personArr = res.content;
        }
      })
    },
    getQueryComs() {
      let queParams = {
        criteria: {
          userId: this.userInfo.userId,
          date: this.yearMonth
        },
        page: 1,
        size: 5
      }
      return queryComsHttp(queParams).then(res => {
        if (!res.content) { return }
        let useNumArr = [];
        let userNumTotal = 0;
        res.content.forEach((item, idx) => {
          useNumArr.push(item.useNum);
          let timeArr = this.dealTime(item.useTime);
          item.timeHour = timeArr[0];
          item.timeMin = timeArr[1] ? timeArr[1] : '';
          item.a = '1';
        })
        for (let i = 0; i < useNumArr.length; i++) {
          userNumTotal += useNumArr[i];
        }
        res.content.forEach((item, idx) => {
          item.percent = (item.useNum / userNumTotal) * 100;
        })

        oftenRoomData = res.content
        this.oftenRoomDataNow = res.content
      })
    },
    getSummary() {
      let $lt = ''
      if (moment().format('YYYYMM') === this.yearMonth) {
        $lt = moment().add(1, 'days').format('YYYYMMDD')
      } else {
        $lt = moment(this.yearMonth).add(1, 'months').startOf('month').format('YYYYMMDD')
      }
      let sumParams = {
        userId: this.userInfo.userId,
        meeting: 'all',
        date: {
          $gte: this.yearMonth + '01',             // 开始日期
          $lt: $lt         // 结束日期 小于
        }
      };
      return summaryHttp(sumParams).then(res => {
        if (!res.content) { return }
        let resObj = res.content;
        let summaryCharArr = [];
        let summaryCharJoin = []; // 参与
        let summaryCharBook = []; // 预约

        let startMonthday = this.yearMonth + '01';
        let endMonthday = moment(this.yearMonth).endOf('month').format('YYYYMMDD');
                // 补齐坐标轴
        for (let i = Number(startMonthday); i <= Number(endMonthday); i++) {
          summaryCharArr.push({
            date: i.toString(),
            bookNum: 0,                // 预约数
            bookTime: 0,                // 预约时长，单位min
            joinNum: 0,                // 参与数
            joinTime: 0                // 参与数
          })
        }
        for (let key in resObj.days) {
          summaryCharArr.forEach((item, idx) => {
            if (item.date == key) {
              summaryCharArr[idx] = resObj.days[key];
            }
          });
        }
        summaryCharArr.forEach(item => {
          item.joinTime = Math.floor(item.joinTime / 60 * 100) / 100;
          item.bookTime = Math.floor(item.bookTime / 60 * 100) / 100;
          item.date = moment(item.date).format('DD');
          summaryCharJoin.push({
            name: 'Join',
            date: item.date,
            valueNum: item.joinNum,
            valueTime: item.joinTime,
            color: '#9FB7CD'
          })
          summaryCharBook.push({
            name: 'Book',
            date: item.date,
            valueNum: item.bookNum,
            valueTime: item.bookTime,
            color: '#5E8BCF'
          })
        })
        resultData.data = summaryCharBook.concat(summaryCharJoin)
        this.infoArr[0].value = resObj.sum;
        this.infoArr[1].value = this.dealTimeOO(resObj.totalTime);
        if (resObj.avgTime < 60) {
          this.infoArr[2].value = resObj.avgTime;
          this.infoArr[2].unit = '分钟/天';
        } else {
          this.infoArr[2].value = this.dealTimeOO(resObj.avgTime);
          this.infoArr[2].unit = '小时/天';
        }
      })
    },

    dealTime(val) {
      let timeArr = [];
      let val60 = val / 60;
      if (val60 % 1 === 0) { // 整数只取一个数
        timeArr.push(val60);
      } else {
        let timeStr = (val60).toFixed(2).toString();
        timeArr = timeStr.split('.');
        timeArr[1] = timeArr[1] + '分钟';
      }
      timeArr[0] = timeArr[0] + '小时';
      return timeArr;
    },
    dealTimeOO(val) {
      let val60 = val / 60;
      if (val60 % 1 === 0) { // 整数只取一个数
        return val60;
      } else {
        return (val60).toFixed(2);
      }
    }

  }
});
</script>


<config>
{
    'navigationBarBackgroundColor': '#eceff4',
    'navigationBarTextStyle':'black',
    'navigationBarTitleText': '',
    backgroundColor: '#eceff4',
    "usingComponents": {
        "ff-canvas": "../../vendor/antv/wx-f2",
        "van-popup": "module:@vant/weapp/dist/popup",
        "monthcom": "./components/monthcom",
         "van-loading": "module:@vant/weapp/dist/loading",
    }
    
}
</config>
