<template>
  <div >
    <div style="padding:5px 20px;height: 30px;" >
      <div style="float:right;font-size:13px">
        <span>自动刷新</span>
        <el-switch v-model="timer" @change="refreshInterval"/>
        <span class="link-type" style="margin-left:20px" @click="openConf()">遇到问题?</span>
      </div>
    </div>

    <el-alert
      v-show="notify.length>0"
      type="info"
      style=" font-size: 14px;"
      show-icon>
      <slot name="description">
        <p v-for="item in notify" :key="item._id">{{ item.content }}</p>
      </slot>
    </el-alert>

    <div class="shadow-content" style="margin-top:20px" >
      <div class="warn-content">
        <svg-icon icon-class="service"/>
        基础服务
        <div style="float: right;">
          <el-button type="warning" size="mini" round @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>
              更多操作
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item @click.native="syncDb">同步线上MySQL</el-dropdown-item>
              <el-dropdown-item @click.native="syncMq">同步线上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"/>
        <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 | formatImages }}
          </template>
        </el-table-column>
        <el-table-column
          prop="createdAt"
          width="120"
          label="创建时间"
        />
        <el-table-column
          prop="status"
          width="100"
          label="运行状态">
          <template slot-scope="scope">
            {{ scope.row.status | formatStatus }}
          </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)">
                  <svg-icon icon-class="detail"/>
                  详细信息
                </el-dropdown-item>
                <el-dropdown-item @click.native="restartService(scope.row)">
                  <svg-icon icon-class="restart"/>
                  重置服务
                </el-dropdown-item>
                <el-dropdown-item @click.native="updateDeploy(scope.row)">
                  <svg-icon icon-class="f5"/>
                  更新部署
                </el-dropdown-item>
                <el-dropdown-item v-permission="['admin']" style="color: red" @click.native="deleteService(scope.row) ">
                  <svg-icon icon-class="delete"/>
                  删除服务
                </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">
        <svg-icon icon-class="service"/>
        {{ item._id.toUpperCase() }} 服务
        <div style="float: right">
          <el-button type="primary" size="mini" round @click="deployMaster(FormatTabledata[item._id])">一键部署master</el-button>
          <el-button type="warning" size="mini" round @click="getRepository(item._id)">新增服务</el-button>
          <el-button type="success" size="mini" round @click="refresh">刷新状态</el-button>
          <el-button type="danger" size="mini" round @click="restartAll(FormatTabledata[item._id])">重置所有服务</el-button>
        </div>
      </div>
      <el-table
        :data="FormatTabledata[item._id]"
        :header-cell-style="{background:'#F3F4F7',color:'#555'}"
        size="medium"
        align="center"
        style="width: 100%">
        <el-table-column
          :index="indexMethod"
          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 | filterTag }}
          </template>
        </el-table-column>
        <el-table-column
          prop="createdAt"
          width="120"
          label="创建时间"
        />
        <el-table-column
          prop="status"
          width="100"
          label="运行状态">
          <template slot-scope="scope">
            {{ scope.row.status | formatStatus }}
          </template>
        </el-table-column>

        <el-table-column
          v-if="item._id==='java'"
          show-overflow-tooltip
          width="90"
          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._id==='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)">
                  <svg-icon icon-class="detail"/>
                  详细信息
                </el-dropdown-item>
                <el-dropdown-item @click.native="updateService(scope.row)">
                  <svg-icon icon-class="f5"/>
                  更新服务
                </el-dropdown-item>

                <el-dropdown-item @click.native="restartService(scope.row)">
                  <svg-icon icon-class="restart"/>
                  重置服务
                </el-dropdown-item>
                <el-dropdown-item @click.native="updateDomain(scope.row)">
                  <svg-icon icon-class="doamin"/>
                  更新域名
                </el-dropdown-item>

                <el-dropdown-item style="color: red" @click.native="deleteService(scope.row, item) ">
                  <svg-icon icon-class="delete"/>
                  删除服务
                </el-dropdown-item>

                <el-dropdown-item @click.native="updateDeploy(scope.row)">
                  <svg-icon icon-class="f5"/>
                  更新部署
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!--添加服务dialog-->
    <el-dialog
      :visible.sync="dialogVisible"
      :title="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.appname.split(':')[0]"
              :value="item.tag.split(':')[0]"/>
          </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-permission="['admin']" 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>

      <div v-show="is_wechat">
        <p class="title-sub">是否微信模式<span style="font-size: 12px">(测试微信时选择是)</span></p>
        <el-row :gutter="20">
          <el-col :span="14">
            <el-select v-model="wechat.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>
      </div>

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

    <!--更新服务的弹框-->
    <el-dialog
      :visible.sync="updateDialog"
      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="updateDialog = false">取 消</el-button>
        <el-button type="primary" @click="updateClusterService()">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      :visible.sync="centerDialogVisible"
      title="详细信息"
      height="500px"
      center>
      <div class="editor-container">
        <json-editor ref="jsonEditor" v-model="value"/>
      </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>
    <el-dialog :visible.sync="dialogHost" title="更新域名">
      <el-form ref="form" :model="form" :rules="rules">
        <el-form-item label="域名" prop="host">
          <el-input v-model="form.host" autocomplete="off"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogHost=false">取 消</el-button>
        <el-button type="primary" @click="submitHost('form')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  fetchK8sdetail,
  fetchUserrepository,
  fetchTaglist,
  CreateCluService,
  fetchServiceDetails,
  modifyCluService,
  modifyDeploy,
  // fetchServiceInstance,
  deleteClusterService,
  redeployClusterService,
  flushRedis,
  modifyIngressHost,
  ingressHost,
  mqDiff
} from '@/api/docker'
import { getType } from '@/api/proconfig'
import JsonEditor from '@/components/JsonEditor'
import permission from '@/directive/permission/index.js' // 权限判断指令
import { getHostName } from '@/api/proconfig'
import { getNotify } from '@/api/notify'
import { buildJenkinsJob } from '@/api/holmes'
export default {
  components: { JsonEditor },
  directives: { permission },
  data() {
    return {
      QATEST: 'qa-test',
      debugOptions: [
        { key: '"1"', display_name: '是' },
        { key: '"0"', display_name: '否' }
      ],
      debug: {},
      mock: {},
      wechat: {},
      centerDialogVisible: false,
      namespace: null,
      tableData: [],
      options: [],
      tagOptions: [],
      FormatTabledata: {},
      reponame: '',
      is_show: false,
      is_wechat: false,
      is_mock: false,
      mysqlName: '',
      typeList: [],
      tagName: '',
      server: '',
      label: '',
      domain: '',
      type: '',
      value: null,
      images: null,
      ingressName: null,
      dialogVisible: false,
      title: '添加服务',
      formInline: {
        user: '',
        region: ''
      },
      updateDialog: false,
      serviceName: '',
      form: {
        host: ''
      },
      rules: {
        host: [
          { required: true, message: '请输入更新的域名信息', trigger: 'blur' }
        ]
      },
      dialogHost: false,
      timer: this.$store.getters.timer,
      timerFunction: null,
      moreShow: false,
      lostShow: false,
      moreArray: [],
      lostArray: [],
      notify: []
    }
  },
  created() {
    getType().then(res => {
      this.typeList = res.data
    })
    const curDate = new Date()
    const date = new Date(curDate.getTime() - 2 * 24 * 60 * 60 * 1000)
    getNotify({ updatedAt: { $gte: date }}).then(res => {
      this.notify = res.data
    })
    this.namespace = this.$route.params.name
    clearInterval(this.timerFunction)
    this.timerFunction = null
    if (this.timer) {
      this.refreshInterval(this.timer)
    } else {
      this.getServicelist()
      this.fetchRabbitmqDetails()
    }
  },
  destroyed() {
    // 每次离开当前界面时，清除定时器
    clearInterval(this.timerFunction)
    this.timerFunction = null
  },
  methods: {
    getServicelist() {
      fetchK8sdetail({ 'namespace': this.namespace }).then(res => {
        const servicelist = res.data.services
        this.array2Object(servicelist)
      })
    },

    refresh() {
      this.getServicelist()
    },

    // 重置所有服务
    restartAll(serviceList) {
      for (var x in serviceList) {
        this.restartService(serviceList[x])
      }
    },

    // 一键部署master
    deployMaster(serviceList) {
      for (var x in serviceList) {
        buildJenkinsJob({
          type: serviceList[x].labels.type,
          project: serviceList[x].serviceName,
          branch: 'master',
          namespace: this.namespace
        }).then((resp) => {
          this.$message({
            type: 'success',
            message: '服务' + serviceList[x].serviceName + '部署master分支成功!'
          })
        })
      }
    },

    refreshInterval(value) {
      this.$store.dispatch('changeSwitch', value)
      if (value) {
        this.getServicelist()
        this.timerFunction = setInterval(this.getServicelist, 15000)
      } else {
        clearInterval(this.timerFunction)
      }
    },

    openConf() {
      window.open('http://confluence.quantgroup.cn/pages/viewpage.action?pageId=20546803', '_blank')
    },

    getRepository(label) {
      this.label = label
      this.reponame = ''
      this.tagName = ''
      this.options = []
      this.tagOptions = []
      this.is_show = false
      this.is_wechat = false
      this.is_mock = label === 'java'
      this.debug = { key: '"0"', display_name: '否' }
      this.wechat = { key: '"0"', display_name: '否' }
      this.mock = { key: '"0"', display_name: '否' }
      const repoName = label === 'base' ? 'base' : 'test'
      fetchUserrepository({ 'namespace': 'qa-' + repoName, type: label }).then(res => {
        this.options = res.data
      })
      this.dialogVisible = true
    },
    getTag() {
      const realName = this.reponame.split('/')[1]
      this.is_show = realName === 'mysql'
      this.is_wechat = realName === 'h5-ui'
      // this.is_mock = realName === 'gu-bei' || realName === 'clotho' || realName === 'ploutos' || realName === 'mo-clotho' || realName === 'koala'
      this.mock = { key: '"0"', display_name: '否' }
      this.wechat = { key: '"0"', display_name: '否' }

      getHostName({ project_name: this.reponame.split('/')[1] }).then(res => {
        if (res.data) {
          this.domain = res.data.host_name
        }
        return fetchTaglist({ reponame: this.reponame })
      }).then(res => {
        if (res.data.tagCount) {
          this.tagOptions = res.data.tagInfo
          this.tagName = res.data.tagInfo[0].tagName
        }
      })
    },
    createClusterService() {
      const self = this
      this.type = this.label === 'base' ? this.reponame.split('/')[1] : this.label
      let serviceName = ''
      if (this.is_show && this.mysqlName !== '') {
        serviceName = this.reponame.split('/')[1] + '-' + this.mysqlName
      } else {
        serviceName = this.reponame.split('/')[1]
      }
      CreateCluService({
        serviceName: serviceName,
        namespace: this.namespace,
        image: `${this.reponame}:${this.tagName}`,
        label: this.label,
        type: this.type,
        domain: this.domain.split('.')[0],
        debug: this.debug.key,
        wechat: this.wechat.key,
        mock: this.mock.key
      }).then(res => {
        this.$message({
          message: res.data,
          type: 'success',
          duration: 1000,
          onClose() {
            self.dialogVisible = false
            self.getServicelist()
          }
        })
      })
    },
    handleDetail(data) {
      window.open(`https://${data.host}/`, '_blank')

      // ingressHost({ namespace: data.namespace, serviceName: data.serviceName }).then(res => {
      //   const url = res.data.body.spec.rules[0].host
      //   window.open(`http://${url}/`, '_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')
    },
    getServiceDetails(value) {
      fetchServiceDetails({ serviceName: value.serviceName, namespace: this.namespace, type: value.labels.type }).then(res => {
        this.centerDialogVisible = true
        this.value = res.data
      })
    },

    fetchRabbitmqDetails() {
      fetchServiceDetails({ namespace: this.namespace, serviceName: 'rabbitmq', type: 'base' })
        .then(res => {
          const data = res.data
          for (const port of data.portMappings) {
            if (port.port === 15672) {
              mqDiff({ host: `${data.lanIp}:${port.nodePort}` }).then(res => {
                const mqDiffData = res.data
                this.moreShow = mqDiffData.more.show
                this.lostShow = mqDiffData.lost.show

                for (const i in mqDiffData.more) {
                  if (mqDiffData.more[i] instanceof Array) {
                    this.moreArray.push({ type: i, value: mqDiffData.more[i].join(', ') })
                  }
                }
                for (const i in mqDiffData.lost) {
                  if (mqDiffData.lost[i] instanceof Array) {
                    this.lostArray.push({ type: i, value: mqDiffData.lost[i].join(', ') })
                  }
                }
              })
            }
          }
        })
    },

    submitHost(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          modifyIngressHost({
            namespace: this.namespace,
            serviceName: this.ingressName,
            host: this.form.host
          }).then(res => {
            this.$message({
              message: '域名更新成功',
              type: 'success'
            })
            this.dialogHost = false
            this.getServicelist()
          })
        }
      })
    },

    updateService(value) {
      this.updateDialog = true
      this.serviceName = value.serviceName
      this.type = value.labels.type
      this.tagOptions = []
      fetchTaglist({ reponame: this.QATEST + '/' + this.serviceName }).then(res => {
        if (res.data.tagCount) {
          this.tagOptions = res.data.tagInfo
          this.reponame = res.data.reponame
          this.tagName = res.data.tagInfo[0].tagName
          this.server = res.data.server
        }
      })
    },

    updateDeploy(value) {
      const self = this
      const image = value.image.split('/').slice(1).join('/')
      const mock = value.labels.mock ? `'${value.labels.mock}'` : value.labels.mock
      modifyDeploy({ serviceName: value.serviceName, image, namespace: this.namespace, type: value.labels.type, mock }).then(res => {
        this.$message({
          message: `更新${value.serviceName}成功`,
          type: 'success',
          duration: 1000,
          onClose() {
            self.getServicelist()
          }
        })
      })
    },

    updateClusterService() {
      const self = this
      modifyCluService({ serviceName: this.serviceName, image: `${this.reponame}:${this.tagName}`, namespace: this.namespace, type: this.type }).then(res => {
        this.$message({
          message: `更新${this.serviceName}成功`,
          type: 'success',
          duration: 1000,
          onClose() {
            self.updateDialog = false
            self.getServicelist()
          }
        })
      })
    },
    restartService(data) {
      redeployClusterService({ namespace: this.namespace, podName: data.podName, serviceName: data.serviceName }).then(res => {
        this.$message({
          type: 'success',
          message: `服务${data.serviceName}重置成功!`
        })
      })
    },
    syncDb() {
      this.$router.push({
        path: '/dbsync',
        query: { namespace: this.namespace }
      })
    },
    syncMq() {
      this.$router.push({
        path: `/dockers/syncMq/${this.namespace}`
      })
    },
    clearRedis() {
      flushRedis({ namespace: this.namespace }).then(res => {
        this.$message({
          message: res.data.msg || '清理redis缓存成功',
          type: 'success'
        })
      })
    },
    updateDomain(data) {
      this.dialogHost = true
      this.form.host = ''
      this.ingressName = data.serviceName
      ingressHost({ namespace: this.namespace, serviceName: data.serviceName }).then(res => {
        this.form.host = res.data.body.spec.rules[0].host
      })
    },
    deleteService(data, item) {
      this.$confirm(
        `此操作将删除 ${data.serviceName} 服务, 是否继续?`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        deleteClusterService({ namespace: this.namespace, serviceName: data.serviceName, podName: data.podName })
          .then((res) => {
            this.$message({
              type: 'success',
              message: `${res.data}`
            })
            this.getServicelist()
          }).catch((res) => {
            this.getServicelist()
          })
      }).catch(() => {

      })
    },

    linkShell(scopeData) {
      if (this.$store.getters.cluster === 'qa') {
        window.open(`http://172.30.220.24:9600/static/terminal.html?namespace=${this.namespace}&pod=${scopeData.podName}`, '_blank')
      }

      if (this.$store.getters.cluster === 'qke') {
        window.open(`http://172.30.220.24:9601/static/terminal.html?namespace=${this.namespace}&pod=${scopeData.podName}`, '_blank')
      }

      // fetchServiceInstance({ serviceName: scopeData.serviceName, namespace: scopeData.namespace }).then(res => {
      //   const podName = res.data.instances[0].name
      //   window.open(`http://172.30.220.24:9600/static/terminal.html?namespace=${scopeData.namespace}&pod=${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`
      }
      if (this.$store.getters.cluster === 'qa') {
        window.open(`http://172.30.220.24:9600/static/logs.html?namespace=${this.namespace}&pod=${scopeData.podName}&paths=${path}`, '_blank')
      }
      if (this.$store.getters.cluster === 'qke') {
        window.open(`http://172.30.220.24:9601/static/logs.html?namespace=${this.namespace}&pod=${scopeData.podName}&paths=${path}`, '_blank')
      }
    },

    array2Object(original) { // 将数组转成对象存储
      this.FormatTabledata = {}
      original.forEach((item, index) => {
        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)
        }
      })
    },
    indexMethod(index) {
      return index + 1
    }
  }
}
</script>
<style scoped>
  .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;
}
</style>
