<template>
  <div class="app-container">
    <div class="page-title">
      <el-icon class="title-icon"><Lock /></el-icon>
      <span>加密日志</span>
    </div>
    <div class="search-box">
      <el-form :model="queryParams" ref="queryForm" :inline="true">
        <el-form-item label="用户" prop="user">
          <el-select
            v-model="queryParams.user"
            placeholder="请选择"
            clearable
            style="width: 200px"
          >
            <el-option
              v-for="item in userOptions"
              :key="item.id"
              :label="item.user"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="时间" prop="range">
          <el-select
            v-model="queryParams.range"
            placeholder="请选择时间"
            style="width: 200px"
          >
            <el-option
              v-for="item in timeRangeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="项目级" prop="projectId">
          <el-select
            v-model="queryParams.projectId"
            placeholder="请选择项目级"
            clearable
            style="width: 200px"
          >
            <el-option
              v-for="item in projectLevelOptions"
              :key="item.id"
              :label="item.project"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button type="primary" icon="Download" @click="handleExport">导出</el-button>
          <!-- <el-button type="primary" @click="handleCheck">数据完整性校验</el-button> -->
        </el-form-item>
      </el-form>
    </div>

    <el-table
      v-loading="loading"
      :data="logList"
      border
      style="width: 100%"
    >
      <el-table-column prop="operptionUser" label="用户" width="200" align="left" />
      <el-table-column prop="createtime" label="时间" align="left" width="180" />
      <el-table-column prop="code" label="模块编号" align="left" width="120" />
      <el-table-column prop="operModule" label="操作模块" align="left" width="150" />
      <el-table-column prop="operptionMassage" label="操作信息" align="left" show-overflow-tooltip />
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.page"
      v-model:limit="queryParams.rows"
      @pagination="getList"
    />
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { Lock } from '@element-plus/icons-vue'
import { queryMenuTreeAndUserlist } from '@/api/logSet/operationLog.js'
import { query , allProject, getEncryptionLogExcel} from '@/api/logSet/encryptedLog.js'
import { ElMessageBox, ElMessage } from 'element-plus'
import useAppStore from '@/store/modules/app'
import timeRangeOptions from '@/constants/timeRangeOptions.js'
const appStore = useAppStore()
console.log('当前用户信息',appStore.userInfo)
const loading = ref(true)
const total = ref(0)
const logList = ref([])
const queryParams = reactive({
  page: 1,
  rows: 10,
  user: undefined,
  range: '0',
  module: undefined,
  projectId: undefined
})

const userOptions = ref([
  // { id: 'admin', user: 'admin' },
  // { id: 'system', user: 'system' },
  // { id: 'test', user: 'test' }
])

const projectLevelOptions = ref([
  // { id: '1', project: '一级' },
  // { id: '2', project: '二级' },
  // { id: '3', project: '三级' }
])


const getList = async () => {
  loading.value = true
  try {
    const response = await query(queryParams)
    logList.value = response.data.list || []
    total.value = response.data.total || 0
  } catch (error) {
    console.error('Failed to fetch log list:', error)
  } finally {
    loading.value = false
  }
}

const handleQuery = () => {
  queryParams.page = 1
  getList()
}

const handleExport = () => {
  ElMessageBox.confirm('是否确认导出所有加密日志数据？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      try {
        const response = await getEncryptionLogExcel(queryParams)
        const blob = new Blob([response], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
        const link = document.createElement('a')
        link.href = URL.createObjectURL(blob)
        link.download = '加密日志.xls'
        link.click()
        URL.revokeObjectURL(link.href)
        ElMessage.success('导出成功')
      } catch (error) {
        console.error('Failed to export operation logs:', error)
        ElMessage.error('导出出错')
      }
    })
    .catch(() => {
      ElMessage.info('导出已取消')
    })
}

const handleCheck = () => {
  window.$modal.msgSuccess('数据完整性校验完成')
}

onMounted(async () => {
  try {
    const response = await queryMenuTreeAndUserlist({ type: 'global' })
    console.log('queryMenuTreeAndUserlist', response)

    userOptions.value = response.data.userlist.map(user => ({
      id: user.id,
      user: user.realname
    }))
  } catch (error) {
    console.error('Failed to fetch user and module data:', error)
  }

  try {
    const params = {
      loginUser: {
        tsysUser: {
          id: appStore.userInfo.user.id,
          username: appStore.userInfo.user.username
        }
      },
      proName: '',
      note: ''
    }
    const projectResponse = await allProject(params)
    projectLevelOptions.value = projectResponse.data.map(project => ({
      id: project.id,
      project: project.project
    }))
  } catch (error) {
    console.error('Failed to fetch project level data:', error)
  }

  getList()
})
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;

  .page-title {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    font-size: 16px;
    font-weight: bold;

    .title-icon {
      margin-right: 8px;
      font-size: 20px;
      color: #409EFF;
    }
  }
  
  .search-box {
    margin-bottom: 20px;
    background-color: #fff;
    padding: 20px;
    border-radius: 4px;
    text-align: left;

    :deep(.el-form) {
      justify-content: flex-start;
    }

    :deep(.el-form--inline .el-form-item) {
      margin-right: 20px;
    }
  }
  
  .el-table {
    margin-top: 20px;
  }

  :deep(.el-table) {
    text-align: left;
  }

  :deep(.el-cascader) {
    width: 100%;
  }
}
</style>
