<template>
  <div class="ob-home-content">
    <div class="ob-home-header">
      <video  data-v-93f40d6c="" data-v-45e53fd3="" autoplay="autoplay" loop="loop" muted="muted" class="bg_video">
        <source data-v-93f40d6c="" data-v-45e53fd3="" :src="homeBg" type="video/mp4">
      </video>
      <div style="position:relative;z-index:10;">
        <el-button type="primary" size="mini" style="margin-right:12px;vertical-align: middle;" round @click="handleAdd">新 增</el-button>
        <el-tooltip placement="bottom" effect="dark" :visible-arrow="false">
          <div slot="content">刷新应用列表</div>
          <i class="el-icon-refresh" style="font-size:20px;vertical-align: middle;margin-right:12px;" @click="getList" />
        </el-tooltip>
        <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" style="position:relative">
      <video  data-v-93f40d6c="" data-v-45e53fd3="" autoplay="autoplay" loop="loop" muted="muted" class="bg_video">
        <source data-v-93f40d6c="" data-v-45e53fd3="" :src="homeBg" type="video/mp4">
      </video>
      <div class="ob-home-warpper">
        <div class="ob-home-inner">
          <div class="content-form">
            <div class="lg-logo">
              <img :src="logo" class="lg-img" width="32" height="32">
            </div>
            <el-form ref="queryForm" :model="queryParams" :inline="true">
              <div class="content-form-flex">
                <el-select v-model="selectOption" placeholder="请选择" style="width:120px;" class="custom-select-input">
                  <el-option label="应用系统" value="1" />
                  <el-option label="URL接口" value="2" />
                </el-select>
                <el-form-item v-if="selectOption == '1'" label="" prop="name">
                  <el-select
                    v-model="queryParams.name"
                    style="width:670px;"
                    class="custom-left-input"
                    placeholder="请选择要访问的业务系统"
                    clearable
                    filterable
                    value-key="id"
                    @change="handChange"
                  >
                    <el-option
                      v-for="app in appList"
                      :key="app.id"
                      :label="app.name"
                      :value="app"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item v-else label="" prop="url">
                  <el-autocomplete
                    ref="autocompleteRef"
                    v-model="stateurl"
                    v-loading="loading"
                    v-scrollLoad="handelScroll"
                    class="custom-autocomplete-input"
                    style="width:670px;"
                    :value-key="'Route'"
                    :debounce="0"
                    :fetch-suggestions="querySearchAsync"
                    placeholder="请输入url"
                    @select="handleSelect"
                  >
                    <template slot-scope="{ item }">
                      <div v-show="item.Route" class="ob-select-box" style="display: flex; align-items: center; justify-content: space-between;">
                        <el-tooltip placement="bottom" effect="dark" :content="item.Route">
                          <span ref="KnowledgeContent" class="ob-select-title" style="overflow: hidden; white-space: nowrap; text-overflow: ellipsis; display: inline-block; max-width: 70%;">{{ item.Route }}</span>
                        </el-tooltip>
                        <div>
                          <el-tag size="mini" type="success" class="ob-tag-right" style="margin-right: 10px;">{{ item.Method }}</el-tag>
                          <el-tag size="mini">{{ item.ServiceName }}</el-tag>
                        </div>
                      </div>
                    </template>
                  </el-autocomplete>
                </el-form-item>
              </div>
            </el-form>
          </div>
          <div class="block-container">
            <div class="row">
              <div class="col">
                <el-tooltip placement="bottom" effect="dark" :visible-arrow="false">
                  <div slot="content">
                    <i class="dot" />
                    <span>{{ appList.length || 0 }}</span>
                  </div>
                  <div class="border-bottom">
                    <div class="block-box px-3 py-4">
                      <div class="col-tit">应用系统总量</div>
                      <div class="col-con">{{ appList.length !=undefined?appList.length:0 }}</div>
                    </div>
                  </div>
                </el-tooltip>
              </div>
              <div class="col">
                <el-tooltip placement="bottom" effect="dark" :visible-arrow="false">
                  <div slot="content"><i class="dot" />{{ rawdata.services }}</div>
                  <div class="border-bottom">
                    <div class="block-box px-3 py-4">
                      <div class="col-tit">服务总量</div>
                      <div class="col-con">{{ statusData.services!=undefined?statusData.services:0 }}</div>
                    </div>
                  </div>
                </el-tooltip>
              </div>
              <div class="col">
                <el-tooltip placement="bottom" effect="dark" :visible-arrow="false">
                  <div slot="content"><i class="dot" /><span>{{ rawdata.traces }}</span></div>
                  <div class="border-bottom">
                    <div class="block-box px-3 py-4">
                      <div class="col-tit">Trace总量</div>
                      <div class="col-con">{{ statusData.traces != undefined? statusData.traces:0 }}</div>
                    </div>
                  </div>
                </el-tooltip>
              </div>
              <div class="col">
                <el-tooltip placement="bottom" effect="dark" :visible-arrow="false">
                  <div slot="content"><i class="dot" />{{ rawdata.logs }}</div>
                  <div class="border-bottom">
                    <div class="block-box px-3 py-4">
                      <div class="col-tit">日志总量</div>
                      <div class="col-con">{{ statusData.logs !=undefined?statusData.logs :0 }}</div>
                    </div>
                  </div>
                </el-tooltip>
              </div>
              <div class="col">
                <el-tooltip placement="bottom" effect="dark" :visible-arrow="false">
                  <div slot="content"><i class="dot" />{{ rawdata.users }}</div>
                  <div class="border-bottom">
                    <div class="block-box px-3 py-4">
                      <div class="col-tit">用户总量</div>
                      <div class="col-con">{{ statusData.users !=undefined?statusData.users:0 }}</div>
                    </div>
                  </div>
                </el-tooltip>
              </div>

            </div>
          </div>
        </div>
        <div class="group_12 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" :key="item.label" 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 v-if="openMonitor" class="group_6 flex-row justify-between" style="position:relative;">
        <!-- <video  data-v-93f40d6c="" data-v-45e53fd3="" autoplay="autoplay" loop="loop" muted="muted" class="bg_video">
          <source data-v-93f40d6c="" data-v-45e53fd3="" :src="homeBg" type="video/mp4">
        </video> -->
        <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="6"
                :lg="6"
                :md="8"
                :sm="12"
                :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">
                      <el-tooltip placement="bottom" effect="dark" :visible-arrow="false">
                        <div slot="content">
                          <div>
                            <i class="el-icon-top icon-tips" />
                            <span>表示趋势向好</span>
                          </div>
                          <div>
                            <i class="el-icon-bottom icon-tips" />
                            <span>表示趋势变差</span>
                          </div>
                          <div>
                            <i class="el-icon-minus icon-tips" />
                            <span>表示没有变化</span>
                          </div>
                        </div>
                        <div class="icon-box">
                          <img class="icon-help" :src="iconHelp">
                        </div>
                      </el-tooltip>
                    <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:parseFloat(item.apdex).toFixed(2)) }}</span>
                            <img class="arrow" :src="item.apdexFlag=='up'?g_up:item.apdexFlag=='down'? red_down:line">
                          </div>
                          <span class="text_8">可用性</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=='up'?g_up:item.rateFlag=='down'?red_down:line">
                          </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=='up'?red_down:item.latencyFlag=='down'?g_up:line">
                          </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.errorRateFlag=='up'?red_up:item.errorRateFlag=='down'?g_up:line">
                          </div>
                          <span class="text_8">错误率(%)</span>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </el-col>
            </el-row>
          </div>
        </div>

      </div>
      <Monitoring v-else style="padding: 0" />
    </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()" />
    <!-- 添加或修改应用配置对话框 -->
    <el-dialog v-if="open" :title="title" :visible.sync="open" width="700px" :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="应用名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入应用名称" />
        </el-form-item>
        <el-form-item label="应用别名" prop="alias">
          <el-input v-model="form.alias" placeholder="请输入应用别名" :disabled="isEdit" />
        </el-form-item>
        <el-form-item label="应用备注">
          <el-input v-model="form.desc" type="textarea" placeholder="请输入应用详情" />
        </el-form-item>
        <el-form-item label="应用图片" prop="imgUrl">
          <img v-if="form.imgUrl" :src="form.imgUrl" class="el-upload el-upload--picture-card" style="float:left">
          <el-upload ref="sys_app_logo" accept=".png,.jpg,.jpeg" :headers="headers" :file-list="appsfileList" :action="appsAction" style="float:left" :before-upload="beforeUpload" list-type="picture-card" :show-file-list="false" :on-success="uploadSuccess">
            <i class="el-icon-plus" />
          </el-upload>
        </el-form-item>
        <el-form-item label="负责人" prop="contractInfo">
          <el-input v-model="form.contractInfo" placeholder="请输入负责人" />
        </el-form-item>
        <el-form-item label="手机号码" prop="contractPhone">
          <el-input v-model="form.contractPhone" placeholder="请输入合作手机号" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { listApps, appsScore, searchServiceUrl, addOtApps, updateOtApps } from '@/api/apps'
import { listStats } from '@/api/home'
import { eventNums } from '@/api/event'
import storage from '@/utils/storage'
import { mapGetters } from 'vuex'
import CalculationModel from './components/calculationModel'
import { getToken } from '@/utils/auth'
import Monitoring from '../global-monitoring/index.vue'
export default {
  components: {
    CalculationModel,
    Monitoring
  },
  data() {
    return {
      homeBg: require('../../assets/home.mp4'),
      logo: require('../../assets/logo/app_logo.png'),
      iconHelp: require('../../assets/icons/help.svg'),
      queryParams: {
        name: ''
      },
      selectOption: '1',
      appList: [],
      stateurl: '',
      suppilerListQuery: {
        url: this.stateurl,
        pageIndex: 1,
        pageSize: 100
      },
      loading: false,
      statusData: {},
      rawdata: {},
      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'),
      line:require('../../assets/apply/line.svg'),
      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,
      open: false,
      title: '',
      isEdit: false,
      // 表单参数
      form: {
        contractInfo: '',
        name: '',
        alias: '',
        desc: '',
        contractPhone: '',
        imgUrl: ''
      },
      // 表单校验
      rules: {
        name: [
          { required: true, message: '应用名称不能为空', trigger: 'blur' }
        ],
        alias: [
          { required: true, message: '应用别名不能为空', trigger: 'blur' }
        ],
        desc: [
          { required: true, message: '应用详情不能为空', trigger: 'blur' }
        ]
      },
      appsfileList: [],
      appsAction: process.env.VUE_APP_BASE_API + '/api/v1/public/uploadFile',
      headers: { 'Authorization': 'Bearer ' + getToken() },
      openMonitor: true
    }
  },
  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) {
        if(oldVal.length >0  && newVal ){
          for(let i=0;i<newVal.length;i++){
            if(newVal[i].apdex != undefined && oldVal[i].apdex != undefined){
              if (parseFloat(newVal[i].apdex) > parseFloat(oldVal[i].apdex)) {
                newVal[i].apdexFlag = 'up'
              } else if(parseFloat(newVal[i].apdex) < parseFloat(oldVal[i].apdex)) {
                newVal[i].apdexFlag = 'down'
              }else{
                newVal[i].apdexFlag = 'equal'
              }
            }
            if (newVal[i].latency != undefined && oldVal[i].latency != undefined) {
              if (parseFloat(newVal[i].latency) > parseFloat(oldVal[i].latency)) {
                newVal[i].latencyFlag = 'up'
              } else if(parseFloat(newVal[i].latency) < parseFloat(oldVal[i].latency)) {
                newVal[i].latencyFlag = 'down'
              }else{
                newVal[i].latencyFlag = 'equal'
              }
            }
            if (newVal[i].rate != undefined && oldVal[i].rate != undefined) {
              if (parseFloat(newVal[i].rate) > parseFloat(oldVal[i].rate)) {
                newVal[i].rateFlag = 'up'
              } else if(parseFloat(newVal[i].rate) < parseFloat(oldVal[i].rate)) {
                newVal[i].rateFlag = 'down'
              }else{
                newVal[i].rateFlag = 'equal'
              }
            }
            if (newVal[i].errorRate != undefined && oldVal[i].errorRate != undefined) {
              if (parseFloat(newVal[i].errorRate) > parseFloat(oldVal[i].errorRate)) {
                newVal[i].errorRateFlag = 'up'
              } else if(parseFloat(newVal[i].errorRate) < parseFloat(oldVal[i].errorRate)) {
                newVal[i].errorRateFlag = 'down'
              }else{
                newVal[i].errorRateFlag = 'equal'
              }
            }
          }
          this.appsList = newVal
          setTimeout(() => {
            this.draw_gauge()
          }, 2000)
        }

        // 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 = 'up'
        //       } else if(parseFloat(newVal[k].apdex) < parseFloat(oldVal[m].apdex)) {
        //         newVal[k].apdexFlag = 'down'
        //       }else{
        //         newVal[k].apdexFlag = 'equal'
        //       }
        //     }
        //     if (newVal[k].latency != undefined && oldVal[m].latency != undefined) {
        //       if (parseFloat(newVal[k].latency) > parseFloat(oldVal[m].latency)) {
        //         newVal[k].latencyFlag = 'up'
        //         console.log(k,'up')
        //       } else if(parseFloat(newVal[k].latency) < parseFloat(oldVal[m].latency)) {
        //         newVal[k].latencyFlag = 'down'
        //         console.log(k,'down')
        //       }else{
        //         newVal[k].latencyFlag = 'equal'
        //         console.log(k,'equal')
        //       }
        //     }

        //     if (newVal[k].rate != undefined && oldVal[m].rate != undefined) {
        //       if (parseFloat(newVal[k].rate) > parseFloat(oldVal[m].rate)) {
        //         newVal[k].rateFlag = 'up'
        //       } else if(parseFloat(newVal[k].rate) < parseFloat(oldVal[m].rate)) {
        //         newVal[k].rateFlag = 'down'
        //       }else{
        //         newVal[k].rateFlag = 'equal'
        //       }
        //     }

        //     if (newVal[k].errorRate != undefined && oldVal[m].errorRate != undefined) {
        //       if (parseFloat(newVal[k].errorRate) > parseFloat(oldVal[m].errorRate)) {
        //         newVal[k].errorRateFlag = 'up'
        //       } else if(parseFloat(newVal[k].errorRate) < parseFloat(oldVal[m].errorRate)) {
        //         newVal[k].errorRateFlag = 'down'
        //       }else{
        //         newVal[k].errorRateFlag = 'equal'
        //       }
        //     }
        //   }
        // }
      },
      deep: true
    }
  },
  created() {
    this.getSumInfo()
    this.getList()
    setTimeout(()=>{
      //利用定时器加载时差走两次计算
      this.getList()
    },300)
  },
  mounted() {
    //利用生命周期加载时差走两次计算
    // this.getList()
    //定时器写法 一分钟刷新一次
    // this.Refresh(60000)
  },
  beforeDestroy() {
    clearInterval(this.appTimer)
  },
  methods: {
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加应用'
      this.isEdit = false
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id !== undefined) {
            updateOtApps(this.form, this.form.id).then(response => {
              if (response.code === 200) {
                this.msgSuccess(response.msg)
                this.open = false
                this.getList()
              } else {
                this.msgError(response.msg)
              }
            })
          } else {
            addOtApps(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess(response.msg)
                this.open = false
                this.getList()
              } else {
                this.msgError(response.msg)
              }
            })
          }
        }
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        name: undefined,
        alias: undefined,
        desc: undefined,
        imgUrl: undefined,
        contractInfo: undefined,
        contractPhone: undefined
      }
      this.resetForm('form')
    },
    // 上传图片
    beforeUpload(file) {
      const isRightSize = file.size / 1024 / 1024 < 2
      if (!isRightSize) {
        this.$message.error('文件大小超过 2MB')
      }
      const isJPG = ['image/jpeg', 'image/png', 'image/jpg'].includes(file.type)
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG/PNG/JPEG 格式!')
      }
      return isRightSize && isJPG
    },
    uploadSuccess(response, file, fileList) {
      this.form.imgUrl = process.env.VUE_APP_BASE_API + response.data.full_path
    },
    getSumInfo() { // 获取概括信息对象
      listStats().then(res => {
        if (res.code == 200) {
          const statusData = res.data
          const rawdata = res.data
          this.rawdata.traces = this.handelerNumberjoin(rawdata.traces)
          this.rawdata.logs = this.handelerNumberjoin(rawdata.logs)
          this.rawdata.users = this.handelerNumberjoin(rawdata.users)
          this.rawdata.services = this.handelerNumberjoin(rawdata.services)

          this.statusData.traces = this.handlerNumber(statusData.traces)
          this.statusData.logs = this.handlerNumber(statusData.logs)
          this.statusData.users = this.handlerNumber(statusData.users)
          this.statusData.services = this.handlerNumber(statusData.services)
        }
      })
    },
    handlerNumber(num) {
      let str
      // let str = num.toString();
      if (num != undefined && num != null) {
        if (isNaN(num)) {
          str = num.toString()
        } else {
          str = num
        }

        // let str = num
        let result
        if (str.length <= 4) {
          result = num
        } else if (str.length > 4 && str.length < 7) {
          result = (num / 1000).toFixed(2) + 'K'
        } else if (str.length >= 7 && str.length < 10) {
          // result = Math.round(num/1000000) + 'M'
          result = (num / 1000000).toFixed(2) + 'M'
        } else {
          result = (num / 1000000000).toFixed(2) + 'B'
        }
        return result
      }
    },
    handelerNumberjoin(num) {
      if (num != undefined && num != null) {
        return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')
      } else {
        return 0
      }
    },
    // 选中
    handleSelect(item) {
      // 处理选中项
      const obj = this.appList.filter(m => m.alias === item.AppAlias)[0]
      storage.set('appsItem', obj)
      const rowItem = {
        method: item.Method,
        service_name: item.ServiceName,
        kind: item.Route,
        name: item.Route,
        route: item.Route
      }
      storage.set('row', rowItem)
      this.$router.push({
        path: '/service/InterfaceDetail/index',
        query: {
          kind: item.Route,
          method: item.Method,
          name: item.Route,
          service_name: item.ServiceName,
          route: item.Route
        }
      })
    },
    // 滚到底部执行的方法
    async handelScroll() {
      const suggestions = this.$refs.autocompleteRef.$data.suggestions
      if (Number(this.pageTotal) <= suggestions.length) { // 全部已经展示完了
        this.suppilerListQuery.pageIndex = 1
        return
      }
      this.suppilerListQuery.pageIndex++
      this.loading = true
      try {
        const result = await searchServiceUrl(this.suppilerListQuery)
        // 根据实际接口返回数据格式将数据插入到选项中
        this.$refs.autocompleteRef.$data.suggestions = suggestions.concat(result.data.list || [])
        this.pageTotal = result.data.count || 0
      } catch (e) {
        // console.log(e)
      } finally {
        this.loading = false
      }
    },
    async querySearchAsync(queryString, cb, type) {
      this.suppilerListQuery.url = this.stateurl.trim()
      if (this.stateurl === '') {
        this.suppilerListQuery.pageIndex = 1
      }
      try {
        const res = await searchServiceUrl(this.suppilerListQuery)
        if (res && res.code === 200) {
          this.suggestions = res.data.list || []
          this.pageTotal = res.data.count || 0
          cb(this.suggestions)
        }
      } catch (e) {
        // console.log(e)
      } finally {
        this.loading = false
      }
    },
    handChange(val) {
      if (val) {
        const obj = val
        obj.live = this.times.live
        obj.start_time = this.times.start_time
        obj.end_time = this.times.end_time
        storage.set('appsItem', obj)
        this.$store.commit('alias/setCurrentAlias', val.alias)
        this.$router.push({
          path: '/business-analysis/system-space/index',
          query: {
            id: val.id,
            app_alias: val.alias,
            name: val.name,
            start_time: this.times.start_time,
            end_time: this.times.end_time,
            item: val,
            live: val.live
          }
        }).catch(err => err)
      }
    },
    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.openMonitor = !this.openMonitor
    },
    // 获取所有应用
    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
            this.appList = 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.appsList[i].apdex == undefined || 0) ? 0 : ((parseFloat((this.appsList[i].apdex)).toFixed(2)) * 100) - 1,
                    detail: {
                      valueAnimation: true,
                      offsetCenter: ['0%', '0%']
                    }
                  }
                ],
                detail: {
                  fontSize: 18,
                  color: 'inherit',
                  borderColor: 'inherit',
                  formatter: '{value}%',
                  animation: true
                }
              }
            ]
          }

          myChart.setOption(option, true)
        }
      }
    },
    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;
    position: relative;
    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%;
    display: flex;
    background: white;
    .right_text_box{
      z-index:10;
    }
  }
  .ob-home-inner{
    flex: 1;
    // width: calc(100% - 340px);
  }
  .content-form{
    margin-top:20px;
    width: 100%;
    display:flex;
    justify-content: center;
    align-items: center;
    margin-bottom: 20px;
  }
  .custom-left-input ::v-deep .el-input__inner{
    border-left: none;
    border-radius: 0 8px 8px 0;
  }
  .custom-select-input ::v-deep .el-input__inner{
    border-right: none;
    border-radius: 8px 0 0 8px;
  }
  .content-form .el-form--inline .el-form-item{
    margin-bottom: 0;
    margin-right: 0;
  }
  .content-form-flex{
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    height:60px;
  }
  .content-form .custom-autocomplete-input ::v-deep .el-input__inner{
    border-left: 0;
    border-radius: 0 8px 8px 0;
  }

  .lg-logo{
    width:32px;
    height: 32px;
    margin-right: 16px;
    position: relative;
    z-index: 10
  }
  .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;
  }
  ::v-deep .el-input .el-input--medium .el-input--suffix{
    border-radius: 0px 8px 8px 0px !important;
    border-left: 0 !important;
  }
  .ob-select-title{
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    display: inline-block;
    max-width: 70%;
  }
  .ob-select-box{
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  .ob-tag-right{
    margin-right: 10px;
  }
}
.box_2{
  position: relative;
  .icon-box {
    position: absolute;
    right: 6px;
    top: 5px;
    .icon-help{
      width: 18px;
      height: 18px;
    }
  }
}
.icon-tips{
  padding-right: 6px;
}
.bg_video{
  position: absolute;
  width:100%;
  height:100%;
  top: 0;
  left: 0;
  // right:0;
  // bottom:0;
  -o-object-fit: cover;
  object-fit: cover;
}
</style>
