<template>
  <d2-container>
    <template #header>
      <div class="search-bar">
        <el-form :inline="true" :model="search" size="mini">
          <el-form-item :label="$t(key('device_code'))">
            <el-input v-model.trim="search.device_code" :placeholder="$t(key('enter_device_code'))" clearable style="width:180px" @keyup.enter.native="onSearch" />
          </el-form-item>
          <el-form-item :label="$t(key('device_name'))">
            <el-input v-model.trim="search.device_name" :placeholder="$t(key('enter_device_name'))" clearable style="width:180px" @keyup.enter.native="onSearch" />
          </el-form-item>
          <el-form-item :label="$t(key('inspection_item_name'))">
            <el-input v-model.trim="search.device_check_items_name" :placeholder="$t(key('enter_inspection_item_name'))" clearable style="width:200px" @keyup.enter.native="onSearch" />
          </el-form-item>
          <el-form-item :label="$t(key('operator'))">
            <el-select v-model="search.user_id" :placeholder="$t(key('please_select_operator'))" clearable filterable style="width:180px">
              <el-option v-for="item in userOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item :label="$t(key('inspection_time'))">
            <el-date-picker v-model="search.create_time" type="datetimerange" value-format="yyyy-MM-dd HH:mm:ss" :start-placeholder="$t(key('start_time'))" :end-placeholder="$t(key('end_time'))" style="width:330px" />
          </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-form-item>
        </el-form>
      </div>
    </template>

    <page-table
      ref="pageTable"
      :columns="columns"
      :data="tableData"
      :loading="loading"
      :toolbar-buttons="toolbarButtons"
      :row-buttons="[]"
      :pagination="pagination"
      auto-height
      @page-change="onPageChange"
    >
      <template #col-result="{ row }">
        <el-tag :type="row.result === 'OK' ? 'success' : 'danger'" size="mini">{{ row.result }}</el-tag>
      </template>
    </page-table>
  </d2-container>
</template>

<script>
import { useTableColumns } from '@/composables/useTableColumns'
import { useTableButtons } from '@/composables/useTableButtons'
import { i18nMixin } from '@/composables/useI18n'
import { confirmMixin } from '@/composables/useConfirmHandle'
import PageTable from '@/components/page-table'
import { getUserList } from '@/api/system-administration/user'
import { getDetailsList, createExportTask } from '@/api/equipment-management/inspection-logs'

function readPageData (res) {
  if (Array.isArray(res)) return { list: res, total: res.length }
  if (res && Array.isArray(res.data)) return { list: res.data, total: Number(res.count || res.total || res.data.length) }
  if (res && res.data && Array.isArray(res.data.data)) {
    return { list: res.data.data, total: Number(res.data.count || res.data.total || res.data.data.length) }
  }
  return { list: [], total: 0 }
}

function compactParams (params) {
  const next = { ...params }
  if (!Array.isArray(next.create_time) || !next.create_time.length) delete next.create_time
  Object.keys(next).forEach(key => {
    if (next[key] === '' || next[key] === undefined || next[key] === null) delete next[key]
  })
  return next
}

export default {
  name: 'equipment-management-inspection-logs',
  components: { PageTable },
  mixins: [i18nMixin('page.equipment_management.inspection_management.inspection_logs'), confirmMixin],
  data () {
    return {
      loading: false,
      tableData: [],
      userOptions: [],
      search: { device_code: '', device_name: '', device_check_items_name: '', user_id: '', create_time: [] },
      pagination: { current: 1, size: 10, total: 0 },
      columns: [],
      toolbarButtons: []
    }
  },
  created () {
    this.columns = useTableColumns([
      { prop: 'id', label: 'ID', width: 80, fixed: 'left' },
      { prop: 'device_code', label: this.key('device_code'), minWidth: 130, fixed: 'left' },
      { prop: 'device_name', label: this.key('device_name'), minWidth: 140 },
      { prop: 'device_category_name', label: this.key('device_category'), minWidth: 140 },
      { prop: 'device_check_items_name', label: this.key('inspection_item_name'), minWidth: 150 },
      { prop: 'result', label: this.key('inspection_result'), slot: 'result', width: 120 },
      { prop: 'val', label: this.key('inspection_value'), minWidth: 110 },
      { prop: 'standard', label: this.key('standard'), minWidth: 140, showOverflowTooltip: true },
      { prop: 'check_method', label: this.key('check_method'), minWidth: 130, showOverflowTooltip: true },
      { prop: 'unit', label: this.key('unit'), width: 90 },
      { prop: 'frequentness', label: this.key('frequentness'), width: 110 },
      { prop: 'example', label: this.key('example'), width: 110 },
      { prop: 'class_please', label: this.key('class_please'), width: 100 },
      { prop: 'implementation_people', label: this.key('implementation_people'), minWidth: 120 },
      { prop: 'username', label: this.key('operator'), minWidth: 120 },
      { prop: 'create_time', label: this.key('inspection_time'), minWidth: 160 }
    ], { selectionWidth: 0 })
    const btns = useTableButtons({
      toolbar: [
        { key: 'export', label: this.key('export'), icon: 'el-icon-download', type: 'success', onClick: this.handleExport }
      ],
      row: []
    }, this.$permission)
    this.toolbarButtons = btns.toolbarButtons
    this.loadUsers()
    this.fetchData()
  },
  methods: {
    async loadUsers () {
      const res = await getUserList({ page_no: 1, page_size: 10000 })
      const page = readPageData(res)
      this.userOptions = page.list.map(item => ({
        label: item.username || item.nickname || item.name,
        value: item.user_id || item.id
      }))
    },
    buildSearchParams () {
      return compactParams(this.search)
    },
    async fetchData () {
      this.loading = true
      try {
        const pageNo = Number(this.pagination.current) || 1
        const pageSize = Number(this.pagination.size) || 10
        const res = await getDetailsList({
          ...this.buildSearchParams(),
          page_no: pageNo,
          page_size: pageSize
        })
        const page = readPageData(res)
        this.tableData = page.list
        this.pagination.total = page.total
      } finally {
        this.loading = false
      }
    },
    onSearch () {
      this.pagination.current = 1
      this.fetchData()
    },
    onReset () {
      this.search = { device_code: '', device_name: '', device_check_items_name: '', user_id: '', create_time: [] }
      this.pagination.current = 1
      this.fetchData()
    },
    onPageChange (page) {
      this.pagination.current = Number(page.current || page.currentPage || 1)
      this.pagination.size = Number(page.size || page.pageSize || this.pagination.size || 10)
      this.fetchData()
    },
    async handleExport () {
      const cancelled = await this.$confirmAction(
        { message: this.key('confirm_export'), title: this.key('tip'), confirmButtonText: this.key('confirm'), cancelButtonText: this.key('cancel') },
        () => createExportTask({ ...this.buildSearchParams(), action: 'download' })
      )
      if (!cancelled) this.$message.success(this.$t(this.key('create_download_task_success')))
    }
  }
}
</script>

<style scoped>
.search-bar {
  padding: 10px 0;
}
/deep/ .el-form-item--mini.el-form-item {
  margin-bottom: 4px;
}
</style>
