<template>
  <div class="ob-home-content">
    <div class="ob-home-header">
      <div>
        <i class="el-icon-refresh" style="font-size:20px;vertical-align: middle;margin-right:12px;" @click="toggle" />
        <el-dropdown
          style="font-size: 16px"
          trigger="hover"
        >
          <div>
            <span class="user-name">{{ name }}</span>
            <i class="el-icon-caret-bottom" />
          </div>
          <el-dropdown-menu slot="dropdown">
            <router-link to="/profile/index">
              <el-dropdown-item>个人中心</el-dropdown-item>
            </router-link>
            <el-dropdown-item>
              <span style="display: block" @click="logout">退出登录</span>
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </div>
    </div>

    <div class="section_2 ">
      <div class="ob-home-warpper">
        <div class="flex-row justify-between width100">
          <div v-for="item in sunList" class="group_2 flex-row padding20">
            <img
              class="image_1"
              referrerpolicy="no-referrer"
              :src="item.icon"
            >
            <div class="text-wrapper_1" :class="item.label == '服务部署包总量'? 'greenColor': ''">
              <span class="text_2">{{ item.label }}</span>
              <span class="text_3" :class="item.label == '服务部署包总量'? 'greenColor': ''">{{ item.value || 0}}</span>
            </div>
          </div>
        </div>
      </div>
      <div class="group_6 flex-row justify-between">
        <div v-if="isLoading" v-loading="isLoading" class="loading-overlay" />
        <div v-else class="flex-row flex-start">
          <div class="group_7">
            <el-row v-if="appsList.length>0" class="flex-wrap" type="flex" justify="start" :gutter="35">
              <el-col
                v-for="item in appsList"
                :key="item.id"
                :span="8"
                :lg="8"
                :md="12"
                :sm="24"
                :xs="24"
                style="margin-bottom:0.4375rem"
              >
                <div class="list-items_1 " @click="handelClick(item)">
                  <div class="box_1 flex-row justify-between">
                    <div class="title">
                      <span
                        class="circle"
                        :class="item.apdex>=0.94?'gc'
                          :(item.apdex>=0.85&&item.apdex<0.94)?'bc'
                            :(item.apdex>=0.7&&item.apdex<0.85)?'grc'
                              :(item.apdex>=0.5&&item.apdex<0.7)?'oc'
                                :'rc'"
                      />{{ item.name }}
                    </div>
                    <div class="flex-row ">
                      <div style="cursor: pointer;">
                        <el-badge ref="badgebox" :value="item.exception_num" class="badge">
                          <img class="title_img" :src="bellpin">
                        </el-badge>
                      </div>
                      <el-dropdown style="cursor: pointer;" @command="goDialog(item)">
                        <div style="width:0.15rem;text-align: center"><img class="title_img" :src="moreImg" style="margin-right:0;width:0.05rem;"></div>
                        <el-dropdown-menu slot="dropdown">
                          <el-dropdown-item common="a">可用性计算模型</el-dropdown-item>
                        </el-dropdown-menu>
                      </el-dropdown>
                    </div>
                  </div>
                  <div class="box_2 flex-row">
                    <div class="echartsbox">
                      <div ref="gauge" class="apply_l " />
                    </div>
                    <div class="flex-row" style="height: 100%; width:48%;">
                      <div class="section_5  ">
                        <div class="box_3">
                          <div class="baseline">
                            <span class="text_8">{{ (item.apdex==undefined?0:truncateNumber(item.apdex,2)) }}</span>
                            <img class="arrow" :src="item.apdexFlag==true?g_up:red_down">
                          </div>
                          <span class="text_8">Apdex</span>
                        </div>
                        <div class="box_3 marginbotom0">
                          <div class="baseline">
                            <span class="text_8">{{ item.rate==undefined?0:parseFloat(item.rate).toFixed(2) }}</span>
                            <img class="arrow" :src="item.rateFlag==true?g_up:red_down">
                          </div>
                          <span class="text_8"> 吞吐率(rpm)</span>
                        </div>
                      </div>
                      <div class="section_5  justify-between">
                        <div class="box_3">
                          <div class="baseline">
                            <span class="text_8">{{ item.latency==undefined?0:parseFloat(item.latency).toFixed(2) }}</span>
                            <img class="arrow" :src="item.latencyFlag==true?red_up:g_down">
                          </div>
                          <span class="text_8">响应时间(ms)</span>
                        </div>
                        <div class="box_3 marginbotom0">
                          <div class="baseline">
                            <span class="text_8">{{ item.errorRate==undefined?0:parseFloat(item.errorRate).toFixed(2) }}</span>
                            <img class="arrow" :src="item.rateFlag==true?g_up:red_down">
                          </div>
                          <span class="text_8">错误率(%)</span>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </el-col>
            </el-row>
          </div>

          <div class="group_8">
            <div class="group_12 right_waring_box">
              <div class="width100 flex-row justify-between marginBotom20">
                <span class="text_31">异常告警</span>
              <!-- <span class="text_32">查看更多</span> -->
              </div>
              <div class="warning-box">
                <div v-for="item in warningList" class="marginBttom10 flex-row ">
                  <div :class="item.type == 1 ? 'text-wrapper_5' : 'text-wrapper_error'"><span class="text_17">{{ item.label }}</span></div>
                  <span class="text_18">{{ item.text }}</span>
                </div>
              </div>
            </div>
            <div class="group_12 margintop20 right_text_box">
              <div class="width100 flex-row justify-between">
                <span class="text_31">帮助文档</span>
              <!-- <span class="text_32">查看更多</span> -->
              </div>
              <div class="block_4 ">
                <div v-for="item in productList" class="img-box">
                  <img
                    class="label_3"
                    referrerpolicy="no-referrer"
                    :src="item.icon"
                  >
                  <span class="text-group">{{ item.label }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>

      </div>
    </div>

    <div class="ob-home-back" @click="toggle2()">
      <i class="iconfont icon-qiehuan1" style="margin-right:5px" />
      新旧版本切换
    </div>
    <CalculationModel v-if="dialogFlag" :dialog-flag="dialogFlag" :alias="itemAlias" @dialogCancel="dialogCancel()" />
  </div>
</template>
<script>
import { listApps, appsScore } from '@/api/apps'
import { eventNums } from '@/api/event'
import BigNumber from 'bignumber.js'
import storage from '@/utils/storage'
import { mapGetters } from 'vuex'
import CalculationModel from './components/calculationModel'
export default {
  components: {
    CalculationModel
  },
  data() {
    return {
      servicesNumber: 0,
      sunList: [
        {
          label: '应用系统总量',
          value: 0,
          icon: require('@/assets/home/img1.png')
        },
        {
          label: '服务部署包总量',
          value: this.servicesNumber,
          icon: require('@/assets/home/img2.png')
        }
      ],
      appsList: [],
      queryNums: {
        start_time: this.$store.state.time.globalTimes.startTime,
        end_time: this.$store.state.time.globalTimes.endTime,
        pageSize: 10,
        pageIndex: 1,
        app_ids: 0
      },
      queryScore: {
        interval: 5,
        req_applist: []
      },
      bellpin: require('../../assets/apply/bellpin.png'),
      moreImg: require('../../assets/apply/more.png'),
      green_down: require('../../assets/apply/green_down.png'),
      green_up: require('../../assets/apply/green_up.png'),
      g_down: require('../../assets/apply/g_down.jpg'),
      g_up: require('../../assets/apply/g_up.jpg'),
      red_down: require('../../assets/apply/red_down.png'),
      red_up: require('../../assets/apply/red_up.png'),
      orange_down: require('../../assets/apply/orange_down.png'),
      orange_up: require('../../assets/apply/orange_up.png'),
      errorBg: require('../../assets/home/error-bg.svg'),
      greenBg: require('../../assets/home/green-bg.svg'),
      warnBg: require('../../assets/home/warn-bg.svg'),
      productList: [{
        icon: require('../../assets/home/gaikuo.png'),
        label: '产品概括'
      }, {
        icon: require('../../assets/home/wendang.png'),
        label: '接口文档'
      }],
      dialogFlag: false,
      itemAlias: '',
      times: {
        start_time: 0,
        end_time: 0,
        live: false
      },
      isLoading: false,
      warningList: [{
        type: 1,
        text: 'invoke(Request request,Resapcb…',
        label: '已警告'
      }, {
        type: 1,
        text: 'processShoppingOrdeString orb…',
        label: '已警告'
      }, {
        type: 2,
        text: 'http.status.code',
        label: '已报错'
      }, {
        type: 2,
        text: 'Servlet Process',
        label: '已报错'
      }, {
        type: 2,
        text: 'Servlet Process',
        label: '已报错'
      }, {
        type: 2,
        text: 'invoke(Request request,Resapc…',
        label: '已报错'
      }, {
        type: 2,
        text: 'invoke(Request request,Resapc…',
        label: '已报错'
      },
      {
        type: 1,
        text: 'Servlet Process',
        label: '已警告'
      },
      {
        type: 1,
        text: 'processShoppingOrdeString orb…',
        label: '已警告'
      }, {
        type: 2,
        text: 'Servlet Process',
        label: '已报错'
      }, {
        type: 2,
        text: 'http.status.code',
        label: '已报错'
      }, {
        type: 1,
        text: 'processShoppingOrdeString orb…',
        label: '已警告'
      }, {
        type: 2,
        text: 'http.status.code',
        label: '已报错'
      }, {
        type: 1,
        text: 'processShoppingOrdeString orb…',
        label: '已警告'
      }
      ]
    }
  },
  computed: {
    ...mapGetters(['name'])
  },
  watch: {
    '$store.state.time.globalTimes': {
      handler(newValue, oldValue) {
        if (newValue) {
          this.times.start_time = newValue.startTime
          this.times.end_time = newValue.endTime
          this.queryScore.interval = newValue.interval
          this.queryNums.start_time = newValue.startTime
          this.queryNums.end_time = newValue.startTime
          this.getList()
          if (newValue.timeOut) {
            if (newValue.timeOut == 1) {
              this.times.live = false
              clearInterval(this.appTimer)
            } else {
              this.times.live = true
              clearInterval(this.appTimer)
              this.Refresh(newValue.timeOut)
            }
          }
        }
      },
      deep: true
    },
    appsList: {
      handler(newVal, oldVal) {
        this.sunList.filter((item) => item.label == '应用系统总量')[0].value = newVal.length || 0
        for (let k = 0; k < newVal.length; k++) {
          for (let m = 0; m < oldVal.length; m++) {
            if (newVal[k].apdex != undefined && oldVal[m].apdex != undefined) {
              if (parseFloat(newVal[k].apdex) > parseFloat(oldVal[m].apdex)) {
                newVal[k].apdexFlag = true
              } else {
                newVal[k].apdexFlag = false
              }
            }
            if (newVal[k].latency != undefined && oldVal[m].latency != undefined) {
              if (parseFloat(newVal[k].latency) > parseFloat(oldVal[m].latency)) {
                newVal[k].latencyFlag = true
              } else {
                newVal[k].latencyFlag = false
              }
            }

            if (newVal[k].rate != undefined && oldVal[m].rate != undefined) {
              if (parseFloat(newVal[k].rate) > parseFloat(oldVal[m].rate)) {
                newVal[k].rateFlag = true
              } else {
                newVal[k].rateFlag = false
              }
            }

            if (newVal[k].errorRate != undefined && oldVal[m].errorRate != undefined) {
              if (parseFloat(newVal[k].errorRate) > parseFloat(oldVal[m].errorRate)) {
                newVal[k].errorRateFlag = true
              } else {
                newVal[k].errorRateFlag = false
              }
            }
          }
        }

        if (newVal) {
          this.appsList = newVal
          setTimeout(() => {
            this.draw_gauge()
          }, 1000)
        }
      },
      deep: true
    }
  },
  created() {
    const item = this.sunList.filter((item) => item.label == '服务部署包总量')[0]
    item.value = this.$route.query.servicesNumber
    this.servicesNumber = this.$route.query.servicesNumber
    this.getList()
  },
  mounted() {

  },
  beforeDestroy() {
    clearInterval(this.appTimer)
  },
  methods: {
    async logout() {
      this.$confirm('确定注销并退出系统吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$store.dispatch('user/LogOut').then(() => {
          location.reload()
        })
      })
    },

    toggle() {
      this.$router.push({
        path: '/home'
      }).catch(err => err)
    },
    toggle2() {
      this.$router.push({
        path: '/home',
        query: {
          openMonitor: true,
          servicesNumber: this.servicesNumber
        }
      })
    },
    // 获取所有应用
    getList() {
      this.isLoading = true
      listApps({ pageIndex: 0, pageSize: 200 }).then(
        res => {
          const req_applist = []
          const app_ids = []
          if (res.code == 200) {
            const arr = res.data.list
            res.data.list.map((item) => {
              req_applist.push({ app_alias: item.alias })
              app_ids.push(item.id)
            })
            this.queryNums.app_ids = app_ids.join(',')
            this.queryScore.req_applist = req_applist
            if (req_applist.length > 0) {
              appsScore(this.queryScore).then(res => {
                // const lists= storage.get('lists')
                if (res.code == 200) {
                  if (res.data.scores != null) {
                    for (let i = 0; i < arr.length; i++) {
                      for (let j = 0; j < res.data.scores.length; j++) {
                        if (arr[i].alias == res.data.scores[j].app_alias) {
                          arr[i] = Object.assign({}, arr[i], res.data.scores[j])
                        }
                      }
                    }
                    setTimeout(() => {
                      this.draw_gauge()
                    }, 1000)
                    eventNums(this.queryNums).then((res) => {

                      if (res.code == 200) {
                        if (res.data.list.length != 0) {
                          for (let i = 0; i < arr.length; i++) {
                            for (let j = 0; j < res.data.list.length; j++) {
                              if (arr[i].id == res.data.list[j].app_id) {
                                arr[i] = Object.assign({}, arr[i], res.data.list[j])
                              } else {
                                arr[i].exception_num = undefined
                              }
                            }
                          }
                        }
                      }
                      this.appsList = arr
                      this.isLoading = false

                      this.$nextTick(() => {
                        const offsetHeight = document.querySelector('.group_7').offsetHeight
                        const rightDom = document.querySelector('.group_8')
                        const rightWaringBox = document.querySelector('.right_waring_box')
                        rightDom.style.height = offsetHeight + 'px'
                        rightWaringBox.style.height = offsetHeight - 350 - 20 + 'px'
                      })
                    })
                  }
                }
              })
            }
          }
        }
      )
    },
    draw_gauge() {
      var myEchart = this.$refs.gauge
      // 获取当前屏幕的宽度
      const screenWidth = window.screen.width

      // 获取当前屏幕的高度
      const screenHeight = window.screen.height
      let coord = []
      let radius = ''
      if (screenWidth == 1920) {
        coord = [
          '47%',
          '45%'
        ]
        radius = '79%'
      } else if (screenWidth <= 1440) {
        radius = '78%'
        coord = [
          '46%',
          '44%'
        ]
      } else {
        coord = [
          '47%',
          '44%'
        ]
        radius = '78%'
      }

      if (myEchart && myEchart.length > 0) {
        for (var i = 0; i < myEchart.length; i++) {
          var myChart = this.$echarts5.getInstanceByDom(myEchart[i])

          if (myChart == null) {
            myChart = this.$echarts5.init(myEchart[i])
          }
          // 配置项
          const option = {
            // 背景图片设置
            graphic: [
              {
                type: 'image',

                z: -10,
                bounding: 'raw',
                rotation: 0, // 旋转角度，可根据需要调整
                origin: (50, 50), // 中心点坐标，可以根据实际情况修改
                // scale: (0.2, 0.2), // 缩放比例
                style: {
                  // 背景图路径
                  image: this.getBgImg(this.appsList[i].apdex),
                  opacity: 1,
                  width: myChart._dom.offsetHeight - 20, // 修改背景图片的宽度
                  height: myChart._dom.offsetHeight - 20 // 修改背景图片的高度
                }
              }
            ],
            series: [
              {
                type: 'gauge',
                startAngle: -122,
                endAngle: -45,
                radius: radius,
                center: coord, // 圆心坐标,
                pointer: {
                  show: false
                },
                itemStyle: {
                  normal: {
                    color: {
                      type: 'linear',
                      x: 0,
                      y: 0,
                      x2: 0,
                      y2: 1,
                      colorStops: [
                        {
                          offset: 0,
                          color: this.getColorForValue(this.appsList[i].apdex, '0') // 0% 处的颜色
                        },
                        {
                          offset: 0.5,
                          color: this.getColorForValue(this.appsList[i].apdex, '0.5') // 0% 处的颜色
                        },
                        {
                          offset: 1,
                          color: this.getColorForValue(this.appsList[i].apdex, '1') // 100% 处的颜色
                        }
                      ],
                      global: false
                    },
                    borderWidth: 4,
                    labelLine: {
                      show: false
                    }
                  }
                },
                progress: {
                  show: true,
                  overlap: false,
                  roundCap: true,
                  clip: false,
                  itemStyle: {
                    borderWidth: 1
                  }
                },
                axisLine: {
                  show: false
                },
                splitLine: {
                  show: false,
                  distance: 0,
                  length: 10
                },
                axisTick: {
                  show: false
                },
                axisLabel: {
                  show: false,
                  distance: 50
                },
                data: [
                  {
                    value: this.truncateNumber(this.appsList[i].apdex,2),
                    detail: {
                      valueAnimation: true,
                      offsetCenter: ['0%', '0%']
                    }
                  }
                ],
                detail: {
                  fontSize: 18,
                  color: 'inherit',
                  borderColor: 'inherit',
                  formatter: '{value}',
                  animation: true
                }
              }
            ]
          }

          myChart.setOption(option, true)
        }
      }
    },
    // 直接截取小数num到小数点后指定位数places，不做四舍五入
    truncateNumber(num, places) {
      if(!num){
        num = 0
      }
      const multiplier = Math.pow(10, places)
      return Math.floor(num * multiplier) / multiplier
    },
    convertToPercentage(value) {
      console.log(123456789,value)
      const bnValue = new BigNumber(value)
      const percentage = bnValue.multipliedBy(100)// 乘法运算
      let roundedPercentage = percentage.decimalPlaces(2, BigNumber.ROUND_FLOOR)// decimalPlaces保留小数位

      // 如果四舍五入后的值小于原始值，手动增加 0.01
      if (roundedPercentage.isLessThan(percentage)) { // 判断是否小于
        roundedPercentage = roundedPercentage.plus(0.01)
      }

      return `${roundedPercentage.toFixed(2)}%`
    },
    getBgImg(apdex) {
      if (apdex == undefined || apdex == null) {
        return this.errorBg
      }
      return apdex <= 0.5 ? this.errorBg : (apdex > 0.5 && apdex < 0.9 ? this.warnBg : this.greenBg)
    },
    getColorForValue(value, type) {
      const redObj = {
        '0': '#F8B402',
        '0.5': '#FF5C76',
        '1': '#FF1011'
      }
      const greenObj = {
        '0': '#66FFFF',
        '0.5': '#00C5FF',
        '1': '#0EFF79'
      }
      const warnObj = {
        '0': '#5BFFBD',
        '0.5': '#FADB3D',
        '1': '#FF6B00'
      }
      if (value <= 0.5 || value == undefined || value == null) { // 红色
        return redObj[type]
      } else if (value > 0.5 && value < 0.9) {
        return warnObj[type]
      } else if (value >= 0.9) {
        return greenObj[type]
      }
    },
    goDialog(item) {
      this.itemAlias = item.alias
      this.dialogFlag = true
    },
    dialogCancel() {
      this.dialogFlag = false
    },
    Refresh(timeOut) {
      this.appTimer = setInterval(() => {
        this.getList()
      }, timeOut)
    },
    handelClick(item) {
      const start_time = this.$store.state.time.globalTimes.startTime
      const end_time = this.$store.state.time.globalTimes.endTime
      const live = this.times.live
      this.$store.commit('alias/setCurrentAlias', item.alias)
      this.$router.push({
        path: '/business-analysis/system-space/index',
        query: {
          id: item.id,
          app_alias: item.alias,
          start_time,
          end_time,
          item: item,
          live: live
        }
      })
      // item.start_time = this.times.start_time
      // item.end_time = this.times.end_time
      item.live = this.times.live
      storage.set('appsItem', item)
    }
  }
}
</script>
<style lang="scss" scoped>
@import "./css/index1.css";
.ob-home-content{
  width: 100%;
  height: 100%;
  .ob-home-header{
    // margin-bottom: 20px;
    width:100%;
    height: 60px;
    text-align: right;
    background-color: white;
    line-height: 60px;
    padding-right: 20px;
    box-shadow: 0 -5px 10px rgba(0, 0, 0, 0.5); /* 水平偏移为0，垂直偏移为负，所以阴影位于底部 */
    cursor: pointer;
  }
  .ob-home-warpper{
    padding:20px;
    width:100%;
  }
  .ob-home-topnav{
    width:100%;
    img{
      width:50%;
      cursor: pointer;
    }
  }
  .ob-home-back{
    position: fixed;
    bottom:20px;
    right:50%;
    padding: 10px;
    display: flex;
    align-items: center;
    z-index: 200;
    border:1px solid #eee;
    background-color: white;
    border-radius: 8px;
    cursor: pointer;
  }
  .icon-qiehuan1:before {
    content: "\e789";
  }
  .iconfont {
    font-family: "iconfont" !important;
    font-size: 20px;
    font-style: normal;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
  }
  .block_4 {
    width: 100%;
    height: 92%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    background: url("../../assets/home/wendangbg.png") no-repeat;
    background-size: contain;
    background-position: right bottom;
  }
}
</style>
