<template>
  <div class="app-container">
    <div class="page-title">
      <el-icon class="title-icon"><Document /></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.realname"
              :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="module">
          <el-cascader
            v-model="queryParams.module"
            :options="moduleTreeOptions"
            :props="{
              checkStrictly: false,
              value: 'value',
              label: 'label',
              emitPath: false,
              leaf: true
            }"
            clearable
            style="width: 200px"
            placeholder="请选择"
          />
        </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="user" label="用户" width="200" align="left" />
      <el-table-column prop="operationtime" label="时间" align="left" width="180" />
      <el-table-column prop="operationObject" label="模块编号" align="left" width="120" />
      <el-table-column prop="module" label="操作模块" align="left" width="150" />
      <el-table-column prop="logmessage" 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 { Document } from '@element-plus/icons-vue'
import { query, checkEnc, queryMenuTreeAndUserlist, getOpeExcel} from '@/api/logSet/operationLog.js'
import { ElMessageBox, ElMessage } from 'element-plus'
import timeRangeOptions from '@/constants/timeRangeOptions.js'
const loading = ref(true)
const total = ref(0)
const logList = ref([])
const queryParams = reactive({
  page: 1,
  rows: 10,
  user: undefined,
  range: '0',
  module: undefined
})

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


const moduleTreeOptions = ref([])

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 = async () => {
  ElMessageBox.confirm('是否确认导出所有操作日志数据？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      try {
        const response = await getOpeExcel(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 = async () => {
  try {
    const response = await checkEnc(queryParams)
    if (response.success) {
      window.$modal.msgSuccess('数据完整性校验完成')
    } else {
      window.$modal.msgError('数据完整性校验失败')
    }
  } catch (error) {
    console.error('Failed to perform data integrity check:', error)
    window.$modal.msgError('数据完整性校验出错')
  }
}

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

    userOptions.value = response.data.userlist.map(user => ({
      id: user.id,
      realname: user.realname
    }))
    moduleTreeOptions.value = response.data.menulist.map(menu => ({
      value: menu.id,
      label: menu.text,
      children: menu.children ? menu.children.map(child => ({
        value: child.id,
        label: child.text
      })) : null
    }))
  } catch (error) {
    console.error('Failed to fetch user and module 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>
