<template>
  <div class="app-container">
    <div class="flex">
      <el-card class="area1">
        <div class="flex-col line-height">
          <div class="flex align-center justify-between">
            <div class="complete-container" style="background: linear-gradient(90deg, #78A1FF 0%, #5776FA 100%);">
              <div class="complete-title">巡检完成率</div>
              <div class="flex justify-between">
                <div class="complete-progress-text">{{ patrolRate.completed }}/{{ patrolRate.total }}</div>
                <div class="complete-scale-text">{{ patrolRate.total > 0 ? Math.round(patrolRate.completed * 100 / patrolRate.total) : 0 }}%</div>
              </div>
              <div class="complete-progress-background">
                <div class="complete-progress" v-if="patrolRate.total" :style="{width:  Math.round(patrolRate.completed * 100 / patrolRate.total)+'%'}"></div>
              </div>
            </div>
            <div class="complete-container" style="background: linear-gradient(90deg, #F2B394 0%, #EE8A8E 100%);">
              <div class="complete-title">维保完成率</div>
              <div class="flex justify-between">
                <div class="complete-progress-text">{{ upkeepRate.completed }}/{{ upkeepRate.total }}</div>
                <div class="complete-scale-text">{{ upkeepRate.total > 0 ? Math.round(upkeepRate.completed * 100 / upkeepRate.total) : 0 }}%</div>
              </div>
              <div class="complete-progress-background">
                <div class="complete-progress" v-if="upkeepRate.total" :style="{width:  Math.round(upkeepRate.completed * 100 / upkeepRate.total)+'%'}"></div>
              </div>
            </div>
<!--            <div class="complete-container" style="background: linear-gradient(90deg, #B478FC 0%, #5776FA 100%, #6E73FD 100%);">-->
<!--              <div class="complete-title">维修完成率</div>-->
<!--              <div class="flex justify-between">-->
<!--                <div class="complete-progress-text">{{ repairRate.completed }} /{{ repairRate.total }}</div>-->
<!--                <div class="complete-scale-text">{{ repairRate.total > 0 ? Math.round(repairRate.completed * 100 / repairRate.total) : 0 }}%</div>-->
<!--              </div>-->
<!--              <div class="complete-progress-background">-->
<!--                <div class="complete-progress" v-if="repairRate.total" :style="{width:  Math.round(repairRate.completed * 100 / repairRate.total)+'%'}"></div>-->
<!--              </div>-->
<!--            </div>-->
          </div>
          <div class="flex1" ref="patrol"></div>
        </div>
      </el-card>
      <el-card class="area2">
        <div class="flex align-center">
          <!--当前机房访客人数-->
          <div class="flex1 line-height visitor-container">
            <div class="chart-title-container">
              <el-image :src="require('./assets/charts-title-icon.png')"></el-image>
              <div class="chart-title-text">当前机房访客人数</div>
            </div>
            <div class="visitor-count-container">
              <div class="visitor-count">当前人数<span>{{ visitor.total }}</span>人</div>
            </div>

            <div class="visitor-title-container">
              <div class="visitor-title-icon"></div>
              <div class="visitor-title">访客人员明细</div>
            </div>
            <div class="visitor-list">
              <div class="visitor-item-container">
                <div class="visitor-item" style="background: #E6ECFE">
                  <div class="visitor-text" style="width: 70px;">姓名</div>
                  <div class="visitor-text flex1">电话</div>
                  <div class="visitor-text" style="width: 70px;">企业</div>
                </div>
                <div class="visitor-item" v-for="(item,index) in visitor.list" :key="index">
                  <div class="visitor-text" style="width: 70px;">{{ item.username }}</div>
                  <div class="visitor-text flex1">{{ item.userPhone }}</div>
                  <el-tooltip :content="item.company" placement="top">
                  <div class="visitor-text text-ellipsis" style="width: 70px; display: block; line-height: 45px; text-align: center; padding: 0 5px;">{{ item.company }}</div>
                  </el-tooltip>
                </div>
              </div>
            </div>
          </div>
          <div class="divider"></div>
          <!--月评分排行榜-->
          <div class="flex1 line-height" ref="score"></div>
        </div>
      </el-card>
    </div>
    <div class="flex">
      <el-card class="area3">
        <div class="flex align-center">
          <!--能耗统计分析-->
          <div class="flex1 line-height" ref="energyConsumption"></div>
          <div class="divider"></div>
          <!--PUE值年度曲线-->
          <div class="flex1 line-height" ref="PUE"></div>
        </div>
      </el-card>
      <el-card class="area4">
        <div class="area4 flex">
          <div class="flex1 line-height" ref="cabinet"></div>
          <div class="divider"></div>
          <div class="flex1 line-height cabinet-container">
            <div class="chart-title-container">
              <el-image :src="require('./assets/charts-title-icon.png')"></el-image>
              <div class="chart-title-text">数据机房机柜占用率排行</div>
            </div>
            <div class="cabinet-list">
              <div class="cabinet-item" v-for="(item,index) in roomUsage" :key="index">
                <div class="cabinet-index-outer">
                  <div class="cabinet-index-inner">
                    <div class="cabinet-index-text">
                      {{ index + 1 }}
                    </div>
                  </div>
                </div>
                <div class="cabinet-text flex1">{{ `${item.buildingName} ${item.floorName}  ${item.roomName}` }}</div>
                <div class="cabinet-text" style="width: 90px;">{{ `${item.used}U/${item.total}U` }}</div>
              </div>
            </div>
          </div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import {dateFormat} from "@/utils/dateUtil";

export default {
  name: "HomeIndex",
  data() {
    return {
      patrolRate: {}, // 任务完成率
      upkeepRate: {}, // 维保完成率
      repairRate: {}, // 维修完成率
      visitor: {}, // 访客
      patrol: undefined, // 巡检统计图
      score: undefined, // 评分统计图
      energyConsumption: undefined, // 能耗统计图
      PUE: undefined, // PUE统计图
      cabinet: undefined, // 机柜使用率统计图
      roomUsage: {}, // 机柜使用排行
    }
  },
  watch: {
    "$store.state.app.sidebar.opened"() {
      setTimeout(() => this.resize(), 300); // 菜单栏收缩动画有300ms
    }
  },
  mounted() {
    this.queryData();
    this.drawPatrol();
    this.drawScore();
    this.drawEnergyConsumption();
    this.drawPUE();
    this.drawCabinet();
    window.addEventListener('resize', this.resize);
  },
  destroyed() {
    window.removeEventListener('resize', this.resize);
  },
  methods: {
    queryData() {
      this.$axios.get("/v1/home/patrol/task/rate").then(data => {
        this.patrolRate = data;
      })
      this.$axios.get("/v1/home/upkeep/task/rate").then(data => {
        this.upkeepRate = data;
      })
      this.repairRate = {
        completed: 0,
        total: 0
      }
      this.$axios.get("/v1/home/visitor").then(data => {
        this.visitor = data;
      })
      this.$axios.get("/v1/home/room/usage").then(data => {
        this.roomUsage = data;
      })
    },
    drawPatrol() {
      this.$axios.get("/v1/home/patrol/task/times").then(data => {
        const actualList = data.map(item => {
          return [dateFormat("yyyy/MM/dd", new Date(item.time)), item.total - item.missed]
        })
        const totalList = data.map(item => {
          return [dateFormat("yyyy/MM/dd", new Date(item.time)), item.total]
        })
        const missedList = data.map(item => {
          return [dateFormat("yyyy/MM/dd", new Date(item.time)), item.missed]
        })
        this.patrol = echarts.init(this.$refs["patrol"])
        // 绘制图表
        this.patrol.setOption({
          // title: {text: 'PUE值年度曲线', textAlign: "center", left: "50%"},
          legend: {
            data: ['实际巡检', '计划巡检', '漏检次数'],
            bottom: "4%"
          },
          tooltip: {trigger: 'axis', valueFormatter: value => value},
          grid: {
            top: '40px',
            left: '32px',
            right: '0',
            bottom: '40px',
            containLabel: true
          },
          label: {
            show: true
          },
          xAxis: {
            type: 'time',
            axisTick: {show: true, alignWithLabel: true},
            axisLabel: {
              formatter: value => {
                return dateFormat("MM月dd日", value)
              }
            },

            boundaryGap: ['5%', '5%']
          },
          yAxis: {
            type: "value",
            name: "巡检次数",
            nameLocation: "middle",
            nameGap: 30
          },
          series: [{
            name: '实际巡检',
            type: 'line',
            symbol: 'circle',
            symbolSize: 7,
            data: actualList
          }
          // , {
          //   name: '计划巡检',
          //   type: 'line',
          //   symbol: 'diamond',
          //   symbolSize: 9,
          //   data: totalList
          // }, {
          //   name: '漏检次数',
          //   type: 'line',
          //   symbol: 'rect',
          //   symbolSize: 6,
          //   data: missedList
          // }
          ],
          color: ['#5cb85c', '#3c90f7', '#d9534f']
        });
      })
    },
    drawScore() {
      this.$axios.get("/v1/home/attendance/statistical").then(data => {
        const nameList = data.list.map(item => item.username);
        const scoreList = data.list.map(item => item.score);
        this.score = echarts.init(this.$refs["score"])
        this.score.setOption({
          title: {
            text: '{icon|}{space|}月评分排行榜',
            textStyle: {
              rich: {
                icon: {
                  backgroundColor: {
                    image: require('./assets/charts-title-icon.png')
                  },
                  height: 16,
                  width: 16,
                  verticalAlign: "top"
                },
                space: {
                  width: 14
                }
              }
            }
          },
          tooltip: {valueFormatter: value => value},
          grid: {
            left: '8%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: {
            type: 'value',
          },
          yAxis: {
            type: 'category',
            axisTick: {
              alignWithLabel: true
            },
            inverse: true,
            data: nameList
          },
          series: [{
            name: '评分',
            type: 'bar',
            barGap: 0,
            barCategoryGap: "50%",
            data: scoreList
          }],
          color: ['#3c90f7']
        });
      })
    },
    drawEnergyConsumption() {
      this.$axios.get("/v1/home/electricity/statistical").then(data => {
        const dateList = data.map(item => `${item.year}-${item.month}`);
        const electricityItList = data.map(item => item.electricityIt);
        const electricityOtherList = data.map(item => item.electricityOther);
        const electricityTotalList = data.map(item => item.electricityTotal);
        this.energyConsumption = echarts.init(this.$refs["energyConsumption"])
        this.energyConsumption.setOption({
          title: {
            text: '{icon|}{space|}能耗统计分析',
            textStyle: {
              rich: {
                icon: {
                  backgroundColor: {
                    image: require('./assets/charts-title-icon.png')
                  },
                  height: 16,
                  width: 16,
                  verticalAlign: "top"
                },
                space: {
                  width: 14
                }
              }
            }
          },
          legend: {
            data: ['IT用电量', '其他用电量', '总用电量'],
            bottom: "0%"
          },
          tooltip: {valueFormatter: value => value},
          xAxis: {
            type: 'category',
            axisTick: {show: true, alignWithLabel: true},
            data: dateList
          },
          yAxis: {},
          series: [{
            name: 'IT用电量',
            type: 'bar',
            barGap: 0,
            barCategoryGap: "50%",
            data: electricityItList
          },{
            name: '其他用电量',
            type: 'bar',
            barGap: 0,
            barCategoryGap: "50%",
            data: electricityOtherList
          }, {
            name: '总用电量',
            type: 'bar',
            barGap: 0,
            barCategoryGap: "50%",
            data: electricityTotalList
          }],
          color: ['#3c90f7', '#3cb85c', '#55bfc0']
        });
      });
    },
    drawPUE() {
      this.$axios.get("/v1/home/electricity/statistical").then(data => {
        const dateList = data.map(item => `${item.year}-${item.month}`);
        const pueList = data.map(item => Number(((item.electricityTotal || 0) - (item.electricityOther || 0)) / item.electricityIt).toFixed(2));
        this.PUE = echarts.init(this.$refs["PUE"])
        // 绘制图表
        this.PUE.setOption({
          title: {
            text: '{icon|}{space|}PUE值年度曲线',
            textStyle: {
              rich: {
                icon: {
                  backgroundColor: {
                    image: require('./assets/charts-title-icon.png')
                  },
                  height: 16,
                  width: 16,
                  verticalAlign: "top"
                },
                space: {
                  width: 14
                }
              }
            }
          },
          legend: {
            data: ['数据'],
            bottom: "4%"
          },
          tooltip: {trigger: 'axis', valueFormatter: value => value},
          xAxis: {
            type: 'category',
            axisTick: {show: true, alignWithLabel: true},
            data: dateList
          },
          yAxis: {},
          series: [{
            name: '数据',
            type: 'line',
            data: pueList
          }],
          color: ['#3c90f7']
        });
      });
    },
    drawCabinet() {
      this.$axios.get("/v1/home/cabinet/usage").then(data => {
        this.cabinet = echarts.init(this.$refs["cabinet"])
        // 绘制图表
        this.cabinet.setOption({
          title: {
            text: '{icon|}{space|}机柜使用率',
            textStyle: {
              rich: {
                icon: {
                  backgroundColor: {
                    image: require('./assets/charts-title-icon.png')
                  },
                  height: 16,
                  width: 16,
                  verticalAlign: "top"
                },
                space: {
                  width: 14
                }
              }
            }
          },
          tooltip: {valueFormatter: value => value },
          legend: {
            bottom: "0",
            left: "center",
            orient: "vertical",
            // 使用回调函数
            formatter: name => {
              if (name === "空闲机柜") {
                return `空闲机柜${data.total - data.used}  ${Math.round(((data.total - data.used) * 100 / data.total) | 0)}%`;
              } else {
                return `占用机柜${data.used}  ${Math.round((data.used * 100 / data.total) | 0)}%`;
              }
            }
          },
          series: [{
            name: '数据',
            type: 'pie',
            avoidLabelOverlap: false,
            selectedMode: "single",
            selectedOffset: 14,
            label: {
              show: false,
              position: 'center'
            },
            labelLine: {
              show: false
            },
            emphasis: {
              label: {
                show: true,
                fontSize: 18,
                fontWeight: 'bold',
                lineHeight: 20,
                padding: [40, 0, 0, 0],
                formatter: item => {
                  return item.name + "\n" + item.data.value;
                }
              }
            },
            radius: ['40%', '70%'],
            center: ['50%', '50%'],
            data: [{value: data.total - data.used, name: "空闲机柜"}, {value: data.used, name: "占用机柜"}]
          }],
          color: ['#5488FE', '#62CA8E']
        });
      });
    },

    resize() {
      this.patrol.resize();
      this.score.resize();
      this.energyConsumption.resize();
      this.PUE.resize();
      this.cabinet.resize();
    }
  }
}
</script>

<style scoped lang="scss">
.app-container {

  .line-height {
    height: 360px;
  }

  .chart-title-container {
    display: flex;
    align-items: center;

    .chart-title-icon {
      width: 16px;
      height: 16px;
      display: block;
    }

    .chart-title-text {
      font-size: 18px;
      font-weight: bolder;
      color: #333;
      font-family: 'sans-serif';
      margin-left: 14px;
    }
  }


  .divider {
    width: 1px;
    height: 340px;
    background: #DCDFE6;
    margin: 0 20px;
  }

  .area1, .area3 {
    flex: 2;
    margin: 5px;
  }

  .area2, .area4 {
    flex: 1;
    margin: 5px;
    min-width: 555px;
  }

  .complete-container {
    flex: 1;
    height: 96px;
    font-size: 16px;
    color: white;
    padding: 14px;
    border-radius: 4px;
    margin: 0 2%;

    .complete-title {
      font-weight: 400;
      margin-bottom: 16px;
    }

    .complete-progress-text {
      font-size: 20px;
    }

    .complete-scale-text {
      font-size: 14px;
    }

    .complete-progress-background {
      width: 100%;
      height: 6px;
      background: rgba(255, 255, 255, 0.4);
      margin-top: 5px;
      border-radius: 3px;

      .complete-progress {
        height: 100%;
        background: #FFFFFF;
        border-radius: 3px;
      }
    }
  }

  .visitor-container {
    display: flex;
    flex-direction: column;

    .visitor-count-container {
      display: flex;
      align-items: center;
      justify-content: center;
      height: 70px;
      background: rgba(91, 119, 250, 0.1);
      margin-top: 18px;
      margin-bottom: 21px;

      .visitor-count {
        font-size: 14px;
        font-weight: 400;
        color: #333333;
        font-family: 'sans-serif';
        display: flex;
        align-items: center;

        span {
          font-size: 26px;
          font-weight: bolder;
          color: #5B77FA;
          margin: 0 14px;
        }
      }
    }

    .visitor-title-container {
      display: flex;
      align-items: center;

      .visitor-title-icon {
        width: 11px;
        height: 11px;
        background: #3875FF;
        border-radius: 50%;
        margin-right: 7px;
      }

      .visitor-title {
        font-size: 14px;
        font-weight: 400;
        color: #000000;
      }
    }

    .visitor-list {
      flex: 1;
      display: flex;
      flex-direction: column;
      margin-top: 14px;

      .visitor-item-container {
        overflow: auto;
        height: 198px;

        .visitor-item {
          width: 100%;
          height: 46px;
          font-size: 14px;
          display: flex;
          align-items: center;
          justify-content: space-around;
          border-top: 1px solid #CCCCCC;

          &:last-of-type {
            border-bottom: 1px solid #CCCCCC;
          }

          .visitor-text {
            font-weight: 400;
            color: #000000;
            height: 100%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 14px;
            border-left: 1px solid #CCCCCC;

            &:last-of-type {
              border-right: 1px solid #CCCCCC;
            }
          }


        }
      }
    }
  }

  .cabinet-container {

    .cabinet-list {
      display: flex;
      flex-direction: column;
      align-items: center;
      margin: 0 auto;
      height: 100%;
      padding: 20% 0 10%;

      .cabinet-item {
        width: 100%;
        height: 47px;
        border-bottom: 1px solid #FFF;
        display: flex;
        align-items: center;
        font-size: 14px;
        justify-content: space-around;

        .cabinet-index-outer {
          width: 28px;
          height: 28px;
          border: 1px solid #5488FE;
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          margin-left: 14px;

          .cabinet-index-inner {
            width: 20px;
            height: 20px;
            background: #5488FE;
            border-radius: 50%;

            .cabinet-index-text {
              font-size: 14px;
              font-weight: 400;
              color: #FFFFFF;
              line-height: 20px;
              text-align: center;
            }
          }
        }

        .cabinet-text {
          line-height: 100%;
          color: #333333;
          text-align: center;
        }

        &:nth-of-type(2n) {
          background: #F3F8FF;
        }

        &:nth-of-type(2n+1) {
          background: #E6ECFE;
        }
      }
    }
  }

}
</style>
