<template>
  <d2-container>
    <template #header>
      <div class="search-bar">
        <el-form :inline="true" ref="searchFormRef" size="mini" @submit.native.prevent>
          <el-form-item :label="$t(key('ip'))">
            <el-input
              v-model="search.ip"
              :placeholder="$t(key('placeholder_ip'))"
              clearable
              style="width:160px"
              @keyup.enter.native="onSearch"
            />
          </el-form-item>
          <el-form-item :label="$t(key('operator'))">
            <el-select
              v-model="search.user_id"
              :placeholder="$t(key('placeholder_operator'))"
              clearable
              filterable
              style="width:200px"
            >
              <el-option
                v-for="u in userList"
                :key="u.user_id"
                :value="u.user_id"
                :label="u.username"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="onSearch">
              {{ $t(key('search')) }}
            </el-button>
            <el-button icon="el-icon-refresh" @click="onReset">
              {{ $t(key('reset')) }}
            </el-button>
            <el-button
              v-if="!searchExpanded"
              type="text"
              icon="el-icon-arrow-down"
              @click="searchExpanded = true"
            >
              {{ $t(key('expand')) }}
            </el-button>
            <el-button
              v-else
              type="text"
              icon="el-icon-arrow-up"
              @click="searchExpanded = false"
            >
              {{ $t(key('collapse')) }}
            </el-button>
          </el-form-item>
          <div v-show="searchExpanded" class="search-bar__extra">
            <el-form-item :label="$t(key('batch'))">
              <el-input
                v-model="search.batch"
                :placeholder="$t(key('placeholder_batch'))"
                clearable
                style="width:160px"
                @keyup.enter.native="onSearch"
              />
            </el-form-item>
            <el-form-item :label="$t(key('tray_no'))">
              <el-input
                v-model="search.tray"
                :placeholder="$t(key('placeholder_tray_no'))"
                clearable
                style="width:160px"
                @keyup.enter.native="onSearch"
              />
            </el-form-item>
            <el-form-item :label="$t(key('create_time'))">
              <el-date-picker
                v-model="search.time"
                type="datetimerange"
                :placeholder="$t(key('placeholder_time'))"
                range-separator="-"
                start-placeholder=""
                end-placeholder=""
                value-format="yyyy-MM-dd HH:mm:ss"
                style="width:340px"
              />
            </el-form-item>
          </div>
        </el-form>
      </div>
    </template>

    <page-table
      ref="pageTable"
      :columns="columns"
      :data="tableData"
      :loading="loading"
      :row-buttons="rowButtons"
      :pagination="pagination"
      auto-height
      @page-change="onPageChange"
    >
      <template #col-status="{ row }">
        <span v-if="row.status === 0" style="color: #67c23a;">
          <i class="el-icon-circle-check" />
          {{ $t(key('success')) }}
        </span>
        <span v-else style="color: #F56C6C;">
          <i class="el-icon-circle-close" />
          {{ $t(key('failure')) }}
        </span>
      </template>
    </page-table>

    <response-dialog
      :visible.sync="respVisible"
      :param-data="respParam"
      :result-data="respResult"
      :prefix="prefix"
    />
  </d2-container>
</template>

<script>
import { useTableColumns } from '@/composables/useTableColumns'
import { useTableButtons } from '@/composables/useTableButtons'
import { i18nMixin } from '@/composables/useI18n'
import { getOperateLogList } from '@/api/system-administration/operation-logs'
import { getUserList } from '@/api/system-administration/user'
import PageTable from '@/components/page-table'
import ResponseDialog from '../api-logs/components/ResponseDialog/index.vue'

export default {
  name: 'system-administration-operation-logs',
  components: { PageTable, ResponseDialog },
  mixins: [i18nMixin('page.system_administration.system_utilities.operation_logs')],
  data () {
    return {
      loading: false,
      tableData: [],
      columns: [],
      rowButtons: [],
      userList: [],
      pagination: { current: 1, size: 10, total: 0 },
      search: {
        ip: '',
        user_id: undefined,
        batch: '',
        tray: '',
        time: undefined
      },
      respVisible: false,
      respParam: null,
      respResult: null,
      searchExpanded: false
    }
  },
  computed: {
    prefix () {
      return 'page.system_administration.system_utilities.operation_logs'
    }
  },
  created () {
    this.columns = useTableColumns([
      { prop: 'id', label: this.key('id'), width: 65 },
      { prop: 'username', label: this.key('operator'), width: 120 },
      { prop: 'ip', label: this.key('ip'), width: 140 },
      { prop: 'status', label: this.key('status'), slot: 'status', width: 90 },
      { prop: 'action_name', label: this.key('action_name'), showOverflowTooltip: true, minWidth: 130 },
      { prop: 'action', label: this.key('action_code'), showOverflowTooltip: true, minWidth: 130 },
      { prop: 'path', label: this.key('request_path'), showOverflowTooltip: true, minWidth: 180 },
      { prop: 'batch', label: this.key('batch'), showOverflowTooltip: true, minWidth: 120 },
      { prop: 'tray', label: this.key('tray_no'), showOverflowTooltip: true, minWidth: 120 },
      { prop: 'create_time', label: this.key('create_date'), width: 170 },
      { prop: '_actions', label: this.key('operation'), width: 100, fixed: 'right' }
    ], { selectionWidth: 0 })
    const btns = useTableButtons({
      row: [
        {
          key: 'view',
          label: this.key('view_response'),
          icon: 'el-icon-view',
          auth: '/system_settings/system_assistant/operate_log/view',
          onClick: this.handleViewResponse
        }
      ]
    }, this.$permission)
    this.rowButtons = btns.rowButtons
    this.fetchUsers()
    this.fetchData()
  },
  methods: {
    async fetchUsers () {
      try {
        const res = await getUserList({ page_no: 1, page_size: 9999 })
        this.userList = Array.isArray(res) ? res : (res.data || [])
      } catch { /* 用户列表加载失败不影响主流程 */ }
    },
    async fetchData () {
      this.loading = true
      try {
        const params = {
          ...this.search,
          page_no: this.pagination.current,
          page_size: this.pagination.size
        }
        const res = await getOperateLogList(params)
        const data = Array.isArray(res) ? res : (res.data || [])
        this.tableData = data
        this.pagination.total = res.count || data.length
      } finally {
        this.loading = false
      }
    },
    onSearch () {
      this.pagination.current = 1
      this.fetchData()
    },
    onReset () {
      this.$refs.searchFormRef.resetFields()
      this.search = {
        ip: '',
        user_id: undefined,
        batch: '',
        tray: '',
        time: undefined
      }
      this.pagination.current = 1
      this.fetchData()
    },
    onPageChange (page) {
      this.pagination.current = page.current
      this.pagination.size = page.size
      this.fetchData()
    },
    handleViewResponse (row) {
      try {
        this.respParam = JSON.parse(row.params || '{}')
        this.respResult = JSON.parse(row.result || '{}')
      } catch {
        this.respParam = row.params || {}
        this.respResult = row.result || {}
      }
      this.respVisible = true
    }
  }
}
</script>

<style scoped>
.search-bar {
  padding: 10px 0;
}
.search-bar .el-form-item--mini.el-form-item {
  margin-bottom: 4px;
}
.search-bar__extra {
  display: inline-block;
  width: 100%;
}
</style>
