<template>
  <div>

    <div class="shadow-content" style="margin-top:20px">
      <div class="warn-content">
        <i class="el-icon-menu"></i>
        基础服务
        <div style="float: right;">
          <el-button type="warning" size="mini" round v-show="nsList.indexOf(namespace) > -1"
            @click="getRepository('base')">新增服务</el-button>
          <el-button type="success" size="mini" round @click="refresh">刷新状态</el-button>
          <el-dropdown>
            <el-button type="primary" size="mini" round v-show="nsList.indexOf(namespace) > -1">
              更多操作
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item @click.native="syncDb">同步线上MySQL</el-dropdown-item>
              <el-dropdown-item @click.native="handleMqSync">同步线上MQ</el-dropdown-item>
              <el-dropdown-item @click.native="clearRedis">清理Redis缓存</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
      </div>
      <el-table :data="FormatTabledata.base" :header-cell-style="{background:'#F3F4F7',color:'#555'}" size="medium"
        align="center" style="width: 100%">
        <el-table-column :index="indexMethod" type="index" label="#" />
        <el-table-column v-if="serviceName!=='rabbitmq'" label="服务名">
          <template slot-scope="scope">
            <i v-if="scope.row.status === 'Normal'" class="el-icon-success" style="color: #67c23a" />
            <i v-else class="el-icon-error" style="color: #f56c6c" />

            <span v-if="scope.row.serviceName === 'consul'">
              <span class="link-type" style="margin-right:5px" @click="openConsole(scope.row)">
                {{ scope.row.serviceName }}
              </span>
            </span>

            <span v-if="scope.row.serviceName === 'redash'">
              <span class="link-type" style="margin-right:5px" @click="openConsole(scope.row)">
                {{ scope.row.serviceName }}
              </span>
            </span>

            <span v-if="scope.row.serviceName === 'rabbitmq'">
              <span class="link-type" style="margin-right:5px" @click="openConsole(scope.row)">
                {{ scope.row.serviceName }}
              </span>

              <!-- <el-popover v-if="moreShow" placement="top-start" trigger="hover" title="本地比线上多出的配置">
                <el-table :data="moreArray" max-height="500">
                  <el-table-column width="100" property="type" label="Type" />
                  <el-table-column width="500" property="value" label="Value" />
                </el-table>
                <i slot="reference" class="el-icon-sort-up" style="color: #67c23a" />
              </el-popover> -->

              <!-- <el-popover v-if="lostShow" placement="top-start" trigger="hover" title="本地比线上缺少的配置">
                <el-table :data="lostArray" max-height="500">
                  <el-table-column width="100" property="type" label="Type" />
                  <el-table-column width="500" property="value" label="Value" />
                </el-table>
                <i slot="reference" class="el-icon-sort-down" style="color: #f56c6c" />
              </el-popover> -->

            </span>
            <span
              v-if="scope.row.serviceName !== 'rabbitmq'&& scope.row.serviceName !== 'consul' && scope.row.serviceName !== 'redash'">{{ scope.row.serviceName }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="lanIp" width="110" label="IP地址" />
        <el-table-column prop="portMappings" label="服务端口">
          <template slot-scope="scope">
            <el-tooltip v-show="scope.row.serviceName === 'redis-sentinel'" placement="top">
              <div slot="content">四个端口分别为一主二从一哨兵<br>哨兵名称：qsmaster，没有密码</div>
              <div><span v-for="item in scope.row.portMappings" :key="item.port">{{ item.nodePort }}->{{ item.port }}
                </span></div>
            </el-tooltip>
            <span v-for="item in scope.row.portMappings" v-show="scope.row.serviceName !== 'redis-sentinel'"
              :key="item.port">{{ item.nodePort }}->{{ item.port }} </span>
          </template>
        </el-table-column>
        <el-table-column prop="image" label="镜像">
          <template slot-scope="scope">
            {{ scope.row.image.split('/')[2] }}
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" width="200" label="创建时间" />
        <el-table-column prop="status" width="100" label="运行状态">
          <template slot-scope="scope">
            <el-tag type="success" v-if="scope.row.status === 'Normal'">正常</el-tag>
            <el-tag type="warning" v-else-if="scope.row.status === 'Pending'">Pod等待中</el-tag>
            <el-tag v-else-if="scope.row.status === 'Waiting'">服务启动中</el-tag>
            <el-tag v-else-if="scope.row.status === 'PodScheduling'">Pod调度中</el-tag>
            <el-tag v-else-if="scope.row.status === 'ContainerCreating'">容器创建中</el-tag>
            <el-tag type="danger" v-else-if="scope.row.status === 'Terminating'">删除中</el-tag>
            <el-tag type="info" v-else>未知状态</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="80" fixed="right">
          <template slot-scope="scope">
            <el-dropdown>
              <el-button type="primary" size="mini">
                更多
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item @click.native="getServiceDetails(scope.row)">
                  <i class="el-icon-document"></i>
                  详细信息
                </el-dropdown-item>
                <el-dropdown-item v-show="nsList.indexOf(namespace) > -1" @click.native="restartService(scope.row)">
                  <i class="el-icon-refresh"></i>
                  重置服务
                </el-dropdown-item>
                <el-dropdown-item v-show="nsList.indexOf(namespace) > -1" style="color: red"
                  @click.native="deleteService(scope.row) ">
                  <i class="el-icon-delete"></i>
                  删除服务
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 业务服务 -->
    <div v-for="(item,index) in typeList" :key="index" class="shadow-content">
      <div class="warn-content">
        <i class="el-icon-menu"></i>
        {{ item.projectType.toUpperCase() }} 服务
        <div style="float: right">
          <el-button v-show="nsList.indexOf(namespace) > -1" type="warning" size="mini" round
            @click="getRepository(item.projectType)">新增服务</el-button>
          <el-button type="success" size="mini" round @click="refresh">刷新状态</el-button>
        </div>
      </div>
      <el-table :data="FormatTabledata[item.projectType]" :header-cell-style="{background:'#F3F4F7',color:'#555'}"
        size="medium" align="center" style="width: 100%">
        <el-table-column :index="indexMethod" label="#" type="index" />
        <el-table-column prop="serviceName" label="服务名">
          <template slot-scope="scope">
            <i v-if="scope.row.status === 'Normal'" class="el-icon-success" style="color: #67c23a" />
            <i v-else class="el-icon-error" style="color: #f56c6c" />
            <span class="link-type" @click="handleDetail(scope.row)">{{ scope.row.serviceName }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="image" label="镜像">
          <template slot-scope="scope">
            {{ scope.row.image.split(':')[1] }}
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" width="200" label="创建时间" />
        <el-table-column prop="status" width="140" label="运行状态">
          <template slot-scope="scope">
            <el-tag type="success" v-if="scope.row.status === 'Normal'">正常</el-tag>
            <el-tag type="warning" v-else-if="scope.row.status === 'Pending'">Pod等待中</el-tag>
            <el-tag v-else-if="scope.row.status === 'Waiting'">服务启动中</el-tag>
            <el-tag v-else-if="scope.row.status === 'PodScheduling'">Pod调度中</el-tag>
            <el-tag v-else-if="scope.row.status === 'ContainerCreating'">容器创建中</el-tag>
            <el-tag type="danger" v-else-if="scope.row.status === 'Terminating'">删除中</el-tag>
            <el-tag type="info" v-else>未知状态</el-tag>
          </template>
        </el-table-column>

        <el-table-column v-if="item.projectType==='java'" show-overflow-tooltip width="60" label="Mock">
          <template slot-scope="scope">
            <el-tooltip v-show="scope.row.labels.mock==='1'" placement="top">
              <div slot="content">使用apollo集群k8s-mock进行启动</div>
              <span v-if="scope.row.labels.mock==='1'">是</span>
            </el-tooltip>
          </template>
        </el-table-column>

        <el-table-column v-if="item.projectType==='java'" width="150" label="调试">
          <template slot-scope="scope">
            <span
              v-if="scope.row.serviceType==='NodePort'">{{ scope.row.lanIp }}:{{ scope.row.portMappings[1].nodePort }}</span>
          </template>
        </el-table-column>

        <el-table-column label="控制台/日志/Kibana" width="170">
          <template slot-scope="scope">
            <el-tooltip class="item" effect="dark" content="控制台" placement="top">
              <el-button type="primary" icon="el-icon-time" circle @click="linkShell(scope.row)" />
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="日志" placement="top">
              <el-button type="success" icon="el-icon-time" circle @click="linkLog(scope.row)" />
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="Kibana(如果没有数据，需删除当前服务后重新添加)" placement="top">
              <el-button type="info" icon="el-icon-time" circle @click="linkKibana(scope.row)" />
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="80" fixed="right">
          <template slot-scope="scope">
            <el-dropdown>
              <el-button type="primary" size="mini">
                更多
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item @click.native="getServiceDetails(scope.row)">
                  <i class="el-icon-document"></i>
                  详细信息
                </el-dropdown-item>
                <el-dropdown-item v-show="nsList.indexOf(namespace) > -1"
                  @click.native="openUpdateServiceDialog(scope.row)">
                  <i class="el-icon-refresh"></i>
                  更新服务
                </el-dropdown-item>

                <el-dropdown-item v-show="nsList.indexOf(namespace) > -1" @click.native="restartService(scope.row)">
                  <i class="el-icon-refresh"></i>
                  重置服务
                </el-dropdown-item>

                <el-dropdown-item v-show="nsList.indexOf(namespace) > -1" style="color: red"
                  @click.native="deleteService(scope.row, item) ">
                  <i class="el-icon-delete"></i>
                  删除服务
                </el-dropdown-item>

              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!--添加服务dialog-->
    <el-dialog :visible.sync="dialogVisible" title="添加服务">
      <el-alert :closable="false" title="温馨提醒" type="warning" description="该操作会创建这个服务对应的镜像分支。" />
      <p class="title-sub">选择服务</p>
      <el-row :gutter="20">
        <el-col :span="14">
          <el-select v-model="reponame" clearable filterable class="elSelect" placeholder="请选择服务，支持模糊搜索"
            @change="getTag">
            <el-option v-for="(item,index) in options" :key="index" :label="item.repoName.split('/')[1]"
              :value="item.repoName" />
          </el-select>
        </el-col>
      </el-row>

      <div v-show="is_mock">
        <p class="title-sub">是否使用mock<span style="font-size: 12px">(使用apollo集群k8s-mock进行启动)</span></p>
        <el-row :gutter="20">
          <el-col :span="14">
            <el-select v-model="mock.key" filterable clearable class="elSelect" placeholder="请选择是否使用mock">
              <el-option v-for="item in debugOptions" :key="item.key" :label="item.display_name" :value="item.key" />
            </el-select>
          </el-col>
        </el-row>
      </div>

      <div v-show="is_show">
        <p class="title-sub">服务名称<span style="font-size: 12px">(创建多个mysql时需要填写此字段)</span></p>
        <el-row :gutter="20">
          <el-col :span="14">
            <el-input v-model="mysqlName" placeholder="请输入服务名称" clearable />
          </el-col>
        </el-row>
      </div>

      <p class="title-sub">选择镜像</p>
      <el-row :gutter="20">
        <el-col :span="14">
          <el-select v-model="tagName" filterable clearable class="elSelect" placeholder="请选择镜像，支持模糊搜索">
            <el-option v-for="(item,index) in tagOptions" :key="index" :label="item.TagName" :value="item.TagName" />
          </el-select>
        </el-col>
      </el-row>

      <p v-if="label==='node'||label==='java'||label==='go'" class="title-sub">是否调试模式<span
          style="font-size: 12px">(执行测试时选择默认选项否即可)</span> </p>
      <el-row v-if="label==='node'||label==='java'||label==='go'" :gutter="20">
        <el-col :span="14">
          <el-select v-model="debug.key" filterable clearable class="elSelect" placeholder="请选择是否调试模式，执行测试时请选择否">
            <el-option v-for="item in debugOptions" :key="item.key" :label="item.display_name" :value="item.key" />
          </el-select>
        </el-col>
      </el-row>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="createService">确 定</el-button>
      </span>
    </el-dialog>

    <!--更新服务的弹框-->
    <el-dialog :visible.sync="updateDialogVisible" title="更新服务">
      <el-alert :closable="false" title="温馨提醒" type="warning" description="警告:该操作将会更新这个服务为指定版本，在这个pod上做的所有操作将会丢失。" />
      <p class="title-sub">选择服务</p>
      <el-row :gutter="20">
        <el-col :span="14">
          <el-input v-model="serviceName" :disabled="true" placeholder="请输入内容" />
        </el-col>
      </el-row>

      <p class="title-sub">选择镜像</p>
      <el-row :gutter="20">
        <el-col :span="14">
          <el-select v-model="tagName" filterable clearable class="elSelect" placeholder="请选择镜像,支持模糊搜索">
            <el-option v-for="(item,index) in tagOptions" :key="index" :label="item.TagName" :value="item.TagName" />
          </el-select>
        </el-col>
      </el-row>

      <span slot="footer" class="dialog-footer">
        <el-button @click="updateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateService()">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 详细信息对话框 -->
    <el-dialog :visible.sync="centerDialogVisible" title="详细信息" height="500px" center>
      <div class="editor-container">
        <json-viewer :expand-depth=3 :value='detailValue' style="margin-top:-25px"></json-viewer>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="centerDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="centerDialogVisible = false">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 同步MQ对话框 -->
    <el-dialog title="同步MQ" :visible.sync="mqSyncDialogVisible" width="50%">
      <el-form ref="mqDataForm" label-position="left" label-width="130px" style="width: 95%; margin-left:20px;">
        <el-form-item label="Namespace名称">
          <el-input v-model="namespace" :disabled="true" />
        </el-form-item>
        <el-form-item label="服务地址">
          <el-input v-model="mqUrl" :disabled="true" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="mqSyncDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="syncMQ()">开始同步</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getServiceList,
  getSingleTypeApp,
  getImageList,
  createK8sService,
  getDockerProjectDetail,
  getServiceDetail,
  serviceRedeploy,
  serviceUpdate,
  serviceDelete,
  getDockerProjectType,
  syncMq,
  flushRedis
} from '@/api/k8s'
import bus from '@/utils/bus'
export default {
  data() {
    return {
      namespace: window.sessionStorage.getItem('env'),
      FormatTabledata: [],
      moreArray: [],
      lostArray: [],
      moreShow: false,
      lostShow: false,
      // 项目类型列表
      typeList: [],
      dialogVisible: false,
      centerDialogVisible: false,
      is_mock: false,
      is_show: false,
      label: '',
      updateDialogVisible: false,
      reponame: '',
      options: [],
      mock: {},
      server: '',
      debug: {},
      debugOptions: [
        { key: 1, display_name: '是' },
        { key: 0, display_name: '否' }
      ],
      tagOptions: [],
      tagName: '',
      detailValue: {},
      mysqlName: '',
      // 当前选中的项目名
      serviceName: '',
      updateServiceParams: {},
      mqSyncDialogVisible: false,
      mqUrl: '',
      mqDataForm: {},
      loadingOptions: {
        text: '加载中...',
        lock: true,
        spinner: 'el-icon-loading',
        background: 'rgba(0,0,0,0.7)'
      },
      nsList: window.sessionStorage.getItem('nsList').split(',')
    }
  },
  created() {
    bus.$on('TransEnv', (name) => {
      this.namespace = name
      this.getServiceList()
    })

    getDockerProjectType({}).then((resp) => {
      this.typeList = resp.data.data
    })
  },
  methods: {
    indexMethod(index) {
      return index + 1
    },
    array2Object(original) {
      // 将数组转成对象存储
      this.FormatTabledata = {}
      original.forEach((item, index) => {
        if (item !== null) {
          if (
            Object.keys(this.FormatTabledata).indexOf(item.labels.type) > -1
          ) {
            this.FormatTabledata[item.labels.type].push(item)
          } else {
            this.FormatTabledata[item.labels.type] = []
            this.FormatTabledata[item.labels.type].push(item)
          }
        }
      })
    },
    // 获取服务列表
    getServiceList() {
      const tLoading = this.$loading.service(this.loadingOptions)
      getServiceList({ namespace: this.namespace })
        .then((resp) => {
          const serviceList = resp.data.data
          this.array2Object(serviceList)
          tLoading.close()
        })
        .catch(() => {
          tLoading.close()
        })
    },
    // 刷新，重新获取服务列表
    refresh() {
      this.getServiceList()
    },
    // 新增服务，获取服务列表
    getRepository(label) {
      this.label = label
      this.reponame = ''
      this.tagName = ''
      this.options = []
      this.tagOptions = []
      this.is_mock = label === 'java'
      this.is_show = false
      this.debug = { key: 0, display_name: '否' }
      this.mock = { key: 0, display_name: '否' }
      if (label === 'base') {
        getSingleTypeApp({ namespace: 'qa-base', type: label }).then((resp) => {
          this.options = resp.data.data.RepoInfo
        })
      } else {
        getSingleTypeApp({ namespace: 'qa-test', type: label }).then((resp) => {
          this.options = resp.data.data.RepoInfo
        })
      }

      this.dialogVisible = true
    },
    // 根据repoName获取镜像列表
    getTag() {
      getImageList({ repoName: this.reponame }).then((resp) => {
        this.tagOptions = resp.data.data.TagInfo
        this.tagName = resp.data.data.TagInfo[0].TagName
      })
      getDockerProjectDetail({ projectName: this.reponame.split('/')[1] }).then(
        (resp) => {
          this.domain = resp.data.data.hostName
        }
      )
    },
    // 同步数据库
    syncDb() {
      this.$router.push('/effect/dbsync')
    },
    // 打开MQ同步对话框
    handleMqSync() {
      getServiceDetail({
        namespace: this.namespace,
        serviceType: 'base',
        serviceName: 'rabbitmq'
      }).then((resp) => {
        if (resp.data.data != null) {
          this.mqUrl =
            resp.data.data.lanIp + ':' + resp.data.data.portMappings[1].nodePort
        } else {
          return this.$message.error('当前环境没有MQ！')
        }
      })
      this.mqSyncDialogVisible = true
    },
    // 同步MQ
    syncMQ() {
      var formdata = new FormData()
      formdata.set('host', this.mqUrl)
      syncMq(formdata).then((resp) => {
        if (resp.data.data === true) {
          this.mqSyncDialogVisible = false
          return this.$message.success('同步成功！')
        } else {
          return this.$message.error('同步失败！')
        }
      })
    },
    // 清空redis
    clearRedis() {
      this.$confirm(
        `此操作将清空${this.namespace}环境所有Redis缓存, 是否继续?`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        var formdata = new FormData()
        formdata.set('namespace', this.namespace)
        flushRedis(formdata).then((resp) => {
          if (resp.data.data) {
            return this.$message.success(resp.data.msg)
          } else {
            return this.$message.error(resp.data.msg)
          }
        })
      })
    },
    // 获取服务详情
    getServiceDetails(service) {
      getServiceDetail({
        namespace: this.namespace,
        serviceType: service.labels.type,
        serviceName: service.serviceName
      }).then((resp) => {
        this.detailValue = resp.data.data
        this.centerDialogVisible = true
      })
    },
    // 重启服务
    restartService(service) {
      var formdata = new FormData()
      formdata.set('namespace', this.namespace)
      formdata.set('podName', service.podName)
      serviceRedeploy(formdata).then((resp) => {
        if (resp.data.data === true) {
          this.getServiceList()
          return this.$message.success(`服务${service.serviceName}重置成功！`)
        } else {
          this.getServiceList()
          return this.$message.error(`服务${service.serviceName}重置失败！`)
        }
      })
    },
    // 打开更新服务对话框
    openUpdateServiceDialog(service) {
      console.log(service)
      this.updateDialogVisible = true
      this.serviceName = service.serviceName
      this.updateServiceParams = {}
      this.updateServiceParams['namespace'] = this.namespace
      this.updateServiceParams['serviceName'] = service.serviceName
      this.updateServiceParams['type'] = service.labels.type
      this.updateServiceParams['label'] = service.labels.type
      this.updateServiceParams['debug'] =
        service.serviceType === 'NodePort' ? 1 : 0
      this.updateServiceParams['mock'] = service.labels.mock
      // 获取domain
      getDockerProjectDetail({ projectName: service.serviceName }).then(
        (resp) => {
          this.updateServiceParams['domain'] =
            resp.data.data.hostName.split('.')[0]
        }
      )
      // 获取镜像列表
      getImageList({
        repoName: 'qa-test/' + service.serviceName
      }).then((resp) => {
        if (resp.data.data.TagCount > 0) {
          this.tagOptions = resp.data.data.TagInfo
          this.reponame = resp.data.data.RepoName
          // 默认选中第一个
          this.tagName = resp.data.data.TagInfo[0].TagName
          this.server = resp.data.data.Server
        }
      })
    },
    // 调用接口更新服务
    updateService() {
      this.updateServiceParams['image'] =
        'qa-test/' + this.serviceName + ':' + this.tagName
      serviceUpdate(this.updateServiceParams).then((resp) => {
        if (resp.data.data === true) {
          // this.getServiceList()
          this.updateDialogVisible = false
          return this.$message.success('更新成功！')
        } else {
          return this.$message.error('更新失败！')
        }
      })
    },
    // 删除服务
    deleteService(service) {
      this.$confirm(
        `此操作将删除 ${service.serviceName} 服务, 是否继续?`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        var formdata = new FormData()
        formdata.set('namespace', this.namespace)
        formdata.set('serviceName', service.serviceName)
        serviceDelete(formdata).then((resp) => {
          if (resp.data.data === true) {
            this.getServiceList()
            return this.$message.success('删除成功！')
          } else {
            return this.$message.error('删除失败！')
          }
        })
      })
    },
    // 创建服务
    createService() {
      createK8sService({
        namespace: this.namespace,
        serviceName: this.reponame.split('/')[1],
        type: this.label === 'base' ? this.reponame.split('/')[1] : this.label,
        label: this.label,
        domain: this.domain === undefined ? '' : this.domain.split('.')[0],
        debug: this.debug.key,
        mock: this.mock.key,
        image: `${this.reponame}:${this.tagName}`
      }).then((resp) => {
        if (resp.data.data) {
          this.dialogVisible = false
          this.getServiceList()
          return this.$message.success('创建成功！')
        } else {
          return this.$message.error(resp.data.msg)
        }
      })
    },
    refreshInterval(value) {},
    linkShell(scopeData) {
      window.open(
        `http://172.30.220.24:9600/static/terminal.html?namespace=${this.namespace}&pod=${scopeData.podName}`,
        '_blank'
      )
    },
    linkKibana(scopeData) {
      const sn = scopeData.serviceName
      const ns = this.namespace
      // const url = `http://kibana-new.quantgroups.com/app/kibana#/discover?_g=(filters:!(),refreshInterval:(pause:!f,value:5000),time:(from:now-2m,to:now))&_a=(columns:!(message),filters:!(('$state':(store:appState),meta:(alias:!n,disabled:!f,index:c7d3a2f0-b760-11e9-a937-01944fbd6d1d,key:k8s.namespace,negate:!f,params:(query:${ns}),type:phrase,value:${ns}),query:(match:(k8s.namespace:(query:${ns},type:phrase)))),('$state':(store:appState),meta:(alias:!n,disabled:!f,index:c7d3a2f0-b760-11e9-a937-01944fbd6d1d,key:k8s.svcname,negate:!f,params:(query:${sn}),type:phrase,value:${sn}),query:(match:(k8s.svcname:(query:${sn},type:phrase))))),index:c7d3a2f0-b760-11e9-a937-01944fbd6d1d,interval:auto,query:(language:kuery,query:''),sort:!(logtime,desc))`
      const url = `http://kibana.liangkebang.com/app/kibana#/discover?_g=(filters:!(),refreshInterval:(pause:!t,value:5000),time:(from:now-15m,to:now))&_a=(columns:!(message),filters:!(('$state':(store:appState),meta:(alias:!n,disabled:!f,index:'9d74e370-c834-11eb-b8c6-3bc355f78a8d',key:k8s.namespace,negate:!f,params:(query:${ns}),type:phrase,value:${ns}),query:(match:(k8s.namespace:(query:${ns},type:phrase)))),('$state':(store:appState),meta:(alias:!n,disabled:!f,index:'9d74e370-c834-11eb-b8c6-3bc355f78a8d',key:k8s.svcname,negate:!f,params:(query:${sn}),type:phrase,value:${sn}),query:(match:(k8s.svcname:(query:${sn},type:phrase))))),index:'9d74e370-c834-11eb-b8c6-3bc355f78a8d',interval:auto,query:(language:kuery,query:''),sort:!(logtime,desc))`
      window.open(`${url}`, '_blank')
    },
    linkLog(scopeData) {
      let path = ''
      if (scopeData.labels.type === 'ui') {
        path =
          '/usr/local/openresty/nginx/logs/access.log /usr/local/openresty/nginx/logs/error.log'
      } else {
        path = `/home/quant_group/logs/*.log`
      }
      window.open(
        `http://172.30.220.24:9600/static/logs.html?namespace=${this.namespace}&pod=${scopeData.podName}&paths=${path}`,
        '_blank'
      )
    },
    openConsole(data) {
      let port
      if (data.serviceName === 'rabbitmq') {
        port = data.portMappings.filter((item) => item.port === 15672)[0]
          .nodePort
      }
      if (data.serviceName === 'consul') {
        port = data.portMappings.filter((item) => item.port === 8500)[0]
          .nodePort
      }
      if (data.serviceName === 'redash') {
        port = data.portMappings.filter((item) => item.port === 5000)[0]
          .nodePort
      }
      window.open(`http://${data.lanIp}:${port}/`, '_blank')
    },
    handleDetail(data) {
      window.open(`https://${data.host}/`, '_blank')
    }
  }
}
</script>

<style lang="less" scoped>
.shadow-content {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-top: 30px;
}
.warn-content {
  background: rgba(66, 185, 131, 0.1);
  border-radius: 2px;
  padding: 16px;
  padding: 1rem;
  line-height: 1.6rem;
  word-spacing: 0.05rem;

  a {
    color: #42b983;
    font-weight: 600;
  }
}
.title-sub {
  margin-top: 30px;
  font-size: 15px;
}
.elSelect {
  width: 100%;
}
.port {
  display: inline-block;
  padding: 2px;
  /*background: #f0f0f0;*/
  border: 1px solid #f0f2f5;
  margin: 2px;
}
.link-type,
.link-type:focus {
  color: #337ab7;
  cursor: pointer;

  &:hover {
    color: rgb(32, 160, 255);
  }
}
</style>
