<template>
  <div>
    <ElForm v-show="showSearchForm" inline @submit.prevent="paging">
      <ElFormItem label="日志时间">
        <ElDatePicker
          v-model="searchForm.logTime"
          :shortcuts="shortcuts"
          end-placeholder="结束"
          range-separator="至"
          start-placeholder="开始"
          type="datetimerange"
          unlink-panels
        />
      </ElFormItem>
      <ElFormItem label="日志等级">
        <ElSelect v-model="searchForm.logLevel" placeholder="请选择日志等级" style="width: 150px;">
          <ElOption v-for="item in logLevelList" :key="item.value" :label="item.label" :value="item.value"/>
        </ElSelect>
      </ElFormItem>
      <ElFormItem>
        <ElButton :icon="elIcons.Search" :loading="searching" native-type="submit" type="primary">搜索</ElButton>
        <ElButton :icon="elIcons.Refresh" :loading="searching" @click="reset">重置</ElButton>
      </ElFormItem>
    </ElForm>

    <!-- <div class="tool-bar">
      <ElButton :icon="elIcons.Filter" type="default" @click="showSearchForm = !showSearchForm"/>
    </div> -->

    <ElTable v-loading="searching" :data="tableData"
      cell-class-name="table-cell"
      class="table-list"
      empty-text="暂无数据"
      header-row-class-name="table-header"
      row-key="id">
      <ElTableColumn label="日志等级" prop="logLevel" width="100">
        <template #default="{row}">
          <ElTag v-if="row.logLevel === 'DEBUG'" type="success">调试</ElTag>
          <ElTag v-else-if="row.logLevel === 'INFO'" type="primary">普通</ElTag>
          <ElTag v-else-if="row.logLevel === 'WARN'" type="warning">警告</ElTag>
          <ElTag v-else type="danger">错误</ElTag>
        </template>
      </ElTableColumn>
      <ElTableColumn label="日志时间" prop="logTime"/>
      <!-- <ElTableColumn label="位置" prop="place" width="240" show-overflow-tooltip/> -->
      <!-- <ElTableColumn label="行号" prop="line"/> -->
      <ElTableColumn label="日志信息" prop="msg">
        <template #default="{row}">
          <span>{{ Strings.isBlank(row.msg) ? '' : (row.msg.length > 40 ? row.msg.substring(0, 40) + '...' : row.msg) }}</span>
        </template>
      </ElTableColumn>
      <ElTableColumn label="错误信息" prop="err">
        <template #default="{row}">
          <span>{{ Strings.isBlank(row.err) ? '' : (row.err.length > 40 ? row.err.substring(0, 40) + '...' : row.err) }}</span>
        </template>
      </ElTableColumn>
      <ElTableColumn label="操作" width="180">
        <template #default="scope">
          <div class="action-btn">
            <ElPopconfirm
              confirm-button-text="是"
              cancel-button-text="否"
              confirm-button-type="danger"
              cancel-button-type="primary"
              placement="top"
              title="是否删除当前数据?"
              width="180"
              @confirm="delHandler(scope)">
              <template #reference>
                <ElButton :loading="deling" text type="danger">删除</ElButton>
              </template>
            </ElPopconfirm>
            <ElButton text type="primary" @click="showMsg(scope.row)">详情</ElButton>
          </div>
        </template>
      </ElTableColumn>
    </ElTable>
    <ElPagination
      class="pagination"
      layout="prev, pager, next"
      :page-size="pagination.size"
      :total="pagination.total"
      @change="pageChangeHandler"/>
    <ElDialog v-model="showDialog"
      :close-on-click-modal="false"
      destroy-on-close
      width="80vw">
      <div class="msg-box">
        <div class="msg-box-title">
          <ElTag v-if="content.logLevel === 'DEBUG'" type="success">调试</ElTag>
          <ElTag v-else-if="content.logLevel === 'INFO'" type="primary">普通</ElTag>
          <ElTag v-else-if="content.logLevel === 'WARN'" type="warning">警告</ElTag>
          <ElTag v-else type="danger">错误</ElTag>
          <div>{{ content.logTime }}</div>
        </div>
        <ElText :type="content.logLevel === 'DEBUG'?'success':(content.logLevel === 'INFO'?'primary':(content.logLevel === 'WARN'?'warning':'danger'))">
          <pre style="line-height: 21px;">{{ (Strings.isBlank(content.place) ? '' : (content.place + '  ')) + (content.line == null ? '' : ('（第' + content.line + '行）\n\n')) + (Strings.isBlank(content.msg) ? '' : (content.msg)) + (Strings.isBlank(content.err) ? '' : ('\n' + content.err)) }}</pre>
        </ElText>
        <!-- <ElInput type="textarea" resize="none" rows="20" :model-value="(Strings.isBlank(content.place) ? '':(content.place+'\n'))+(Strings.isBlank(content.line) ? '':(content.line+'\n')) + (Strings.isBlank(content.msg) ? '':(content.msg+'\n'))+'\n'+(Strings.isBlank(content.err) ? '':(content.err+'\n'))"/> -->
      </div>
      <template #footer>
        <ElButton @click="showDialog = false">关闭</ElButton>
      </template>
    </ElDialog>
  </div>
</template>

<script lang="ts" setup>
import TaskExecuteLogApi from '@/pages/sys/task/execute-log/execute-log-api.ts'
import { elIcons } from '@/common/element/element.ts'
import Strings from '@/common/utils/strings.ts'
import Colls from '@/common/utils/colls.ts'
import Times from '@/common/utils/times.ts'

const props = defineProps<{
  scheduleId: string
}>()
const showDialog = ref(false)
const content = ref<TaskExecuteLogTypes.SearchTaskExecuteLogResult>({})

const tableData = ref<TaskExecuteLogTypes.SearchTaskExecuteLogResult[]>([])
const searchForm = ref<TaskExecuteLogTypes.SearchTaskExecuteLogParam>({
  current: 1,
  size: 20,
})
const searching = ref(false)
const deling = ref(false)
const showSearchForm = ref(true)
const pagination = reactive<G.Pagination>({
  current: 1,
  size: 1,
})
const shortcuts = [
  {
    text: '上周',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [ start, end ]
    },
  },
  {
    text: '上个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [ start, end ]
    },
  },
  {
    text: '最近三个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      return [ start, end ]
    },
  },
]
const logLevelList = [
  {value: 'DEBUG', label: '调试'},
  {value: 'INFO', label: '普通'},
  {value: 'WARN', label: '警告'},
  {value: 'ERROR', label: '错误'},
  {value: 'OFF', label: '关闭'},
]

function showMsg(data: TaskExecuteLogTypes.SearchTaskExecuteLogResult) {
  showDialog.value = true
  content.value = data
}

function pageChangeHandler(currentPage: number, pageSize: number) {
  searchForm.value.current = currentPage
  searchForm.value.size = pageSize
  paging()
}

function delHandler({row}: { row: TaskExecuteLogTypes.SearchTaskExecuteLogResult }) {
  deling.value = true
  TaskExecuteLogApi.del([ row.id! ])
    .then(() => {
      ElMessage.success('删除成功')
      paging()
    })
    .finally(() => {
      deling.value = false
    })
}


function reset() {
  searchForm.value = {
    current: 1,
    size: 20,
  }
  paging()
}

function paging() {
  searching.value = true
  const {
    logLevel,
    logTime,
  } = searchForm.value
  TaskExecuteLogApi.paging({
    logLevel,
    startLogTime: Colls.isEmpty(logTime) ? undefined : Times.format(logTime![0]),
    endLogTime: Colls.isEmpty(logTime) ? undefined : Times.format(logTime![1]),
    scheduleId: props.scheduleId,
  })
    .then(res => {
      tableData.value = res.data?.records ?? []
    })
    .finally(() => {
      searching.value = false
    })
}

onMounted(() => {
  paging()
})

</script>

<style lang="stylus" scoped>
.table-list {
  height 50vh;
  width 100%

  :deep(.table-header) {
    color #454C59

    th {
      background-color #EDF1F7
      font-weight 500
      position relative

      & > div {
        display flex
        gap 5px
        align-items center
      }

      &:not(:first-child) > div::before {
        position: absolute;
        top: 50%;
        left: 1px;
        width: 1px;
        background-color: #D3D7DE;
        transform: translateY(-50%);
        content: "";
        height 50%
      }
    }
  }

  :deep(.table-cell) {
    color #2F3540
  }

  .action-btn {
    width 100%
    display flex
    flex-wrap wrap

    & > button {
      margin 0
    }
  }
}

.tool-bar {
  display flex
  justify-content space-between
  margin 0 0 20px 0
}

.pagination {
  justify-content: end;
  margin: 8px;
}

.msg-box {
  display flex
  flex-direction column
  gap 20px

  .msg-box-title {
    display flex
    gap 20px
  }

  & > span {
    display: block;
    height: 60vh;
    text-align: start;
    width: 100%;
    overflow: auto;
  }
}
</style>
