<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="handleMogodb">初始化Mongodb</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-top" style="color: #67c23a;font:caption" />
              </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-bottom" style="color: #f56c6c;font:caption" />
              </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="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 | filterTag }}
          </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="40%">
      <el-form ref="mqDataForm" label-width="120px" style="width:95%">
        <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>
    <!-- 同步mogobd对话框 2021-12-20新添加-->
    <el-dialog title="同步Mongodb" :visible.sync="mongodbSyncDialogVisible" width="40%">
      <el-form :model="mongodbDataForm" label-width="100px" style="width:95%">
        <el-form-item label="服务地址：">
          <el-input v-model="mongodbDataForm.host" :disabled="true" />
        </el-form-item>
        <el-form-item label="端口号：">
          <el-input v-model="mongodbDataForm.port" :disabled="true" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="mongodbSyncDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="syncMongodb()">开始同步</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getServiceList,
  getSingleTypeApp,
  getImageList,
  createK8sService,
  getDockerProjectDetail,
  getServiceDetail,
  serviceRedeploy,
  serviceUpdate,
  serviceDelete,
  getDockerProjectType,
  syncMq,
  flushRedis,
  mqDiff,
  syncMongodb
} 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,
      mongodbSyncDialogVisible: false,
      mqUrl: '',
      mqDataForm: {},
      mongodbDataForm: {
        host: '',
        port: 0
      },
      loadingOptions: {
        text: '加载中...',
        lock: true,
        spinner: 'el-icon-loading',
        background: 'rgba(0,0,0,0.7)'
      },
      nsList: window.localStorage.getItem('nsList').split(','),
      mqLoadingOptions: {
        text: 'MQ同步中...',
        lock: true,
        spinner: 'el-icon-loading',
        background: 'rgba(0,0,0,0.7)'
      },
      mongodbLoadingOptions: {
        text: 'Mongodb同步中...',
        lock: true,
        spinner: 'el-icon-loading',
        background: 'rgba(0,0,0,0.7)'
      }
    }
  },
  created() {
    this.getServiceList()
    this.fetchRabbitmqDetails()
    bus.$on('refreshEnv', (name) => {
      this.namespace = name
      this.getServiceList()
      this.fetchRabbitmqDetails()
    })

    getDockerProjectType({}).then((resp) => {
      this.typeList = resp.data.data
    })
  },
  methods: {
    indexMethod(index) {
      return index + 1
    },
    array2Object(original) {
      console.log('original: ', 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)
          }
        }
      })
      console.log(this.FormatTabledata)
    },
    // 获取服务列表
    getServiceList() {
      const tLoading = this.$loading.service(this.loadingOptions)
      getServiceList({ namespace: this.namespace })
        .then((resp) => {
          if (resp.data.success === true) {
            const serviceList = resp.data.data
            this.array2Object(serviceList)
            tLoading.close()
          } else {
            // this.$message.error(resp.data.msg)
            tLoading.close()
          }
        })
        .catch((error) => {
          this.$message({ type: 'error', message: error })
          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)
      const mqLoading = this.$loading.service(this.mqLoadingOptions)
      syncMq(formdata).then((resp) => {
        if (resp.data.data === true) {
          this.mqSyncDialogVisible = false
          mqLoading.close()
          return this.$message.success('同步成功！')
        } else {
          mqLoading.close()
          return this.$message.error('同步失败！')
        }
      })
    },
    // 打开Mogodb同步对话框并且获取服务地址和端口号 2021-12-20新增
    handleMogodb() {
      getServiceDetail({
        namespace: this.namespace,
        serviceType: 'base',
        serviceName: 'mongodb'
      }).then((resp) => {
        if (resp.data.data != null) {
          this.mongodbDataForm.host = resp.data.data.lanIp
          this.mongodbDataForm.port = resp.data.data.portMappings[0].nodePort
        } else {
          return this.$message.error('当前环境没有Mogodb！')
        }
      })
      this.mongodbSyncDialogVisible = true
    },
    // 点击同步Mongodb
    syncMongodb() {
      const mongodbLoading = this.$loading.service(this.mongodbLoadingOptions)
      syncMongodb(this.mongodbDataForm).then((resp) => {
        if (resp.data.businessCode === '0000') {
          this.mongodbSyncDialogVisible = false
          mongodbLoading.close()
          return this.$message.success('同步成功！')
        } else {
          mongodbLoading.close()
          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) => {
        // console.log('数据返回信息', resp.data.data)
        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.updateDialogVisible = false
          this.getServiceList()
          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.29.1.16: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))`

      const url = `http://kibana.staff.quantgroups.com/s/test/app/kibana#/discover?_g=(filters:!(),refreshInterval:(pause:!t,value:0),time:(from:now-15m,to:now))&_a=(columns:!(message),filters:!(('$state':(store:appState),meta:(alias:!n,disabled:!f,index:e4562430-50eb-11ec-bcd8-c18b5d83cf13,key:k8s.namespace,negate:!f,params:(query:${ns}),type:phrase),query:(match_phrase:(k8s.namespace:${ns}))),('$state':(store:appState),meta:(alias:!n,disabled:!f,index:e4562430-50eb-11ec-bcd8-c18b5d83cf13,key:k8s.svcname,negate:!f,params:(query:${sn}),type:phrase),query:(match_phrase:(k8s.svcname:${sn})))),index:e4562430-50eb-11ec-bcd8-c18b5d83cf13,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.29.1.16: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')
    },
    fetchRabbitmqDetails() {
      getServiceDetail({
        namespace: this.namespace,
        serviceType: 'base',
        serviceName: 'rabbitmq'
      }).then((resp) => {
        var data = resp.data.data
        data.portMappings.forEach((item) => {
          if (item.port === 15672) {
            // 重新组装ip和端口号
            var ip = data.lanIp
            var newPort = item.nodePort
            var newHost = ip + ':' + newPort
            // 调取接口
            mqDiff({ host: newHost }).then((resp) => {
              const mqDiffData = resp.data.data
              this.moreShow = mqDiffData.more.show
              this.lostShow = mqDiffData.lost.show

              this.moreArray = []
              // 判断本地比线上多出来的配置
              for (const i in mqDiffData.more) {
                // 判断是否是数组类型
                if (mqDiffData.more[i] instanceof Array) {
                  this.moreArray.push({
                    type: i,
                    value: mqDiffData.more[i].join(',')
                  })
                }
              }

              this.lostArray = []
              // 判断本地比线上少出来的配置
              for (const i in mqDiffData.lost) {
                if (mqDiffData.lost[i] instanceof Array) {
                  this.lostArray.push({
                    type: i,
                    value: mqDiffData.lost[i].join(',')
                  })
                }
              }
            })
          }
        })
      })
    }
  }
}
</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>
