<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('interface_name'))">
            <el-input
              v-model="search.unit"
              :placeholder="$t(key('placeholder_interface_name'))"
              clearable
              style="width:200px"
              @keyup.enter.native="onSearch"
            />
          </el-form-item>
          <el-form-item :label="$t(key('status'))">
            <el-select
              v-model="search.status"
              :placeholder="$t(key('placeholder_status'))"
              clearable
              style="width:120px"
            >
              <el-option :value="200" :label="$t(key('success'))" />
              <el-option :value="4001" :label="$t(key('failure'))" />
            </el-select>
          </el-form-item>
          <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>
            <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('tray_number'))">
              <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('process_code'))">
              <el-input
                v-model="search.process_code"
                :placeholder="$t(key('placeholder_process_code'))"
                clearable
                style="width:160px"
                @keyup.enter.native="onSearch"
              />
            </el-form-item>
            <el-form-item :label="$t(key('battery_id'))">
              <el-input
                v-model="search.battery_id"
                :placeholder="$t(key('placeholder_battery_barcode'))"
                clearable
                style="width:220px"
                @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_create_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 { getInterfaceLogList } from '@/api/system-administration/api-logs'
import PageTable from '@/components/page-table'
import ResponseDialog from './components/ResponseDialog/index.vue'

export default {
  name: 'system-administration-api-logs',
  components: { PageTable, ResponseDialog },
  mixins: [i18nMixin('page.system_administration.system_utilities.api_logs')],
  data () {
    return {
      loading: false,
      tableData: [],
      columns: [],
      rowButtons: [],
      pagination: { current: 1, size: 10, total: 0 },
      search: {
        ip: '',
        unit: '',
        status: undefined,
        batch: '',
        tray: '',
        process_code: '',
        battery_id: '',
        time: undefined
      },
      respVisible: false,
      respParam: null,
      respResult: null,
      searchExpanded: false
    }
  },
  computed: {
    prefix () {
      return 'page.system_administration.system_utilities.api_logs'
    }
  },
  created () {
    this.columns = useTableColumns([
      { prop: 'id', label: this.key('id'), width: 65 },
      { prop: 'client_ip', label: this.key('ip'), width: 140 },
      { prop: 'unit', label: this.key('request_method'), minWidth: 150 },
      { prop: 'status', label: this.key('response_status'), slot: 'status', width: 100 },
      { prop: 'insterface_time', label: this.key('response_time_ms'), width: 130 },
      { prop: 'data1', label: this.key('process_code'), showOverflowTooltip: true, minWidth: 120 },
      { prop: 'data2', label: this.key('tray_number'), showOverflowTooltip: true, minWidth: 120 },
      { prop: 'data3', label: this.key('battery_id'), showOverflowTooltip: true, minWidth: 130 },
      { prop: 'data4', label: this.key('batch_number'), showOverflowTooltip: true, minWidth: 120 },
      { prop: 'data5', label: this.key('process_id'), 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/interface_log/view',
          onClick: this.handleViewResponse
        }
      ]
    }, this.$permission)
    this.rowButtons = btns.rowButtons
    this.fetchData()
  },
  methods: {
    async fetchData () {
      this.loading = true
      try {
        const params = {
          ...this.search,
          page_no: this.pagination.current,
          page_size: this.pagination.size
        }
        const res = await getInterfaceLogList(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 = ''
      this.search.unit = ''
      this.search.status = undefined
      this.search.batch = ''
      this.search.tray = ''
      this.search.process_code = ''
      this.search.battery_id = ''
      this.search.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>
