<template>
  <div class="lic-container" v-loading="state.loading">
    <div style="display: flex; justify-content: space-between">
      <div style="margin-bottom: 20px; display: flex; flex-direction: row; align-items: center">
        <el-button type="primary" size="small" @click="onStart">启动 </el-button>
        <el-button type="primary" size="small" @click="onRestartOne" style="margin-left: 20px"
          >重启
        </el-button>
        <el-button type="primary" size="small" @click="onUpdate" style="margin-left: 20px"
          >更新
        </el-button>
        <el-button type="primary" size="small" @click="onClean" style="margin-left: 20px"
          >清理
        </el-button>
        <el-button type="primary" size="small" @click="onShowLogs" style="margin-left: 20px"
          >查看日志
        </el-button>
        <el-button type="primary" size="small" @click="onMessages" style="margin-left: 20px"
          >刷新
        </el-button>
      </div>
    </div>
    <el-table
      :data="tableData"
      style="width: 100%"
      stripe
      border
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="序号" width="80" align="center" />
      <el-table-column prop="name" label="服务" />
      <el-table-column prop="version" label="版本" width="100" align="center" />
      <el-table-column prop="stats" label="状态" width="100" align="center">
        <template #default="scope">
          <el-tag
            :type="scope.row.stats === '运行中' ? 'success' : 'warning'"
            disable-transitions
            >{{ scope.row.stats }}</el-tag
          >
        </template>
      </el-table-column>
    </el-table>
    <div v-show="state.messages.length" class="timeline" v-loading="state.messageLoading">
      <el-icon size="28" color="#409EFC" class="RefreshRight" @click="initMessage"
        ><i-ep-RefreshRight
      /></el-icon>
      <el-timeline>
        <el-timeline-item v-for="(item, index) in state.messages" :key="index">
          {{ item }}
        </el-timeline-item>
      </el-timeline>
    </div>
  </div>
  <logs ref="logsRef" />
</template>

<script setup lang="ts">
import { getListAll, getMessage, restartOne, startBatch, updateBatch, cleanBatch } from '@/api'
import { useTenantStore } from '@/stores/modules/tenant'
import logs from '@/components/logs.vue'

const tenantStore = useTenantStore()
const tenantId = computed(() => tenantStore.getTenantId)
const state = reactive({
  visible: false,
  loading: true,
  messageLoading: true,
  action: '/admin/api/lic/info/file/import',
  tableData: [],
  messages: [] as any,
  dialogVisible: false,
  environment: '',
  selectRows: [] as any,
  logsRows: [] as any
})

const tableData = ref()
const logsRef = ref()

const handleSelectionChange = (rows: any) => {
  state.selectRows = rows.map((item: any) => item.name)
  state.selectRows = [...state.selectRows]
  state.logsRows = rows
}

const onStart = () => {
  if (!state.selectRows.length) return ElMessage.warning('请先选择数据')
  ElMessageBox.confirm('确认启动?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res: any = await startBatch({ names: state.selectRows, tenantId: tenantId.value })
      if (res.code === 200) ElMessage.success('启动成功')
      else ElMessage.error(res.msg)
    } finally {
      onMessages()
    }
  })
}
const onUpdate = () => {
  if (!state.selectRows.length) return ElMessage.warning('请先选择数据')
  ElMessageBox.confirm('确认更新?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    const res: any = await updateBatch({ names: state.selectRows, tenantId: tenantId.value })
    try {
      if (res.code === 200) ElMessage.success('更新成功')
      else ElMessage.error(res.msg)
    } finally {
      onMessages()
    }
  })
}

const onClean = () => {
  if (!state.selectRows.length) return ElMessage.warning('请先选择数据')
  ElMessageBox.confirm('确认清理?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    const res: any = await cleanBatch({ names: state.selectRows, tenantId: tenantId.value })
    try {
      if (res.code === 200) ElMessage.success('清理成功')
      else ElMessage.error(res.msg)
    } finally {
      onMessages()
    }
  })
}

const onMessages = async () => {
  state.loading = true
  await initListAll(tenantId.value)
  await initMessage().then(() => {
    state.loading = false
  })
}

const onRestartOne = () => {
  if (!state.selectRows.length) return ElMessage.warning('请先选择数据')
  if (state.selectRows.length > 1) return ElMessage.warning('一次只能重启一个容器')

  ElMessageBox.confirm(`确认重启?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res: any = await restartOne({
        codeName: state.selectRows[0],
        tenantId: tenantId.value
      })
      if (res.code === 200) ElMessage.success('重启成功')
      else ElMessage.error(res.msg)
    } finally {
      onMessages()
    }
  })
}

const onShowLogs = () => {
  if (!state.logsRows.length) return ElMessage.warning('请先选择数据')
  if (state.logsRows.length > 1) return ElMessage.warning('一次只能查看一个容器日志')
  ElMessageBox.prompt('请输入查看日志时间', '查看日志', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    inputPattern: /^[1-9]\d*$/,
    inputErrorMessage: '请输入数字'
  }).then(({ value }) => {
    logsRef.value.show = true
    logsRef.value.init(state.logsRows[0], value)
  })
}

const tenantChange = (tenantId: any) => {
  state.loading = true
  initListAll(tenantId).then(() => {
    state.loading = false
  })
}

const initListAll = async (tenantId: number | string = '') => {
  const res = await getListAll({ tenantId })
  if (res.code === 200) {
    tableData.value = res.data
  }
}

const initMessage = async () => {
  state.messageLoading = true
  const res = await getMessage(tenantId.value)
  if (res.code === 200) {
    state.messages = res.data
    setTimeout(() => {
      state.messageLoading = false
    }, 300)
  }
}

watch(
  () => tenantId.value,
  (newTenantId) => {
    tenantChange(newTenantId)
  },
  { immediate: true }
)

const init = async () => {
  initMessage().then(() => {
    state.loading = false
  })
}
init()
</script>

<style scoped>
.el-select {
  width: 200px;
}
.timeline {
  position: relative;
  margin-top: 20px;
  width: 500px;
  border: 1px solid var(--el-border-color);
  padding: 20px;
  border-radius: 10px;
}

.RefreshRight {
  position: absolute;
  top: 6px;
  right: 6px;
  cursor: pointer;
}
.el-timeline-item {
  padding-bottom: 10px;
}
</style>
