<template>
  <div class="xxx-container auto-height-container" :class="{ 'fullscreen-container': isFullscreen }">
    <vab-query-form>
      <vab-query-form-top-panel>
        <el-form ref="queryRef" inline label-width="70px" :model="queryForm" @submit.prevent>
          <el-form-item label="操作地址" prop="operIp">
            <el-input v-model="queryForm.operIp" clearable placeholder="请输入操作地址" style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item v-show="!fold" label="系统模块" prop="title">
            <el-input v-model="queryForm.title" clearable placeholder="请输入系统模块" style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item v-show="!fold" label="操作人员" prop="operName">
            <el-input v-model="queryForm.operName" clearable placeholder="请输入操作人员" style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item v-show="!fold" label="类型" prop="businessType">
            <el-select v-model="queryForm.businessType" clearable placeholder="操作类型" style="width: 240px">
              <el-option v-for="dict in sys_oper_type" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item v-show="!fold" label="状态" prop="status">
            <el-select v-model="queryForm.status" clearable placeholder="操作状态" style="width: 240px">
              <el-option v-for="dict in sys_common_status" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item v-show="!fold" label="操作时间" prop="dateRange" style="width: 308px">
            <el-date-picker
              v-model="queryForm.dateRange"
              :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
              end-placeholder="结束日期"
              range-separator="-"
              start-placeholder="开始日期"
              type="daterange"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
          <el-form-item>
            <el-button icon="Search" :loading="listLoading" native-type="submit" type="primary" @click="handleQuery">查询</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            <el-button class="hidden-xs-only" text type="primary" @click="handleFold">
              <span v-if="fold">展开</span>
              <span v-else>合并</span>
              <vab-icon class="vab-dropdown" :class="{ 'vab-dropdown-active': fold }" icon="arrow-up-s-line" />
            </el-button>
          </el-form-item>
        </el-form>
      </vab-query-form-top-panel>
      <vab-query-form-left-panel>
        <el-button icon="Delete" type="danger" @click="handleDelete">删除</el-button>
        <el-button icon="Delete" type="danger" @click="handleClean">清空</el-button>
        <el-button icon="Upload" plain type="warning" @click="handleExport">导出</el-button>
      </vab-query-form-left-panel>
      <vab-query-form-right-panel>
        <div class="custom-table-right-tools">
          <el-button @click="handleQuery">
            <vab-icon icon="refresh-line" />
          </el-button>
          <el-button @click="clickFullScreen">
            <vab-icon :icon="isFullscreen ? 'fullscreen-exit-fill' : 'fullscreen-fill'" />
          </el-button>
          <el-popover popper-class="custom-table-checkbox">
            <template #reference>
              <el-button>
                <vab-icon icon="settings-line" />
              </el-button>
            </template>
            <vab-draggable v-model="columns" :animation="600" target=".el-checkbox-group">
              <el-checkbox-group v-model="checkList">
                <el-checkbox
                  v-for="item in columns"
                  :key="item.label"
                  :disabled="item.disableCheck"
                  :label="item.label"
                  :value="item.label"
                >
                  {{ item.label }}
                </el-checkbox>
              </el-checkbox-group>
            </vab-draggable>
          </el-popover>
        </div>
      </vab-query-form-right-panel>
    </vab-query-form>

    <el-table
      ref="tableRef"
      v-loading="listLoading"
      border
      :data="list"
      :default-sort="defaultSort"
      @selection-change="setSelectRows"
      @sort-change="handleSortChange"
    >
      <el-table-column align="center" type="selection" width="50" />

      <el-table-column
        v-for="(item, index) in finallyColumns"
        :key="index"
        align="center"
        :fixed="item.fixed"
        :label="item.label"
        :min-width="item.minWidth || 160"
        :prop="item.prop"
        show-overflow-tooltip
        :sortable="item.sortable"
      >
        <template #default="scope">
          <span v-if="item.label === '操作类型'">
            <dict-tag :options="sys_oper_type" :value="scope.row.businessType" />
          </span>
          <span v-else-if="item.label === '操作状态'">
            <dict-tag :options="sys_common_status" :value="scope.row.status" />
          </span>
          <span v-else-if="item.label === '消耗时间'">{{ scope.row.costTime }}毫秒</span>
          <span v-else>{{ scope.row[item.prop] }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" fixed="right" label="操作" min-width="100">
        <template #default="scope">
          <el-button icon="View" link type="primary" @click="handleView(scope.row, scope.index)">详细</el-button>
        </template>
      </el-table-column>
      <template #empty>
        <el-empty class="vab-data-empty" description="暂无数据" />
      </template>
    </el-table>
    <vab-pagination
      :current-page="queryForm.pageNum"
      :page-size="queryForm.pageSize"
      :total="total"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
    />

    <operator-detail ref="detailRef" />
  </div>
</template>

<script lang="ts" setup>
import type { TableInstance } from 'element-plus'
import { VueDraggable as VabDraggable } from 'vue-draggable-plus'
import { cleanOperlog, doDelete, getList } from '/@/api/operatorLog'

defineOptions({
  name: 'OperatorLog',
})

const { proxy } = getCurrentInstance() as any
const { sys_common_status, sys_oper_type } = proxy.useDict('sys_common_status', 'sys_oper_type')

const { exit, enter, isFullscreen: _isFullscreen } = useFullscreen()

const isFullscreen = ref<boolean>(false)
const fold = ref<boolean>(true)
const tableRef = ref<TableInstance>()
const detailRef = ref<any>(null)
const list = ref<any>([])
const listLoading = ref<boolean>(true)

const total = ref<number>(0)
const selectRows = ref<any>([])
const checkList = ref<any>([])
const queryForm = reactive<any>({
  pageNum: 1,
  pageSize: 10,
  operIp: undefined,
  title: undefined,
  operName: undefined,
  businessType: undefined,
  status: undefined,
  dateRange: [],
  orderByColumn: undefined,
  isAsc: undefined,
})
const defaultSort = ref<any>({ prop: 'operTime', order: 'descending' })

const columns = ref<any>([
  { label: '日志编号', prop: 'operId', minWidth: 120, checked: true },
  { label: '系统模块', prop: 'title', minWidth: 160, checked: true },
  { label: '操作类型', prop: 'businessType', minWidth: 160, checked: true },
  { label: '操作人员', prop: 'operName', minWidth: 110, sortable: 'custom', checked: true },
  { label: '操作地址', prop: 'operIp', minWidth: 130, checked: true },
  { label: '操作状态', prop: 'status', minWidth: 120, checked: true },
  { label: '操作日期', prop: 'operTime', minWidth: 160, sortable: 'custom', checked: true },
  { label: '消耗时间', prop: 'costTime', minWidth: 160, sortable: 'custom', checked: true },
])
const finallyColumns = computed(() => columns.value.filter((item: any) => checkList.value.includes(item.label)))

watch(
  _isFullscreen,
  () => {
    if (_isFullscreen.value) isFullscreen.value = true
    else isFullscreen.value = false
  },
  { immediate: true }
)

onActivated(() => {
  tableRef.value?.doLayout()
})

onBeforeMount(() => {
  columns.value.forEach((item: any) => {
    if (item.checked) checkList.value.push(item.label)
  })
  fetchData()
})

/** 点击全屏 */
const clickFullScreen = () => {
  isFullscreen.value = !isFullscreen.value
  isFullscreen.value ? enter() : exit()
}

/** 搜索条件折叠 */
const handleFold = () => {
  fold.value = !fold.value
}

/** 查询用户列表 */
const fetchData = async () => {
  listLoading.value = true
  // const pp = Object.assign({}, queryForm)
  const pp = Object.assign({}, proxy.addDateRange(queryForm, queryForm.dateRange))
  delete pp.dateRange
  const { rows, total: _total } = (await getList(pp)) as any
  list.value = rows
  total.value = _total
  listLoading.value = false
}

/** 搜索按钮操作 */
function handleQuery() {
  queryForm.pageNum = 1
  fetchData()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm('queryRef')
  handleQuery()
}

const handleSizeChange = (value: number) => {
  queryForm.pageNum = 1
  queryForm.pageSize = value
  fetchData()
}

const handleCurrentChange = (value: number) => {
  queryForm.pageNum = value
  fetchData()
}

const setSelectRows = (value: string) => {
  selectRows.value = value
}

/** 排序触发事件 */
function handleSortChange(column: any) {
  queryForm.orderByColumn = column.prop
  queryForm.isAsc = column.order
  fetchData()
}

/** 详细按钮操作 */
function handleView(row: any) {
  detailRef.value.show(row)
}

/** 清空按钮操作 */
function handleClean() {
  $baseConfirm('是否确认清空所有操作日志数据项?', null, async () => {
    await cleanOperlog()
    $baseMessage('清空成功', 'success', 'hey')
    await fetchData()
  })
}

/** 删除按钮操作 */
const handleDelete = (row: any = {}) => {
  if (row.operId) {
    $baseConfirm(`您确定要删除日志编号为“${row.operId}”的数据项吗`, null, async () => {
      const { msg }: any = await doDelete(row.operId)
      $baseMessage(msg, 'success', 'hey')
      await fetchData()
    })
  } else {
    if (selectRows.value.length > 0) {
      const ids = selectRows.value.map((item: { operId: any }) => item.operId)
      $baseConfirm('您确定要删除选中项吗', null, async () => {
        const { msg }: any = await doDelete(ids)
        $baseMessage(msg, 'success', 'hey')
        await fetchData()
      })
    } else {
      $baseMessage('您未选中任何行', 'warning', 'hey')
    }
  }
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    'monitor/operlog/export',
    {
      ...queryForm,
    },
    `operlog_${Date.now()}.xlsx`
  )
}
</script>
