<template>
  <BasicLayout>
    <template #wrapper>
      <el-card class="box-card" style="flex:1;">
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <el-tab-pane label="应用概览" name="first">
            <!-- <div class="dataBlock">
              <el-row :gutter="10">
                <el-col :span="6">
                  <el-tooltip placement="bottom" effect="dark" :visible-arrow="false">
                    <div slot="content">
                      <i class="dot" />
                      <span>{{ apdex!=undefined?apdex:0 }}</span>
                    </div>
                    <div class="grid-container" @click="gotoPath('/business-analysis/topology/index')">
                      <div class="grid-header">
                        <h6 class="grid-header-title">健康度</h6>
                      </div>
                      <div class="grid-content">
                        <span
                          :class="ApdexNum>=0.94?'gc'
                            :(ApdexNum>=0.85&&ApdexNum<0.94)?'bc'
                              :(ApdexNum>=0.7&&ApdexNum<0.85)?'grc'
                                :(ApdexNum>=0.5&&ApdexNum<0.7)?'oc'
                                  :'rc'"
                          style="font-size:46px;font-weight:500"
                        >{{ ApdexNum>=0.94?'性能极佳':((ApdexNum>=0.85 && ApdexNum<0.94)?"性能较好":(ApdexNum>=0.7&&ApdexNum<0.85)?"性能一般":(ApdexNum>=0.5&&ApdexNum<0.7)?"性能一般":"性能未知") }}</span>
                      </div>
                    </div>
                  </el-tooltip>
                </el-col>
                <el-col :span="6">
                  <el-tooltip placement="bottom" effect="dark" :visible-arrow="false">
                    <div slot="content">
                      <i class="dot" />
                      <span>{{ basicObj.biz!=undefined?basicObj.biz:0 }}</span>
                    </div>
                    <div class="grid-container" @click="gotoPath('/business-analysis/analysis/index')">
                      <div class="grid-header">
                        <h6 class="grid-header-title">业务总数</h6>
                      </div>
                      <div class="grid-content">{{ basicObj.biz!=undefined?basicObj.biz:0 }}</div>
                    </div>
                  </el-tooltip>
                </el-col>
                <el-col :span="6">
                  <el-tooltip placement="bottom" effect="dark" :visible-arrow="false">
                    <div slot="content">
                      <i class="dot" />
                      <span>{{ basicObj.svrs!=undefined?basicObj.svrs:0 }}</span>
                    </div>
                    <div class="grid-container" @click="gotoPath('/service/service/index')">
                      <div class="grid-header">
                        <h6 class="grid-header-title">Server总数</h6>
                      </div>
                      <div class="grid-content">{{ basicObj.svrs !=undefined?basicObj.svrs:0 }}</div>
                    </div>
                  </el-tooltip>
                </el-col>
                <el-col :span="6">
                  <el-tooltip placement="bottom" effect="dark" :visible-arrow="false">
                    <div slot="content">
                      <i class="dot" />
                      <span>{{ basicObj.interface!=undefined?basicObj.interface:0 }}</span>
                    </div>
                    <div class="grid-container" @click="gotoPath('/service/InterfaceSublist/index')">
                      <div class="grid-header">
                        <h6 class="grid-header-title">对外接口总数</h6>
                      </div>
                      <div class="grid-content">{{ basicObj.interface != undefined?basicObj.interface:0 }}</div>
                    </div>
                  </el-tooltip>
                </el-col>

              </el-row>
            </div> -->
            <!-- <div class="grafanaWrap">
              <iframe v-if="iframeUrl!=''" :src='iframeUrl' style="width:100%;height:calc( 100vh - 114px );min-height:500px;margin-top: -10px;over-flow:hidden"
                  id="myIframe"
                  scrolling='auto'
                  frameBorder='no'
                  border='0'
                  marginWidth='0'
                  marginHeight='0' height="calc( 100vh - 114px )"></iframe>
            </div>
            <el-row v-if='dashFlag==true' style="padding:0 16px;background: rgb(244,245,245);">
                <el-col
                :span="24"
                :lg="24"
                :md="24"
                :sm="24"
                style="margin-top: 8px;margin-bottom:35px;"
              >
                  <el-tooltip content="为本应用添加自定义面板" placement="bottom" effect="light">
                    <div
                      class="addCard"
                      :body-style="{ padding: '0px' }"
                      @click="handleAdd"
                    >
                      <div class="flex-add">
                        <i class="el-icon-plus" size='24'></i>
                      </div>
                    </div>
                  </el-tooltip>
                </el-col>
            </el-row> -->
            <div class="grafanaBox">
              <div class="amountIframe">
                <div v-if="grafanaIframeFlag">
                  <div class="header">
                    <div class="header-right">
                      <el-button type="primary" size="mini" style="margin-right:12px;vertical-align: middle;" round @click="handleGrafanaIframe">使用快捷站点</el-button>
                    </div>
                  </div>
                  <div>
                    <NoData style="height:calc( 100vh - 114px )" />
                  </div>
                </div>
                <div v-else>
                  <iframe
                    id="amountIframeGrafana"
                    :src="GrafanaAmountUrl"
                    style="width:100%;height:calc( 100vh - 114px );min-height:500px;margin-top: -10px;over-flow:hidden"
                    scrolling="auto"
                    frameBorder="no"
                    border="0"
                    marginWidth="0"
                    marginHeight="0"
                    height="calc( 100vh - 280px )"
                  />
                </div>
              </div>
            </div>
          </el-tab-pane>
          <el-tab-pane label="资源使用" name="second">
            <!-- <div class="dataBlock">
                <el-row :gutter="10" class="mb8" style='background: #fff;padding: 10px;'>
                  <el-col :span="1.5">
                    <el-button
                      type="primary"
                      icon="el-icon-plus"
                      size="mini"
                      @click="handleAddIframeUrl"
                    >新增</el-button>
                  </el-col>
                  <el-col :span="1.5">
                    <el-button
                      type="success"
                      icon="el-icon-edit"
                      size="mini"
                      @click="handleUpdateIframeUrl"
                    >修改</el-button>
                  </el-col>
                </el-row>
            </div> -->
            <div class="amountIframe">
              <div v-if="iframeFlag">
                <div class="header">
                  <div class="header-right">
                    <el-button type="primary" size="mini" style="margin-right:12px;vertical-align: middle;" round @click="handleIframe">使用快捷站点</el-button>
                  </div>
                </div>
                <div>
                  <NoData />
                </div>
              </div>
              <div v-else>
                <iframe
                  id="amountIframe"
                  :src="amountUrl"
                  style="width:100%;height:calc( 100vh - 114px );min-height:500px;margin-top: -10px;over-flow:hidden"
                  scrolling="auto"
                  frameBorder="no"
                  border="0"
                  marginWidth="0"
                  marginHeight="0"
                  height="calc( 100vh - 114px )"
                />
              </div>
              <!-- <div v-else class="urlbox"> -->
              <!-- <el-form ref="form" :model="form" :rules="rules" label-width="120px">
                      <el-row>
                        <el-col :span="24">
                          <el-form-item label="站点地址:" prop="url">
                            <el-input v-model="form.url" placeholder="请填入需要绑定的站点URL" />
                          </el-form-item>
                        </el-col>
                        <el-col :span="24">
                          <el-form-item label="鉴权信息:" prop="desc">
                            <el-input v-model="form.desc" placeholder="请填入鉴权信息 (如有)" />
                          </el-form-item>
                        </el-col>
                      </el-row>
                      <el-form-item style="text-align: center;">
                        <el-button type="primary" @click="submitForm">确 定</el-button>
                      </el-form-item>
                  </el-form> -->
              <!-- </div> -->

            </div>
          </el-tab-pane>
        </el-tabs>

        <!-- <div class="grafanaEdit">
          <div class="small">
            <i class="el-icon-refresh" style="font-size:20px;vertical-align: middle;" title="编辑"></i>
          </div>
          <div class="big">
            <el-switch
              v-model="isEdit"
              @change='handleUpdate'
              style="margin-top:1px;margin-right:4px;"
              >
            </el-switch><span style="vertical-align: middle;">编辑</span>
          </div>
        </div> -->

        <!-- 添加或修改参数配置对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="600px" :close-on-click-modal="false">
          <!-- <el-form ref="form" :model="form" :rules="rules" label-width="120px">
            <el-row>
              <el-col :span="24">
                <el-form-item label="页面标识" prop="pageTag">
                  <el-input v-model="form.pageTag" placeholder="请输入页面标识" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="Url" prop="url">
                  <el-input v-model="form.url" placeholder="请输入url地址" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="鉴权" prop="desc">
                  <el-input v-model="form.desc" placeholder="请输入鉴权" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form> -->
          <el-form ref="form" :model="form" :rules="rules" label-width="120px">
            <el-row>
              <el-col :span="24">
                <el-form-item label="站点地址:" prop="url">
                  <el-input v-model="form.url" placeholder="请填入需要绑定的站点URL" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="鉴权信息:" prop="desc">
                  <el-input v-model="form.desc" placeholder="请填入鉴权信息 (如有)" />
                </el-form-item>
              </el-col>
            </el-row>
          </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>
      </el-card>
    </template>
  </BasicLayout>
</template>

<script>
import { otAppDashboard, addDashBoard } from '@/api/dashboard'
import { listIframeUrl, addIframeUrl, updateIframeUrl } from '@/api/iframe-url'
import { appsScore } from '@/api/apps'
import { basicGuy } from '@/api/mapping'
import storage from '@/utils/storage'
import NoData from '@/views/NoData/nodata'
export default {
  components: {
    NoData
  },
  data() {
    return {
      grafanaIframeFlag: true,
      iframeFlag: true,
      activeName: 'first',
      appId: '',
      app_alias: '',
      // 插件url拼接dashboarduid的最终iframe的url地址
      iframeUrl: '',
      // 插件的url，用于拼接dashboardid
      pluginUrl: '',
      // dashboard uid 用于拼接插件的url
      dashboardUid: '',
      // 是否携带请求头（例如：token）
      isRequestHeader: true,
      config: {},
      pluginList: [], // 插件列表
      dashFlag: false,
      loading: false,
      isEdit: false,
      appItem: {},
      amountUrl: '',
      GrafanaAmountUrl: '',
      open: false,
      title: '',
      form: {
        pageTag: '',
        appId: undefined,
        url: undefined,
        desc: undefined
      },
      rules: {
        // pageTag: [{ required: true, message: '页面标识不能为空', trigger: 'blur' }],
        url: [{ required: true, message: 'url不能为空', trigger: 'blur' }]
      },
      iframeQuery: {
        appId: undefined,
        pageTag: ''
      },
      iframeList: [],
      queryScore: {
        interval: 5,
        req_applist: []
      },
      queryNums: {
        start_time: 0,
        end_time: 0,
        pageSize: 10,
        pageIndex: 1,
        app_ids: 0
      },
      ApdexNum: 1,
      appsList: [],
      apdex: 0,
      basicQuery: {
        app_alias: ''
      },
      basicObj: {},
      timer: null
    }
  },
  watch: {
    '$store.state.time.globalTimes': {
      handler(newValue, oldValue) {
        if (newValue) {
          this.queryScore.interval = newValue.interval
          this.getAppsScore()
          if (newValue.timeOut) {
            if (newValue.timeOut == 1) {
              clearInterval(this.timer)
            } else {
              clearInterval(this.timer)
              this.Refresh(newValue.timeOut)
            }
          }
        }
      },
      // immediate: true,
      deep: true
    }
  },
  created() {
    this.appItem = storage.get('appsItem')
    if (JSON.stringify(this.appItem) != '{}') {
      this.appId = this.appItem.id
      this.form.appId = this.appItem.id
      this.iframeQuery.appId = this.appItem.id
      this.basicQuery.app_alias = this.appItem.alias

      this.getAppsScore()
      this.getbasicGuy()

      // this.getListApps();
    }
    if (this.activeName == 'first') {
      this.iframeQuery.pageTag = 'grafana'
      this.form.pageTag = 'grafana'
      this.getListIframeUrl()
    } else {
      this.iframeQuery.pageTag = 'resource'
      this.form.pageTag = 'resource'
      this.getListIframeUrlZiYuan()
    }
  },
  beforeDestroy() {
    clearInterval(this.timer)
  },
  methods: {
    Refresh(timeOut) {
      this.timer = setInterval(() => {
        this.getAppsScore()
        this.getbasicGuy()
      }, timeOut)
    },
    gotoPath(path) {
      this.$router.push({
        path: path
      })
    },
    getbasicGuy() {
      basicGuy(this.basicQuery).then((res) => {
        if (res.code == 200) {
          this.basicObj = res.data
        }
      })
    },
    handleGrafanaIframe() {
      this.form.pageTag = 'grafana'
      this.open = true
    },
    handleIframe() {
      this.form.pageTag = 'resource'
      this.open = true
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    /** 提交按钮 */
    submitForm: function() {
      if (this.form.pageTag == 'grafana') {
        this.$refs['form'].validate(valid => {
          if (valid) {
            if (this.form.id !== undefined) {
              updateIframeUrl(this.form, this.form.id).then(response => {
                if (response.code === 200) {
                  this.msgSuccess(response.msg)
                  this.open = false
                  this.getListIframeUrl()
                } else {
                  this.msgError(response.msg)
                }
              })
            } else {
              addIframeUrl(this.form).then(response => {
                if (response.code === 200) {
                  this.msgSuccess(response.msg)
                  this.open = false
                  this.getListIframeUrl()
                  this.iframeFlag = false
                } else {
                  this.msgError(response.msg)
                }
              })
            }
          }
        })
      } else {
        this.$refs['form'].validate(valid => {
          if (valid) {
            if (this.form.id !== undefined) {
              updateIframeUrl(this.form, this.form.id).then(response => {
                if (response.code === 200) {
                  this.msgSuccess(response.msg)
                  this.open = false
                  this.getListIframeUrlZiYuan()
                } else {
                  this.msgError(response.msg)
                }
              })
            } else {
              addIframeUrl(this.form).then(response => {
                if (response.code === 200) {
                  this.msgSuccess(response.msg)
                  this.open = false
                  this.getListIframeUrlZiYuan()
                  this.iframeFlag = false
                } else {
                  this.msgError(response.msg)
                }
              })
            }
          }
        })
      }
    },
    // 表单重置
    reset() {
      this.form = {
        pageTag: '',
        appId: undefined,
        url: undefined,
        desc: undefined
      }
      this.resetForm('form')
    },
    getListIframeUrl() {
      this.iframeQuery.pageTag = 'grafana'
      listIframeUrl(this.iframeQuery).then(res => {
        if (res.code == 200) {
          this.iframeList = res.data.list
          if (res.data.list.length > 0) {
            for (let i = 0; i < this.iframeList.length; i++) {
              if (this.iframeList[i].pageTag == 'grafana') {
                this.GrafanaAmountUrl = this.iframeList[i].url
                this.grafanaIframeFlag = false
              } else if (this.iframeList[i].pageTag == 'resource') {
                this.amountUrl = this.iframeList[i].url
                this.iframeFlag = false
              }
            }
            if (this.isRequestHeader) {
              setTimeout(() => {
                const myIframe = document.querySelector('#amountIframe')
                this.populateIframe(myIframe, [['Authorization:', +this.form.desc]])
              }, 0)
            }
          }
        }
      })
    },
    getListIframeUrlZiYuan() {
      this.iframeQuery.pageTag = 'resource'
      listIframeUrl(this.iframeQuery).then(res => {
        if (res.code == 200) {
          this.iframeList = res.data.list
          if (res.data.list.length > 0) {
            for (let i = 0; i < this.iframeList.length; i++) {
              if (this.iframeList[i].pageTag == 'grafana') {
                this.GrafanaAmountUrl = this.iframeList[i].url
                this.grafanaIframeFlag = false
              } else if (this.iframeList[i].pageTag == 'resource') {
                this.amountUrl = this.iframeList[i].url
                this.iframeFlag = false
              }
            }
            if (this.isRequestHeader) {
              setTimeout(() => {
                const myIframe = document.querySelector('#amountIframe')
                this.populateIframe(myIframe, [['Authorization:', +this.form.desc]])
              }, 0)
            }
          }
        }
      })
    },
    /**
     * iframe 添加请求头
     */
    populateIframe(iframe, headers) {
      const xhr = new XMLHttpRequest()
      xhr.open('GET', this.amountUrl)
      xhr.responseType = 'blob'
      headers.forEach((header) => {
        xhr.setRequestHeader(header[0], header[1])
      })
      xhr.onreadystatechange = () => {
        if (xhr.readyState === xhr.DONE) {
          if (xhr.status === 200) {
            // iframe.src = URL.createObjectURL(xhr.response)
            iframe.src = this.amountUrl
          }
        }
      }
      xhr.send()
    },
    handleClick(tab, event) {
      if (tab.name == 'second') {
        this.getListIframeUrlZiYuan()
      }
      // sessionStorage.setItem('currentTab', tab.name)
    },
    // 获取grafana地址
    getOtAppDashboard() {
      otAppDashboard(this.appId).then(
        res => {
          if (res.code == 200) {
            this.dashboardUid = res.data.dashboardUid
            if (res.data.dashboardUid) {
              if (this.isEdit == true) {
                this.iframeUrl = this.pluginUrl + this.dashboardUid
              } else {
                this.iframeUrl = this.pluginUrl + this.dashboardUid + '?kiosk'
              }
            } else {
              this.iframeUr = ''
            }

            if (this.isRequestHeader) {
              setTimeout(() => {
                const myIframe = document.querySelector('#myIframe')
                this.populateIframe(myIframe, [['Authorization', 'Bearer ' + this.config.viewer]])
              }, 0)
            }

            if (res.data.dashboardUid) {
              this.dashFlag = false
            } else {
              this.dashFlag = true
            }
          }
        }
      )
    },
    /** iframe 添加请求头**/
    populateIframe(iframe, headers) {
      const xhr = new XMLHttpRequest()
      xhr.open('GET', this.iframeUrl)
      xhr.responseType = 'blob'
      headers.forEach((header) => {
        // xhr.setRequestHeader('Authorization', "Bearer eyJrIjoiT0tTcG1pUlY2RnVKZTFVaDFsNFZXdE9ZWmNrMkZYbk");
        xhr.setRequestHeader(header[0], header[1])
      })
      xhr.onreadystatechange = () => {
        if (xhr.readyState === xhr.DONE) {
          if (xhr.status === 200) {
            // iframe.src = URL.createObjectURL(xhr.response)
            iframe.src = this.iframeUrl
          }
        }
      }
      xhr.send()
    },
    // 添加
    handleAdd() {
      this.isEdit = false
      if (this.pluginList.length == 0 || this.pluginList == null) {
        this.$message({
          message: '请到插件中心创建插件',
          type: 'warning'
        })
      } else {
        addDashBoard(this.appId).then((res) => {
          this.msgSuccess(res.msg)
          window.location.reload()
        })
      }
    },
    handleUpdate(val) {
      this.isEdit = val
      this.getList()
      // const myIframe = document.querySelector('#myIframe')
      // this.populateIframe(myIframe, [['Authorization', 'Bearer '+this.config.editor]])
      // window.location.reload();
    },
    getAppsScore() {
      this.queryScore.req_applist.push({ app_alias: this.appItem.alias })
      appsScore(this.queryScore).then(res => {
        if (res.code == 200) {
          if (res.data.scores != null && res.data.scores.length > 0) {
            this.ApdexNum = parseFloat(res.data.scores[0].apdex).toFixed(2)
            this.apdex = parseFloat(res.data.scores[0].apdex).toFixed(2) * 100 - 1
          }
        }
      })
    },
    handleAddIframeUrl() {
      this.open = true
      this.title = '请填入需要展示的页面URL'
    },
    handleUpdateIframeUrl() {
      this.reset()
      this.open = true
      this.title = '修改iframe'
      this.form = this.iframeList[0]
    }
  }
}
</script>

<style lang="scss" scoped>
.grid-container{
    width:100%;
    background-color: rgb(255, 255, 255);
    border: 1px solid rgba(36, 41, 46, 0.12);
    position: relative;
    border-radius: 2px;
    height: 100%;
    display: flex;
    flex-direction: column;
    cursor: pointer;
    .grid-header{
      height: 32px;
      display: flex;
      -webkit-box-align: center;
      align-items: center;
      margin-bottom: 0px;
      padding: 0px 8px;
      text-overflow: ellipsis;
      overflow: hidden;
      white-space: nowrap;
      .grid-header-title{
        font-size: 14px;
      // font-weight: 500;
      // margin: 0px 0px 0.45em;
      line-height: 1.57143;
      // letter-spacing: 0.01071em;
      font-family: Inter, Helvetica, Arial, sans-serif;
      }
    }
    .grid-content{
        display: flex;
        overflow: hidden;
        flex-direction: column;
        margin-bottom: 0px;
        margin-right: 0px;
        padding: 12px;
        border-radius: 2px;
        position: relative;
        align-items: center;
        flex-direction: row;
        justify-content: center;
        flex-grow: 1;
        font-size: 46px;
        font-weight: 500;
        line-height: 1.2;
        position: relative;
        z-index: 1;
        text-align: center;
        color: rgb(36, 41, 46);
    }
}
.addCard {
  border: 2px dotted #e9e9e9;
  border-radius: 2px;
  height: 110px;
}
.addCard:hover {
  border-color: #409eff;
  color: #409eff;
  .flex-add {
    color: #409eff;
  }
}
.flex-add {
  display: flex;
  width: 100%;
  height: 100%;
  justify-content: center;
  align-items: center;
  font-size: 16px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: rgba(0, 0, 0, 0.45);
  line-height: 24px;
  cursor: pointer;
  background:#fff;
}
.dataBlock{
    background: rgb(244,245,245);
    padding: 10px 14px;
}
.grafanaEdit{
  position: fixed;
  background-color: #fff;
  border-radius: 15px;
  padding: 4px 15px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  right:10px;
  bottom:50px;
  height: 30px;
  // line-height: 30px;
  text-align: center;
  z-index: 99;
  font-size: 12px;
  color: #303133;
  font-weight: 500;
  .small{
    display: block;
  }
  .big{
    // display: none;
    width:0;
    opacity: 0;
  }
  // background:#1890ff;
}
.grafanaEdit:hover{
  .small{
    display: none;
  }
  .big{
    // display: block;
    opacity: 1;
    width:auto;
    transform: all 0.3;
  }
}
::v-deep .el-tabs__header{
  position: fixed;
  top:50.5px;
  z-index: 8;
  background: #fff;
  width: 88%;
  padding-top:16px;
}
::v-deep .el-tabs__nav-wrap {
    padding-left: 30px;
}
::v-deep .el-tabs__content {
    overflow: hidden;
    position: relative;
    margin-top: 40px;
}
.box-card ::v-deep .el-card__body{
  padding:0!important;
}
.amountIframe{
  // padding:10px;
  position: relative;
  // background: rgb(244, 245, 245);
}
.urlbox{
  width: 700px;
  height: 100vh;
  margin:10px auto;
  .urlbox-title{
    font-size: 16px;
    text-align: center;
    margin-bottom: 12px;
    font-weight: 500;
  }
}
.gc{
    // background: #66DC4A;
  color:#00B54F;
}
.bc{
  color: #60B4F9;
}
.grc{
  color: #8B8B8B;
}
.oc{
  color: #F1A657;
}
.rc{
  color: #d0cbcb;
}
.header{
  position: absolute;
  z-index: 99;
  min-width: 1000px;
  width: 100%;
  border-bottom: 0;
  height: 60px;
  line-height: 60px;
  background: #fff;
  left: 0px;
  .header-right{
      position: absolute;
      right: 0;
      top: 0;
      z-index: 100;
      height: 60px;
      padding-right: 24px;
      padding-left: 200px;
      -webkit-tap-highlight-color: transparent;
  }
}
.dot{
      display: inline-block !important;
      width:8px !important;
      height: 8px !important;
      border-radius: 50% !important;
      background: #1976d2 !important;
      margin-right: 12px !important;
    }
</style>
