<template>
  <d2-container>
    <template #header>
      <div class="search-bar">
        <el-form ref="searchForm" :inline="true" :model="search" size="mini">
          <el-form-item :label="$t(key('item_code'))" prop="item_code">
            <el-input
              v-model.trim="search.item_code"
              :placeholder="$t(key('enter_item_code'))"
              clearable
              style="width:220px"
              @keyup.enter.native="onSearch"
            />
          </el-form-item>
          <el-form-item :label="$t(key('item_batch'))" prop="item_batch">
            <el-input
              v-model.trim="search.item_batch"
              :placeholder="$t(key('enter_item_batch'))"
              clearable
              style="width:220px"
              @keyup.enter.native="onSearch"
            />
          </el-form-item>
          <el-form-item :label="$t(key('item_id'))" prop="item_id">
            <el-input
              v-model.trim="search.item_id"
              :placeholder="$t(key('enter_item_id'))"
              clearable
              style="width:220px"
              @keyup.enter.native="onSearch"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" :disabled="loading" @click="onSearch">
              {{ $t(key('query')) }}
            </el-button>
            <el-button icon="el-icon-download" :disabled="loading" @click="exportTask">
              {{ $t(key('export')) }}
            </el-button>
            <el-button icon="el-icon-refresh" :disabled="loading" @click="onReset">
              {{ $t(key('reset')) }}
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </template>

    <page-table
      :columns="columns"
      :data="pagedData"
      :loading="loading"
      :toolbar-buttons="[]"
      :row-buttons="rowButtons"
      :pagination="pagination"
      :table-attrs="{ size: 'mini', rowKey: rowKey, highlightCurrentRow: true }"
      auto-height
      @page-change="onPageChange"
    >
      <template #empty>
        <el-empty :description="$t(key('no_data'))" :image-size="80" />
      </template>
    </page-table>
  </d2-container>
</template>

<script>
import { useTableColumns } from '@/composables/useTableColumns'
import { i18nMixin } from '@/composables/useI18n'
import PageTable from '@/components/page-table'
import {
  createForwardTraceabilityExportTask,
  getForwardTraceabilityList
} from '@/api/data-platform/traceability/forward'

export default {
  name: 'data-platform-traceability-forward',
  components: { PageTable },
  mixins: [i18nMixin('page.data_platform.traceability.forward')],
  data () {
    return {
      loading: false,
      search: {
        item_code: '',
        item_batch: '',
        item_id: ''
      },
      tableData: [],
      pagination: {
        current: 1,
        size: 10,
        total: 0
      }
    }
  },
  computed: {
    columns () {
      return useTableColumns([
        { prop: 'battery_id', label: this.key('battery_id'), minWidth: 170, showOverflowTooltip: true },
        { prop: 'batch', label: this.key('batch_id'), minWidth: 150, showOverflowTooltip: true },
        { prop: 'item_name', label: this.key('item_name'), minWidth: 180, showOverflowTooltip: true },
        { prop: 'item_code', label: this.key('item_code'), minWidth: 170, showOverflowTooltip: true },
        { prop: 'item_batch', label: this.key('item_batch'), minWidth: 170, showOverflowTooltip: true },
        { prop: 'device_code', label: this.key('device_code'), minWidth: 150, showOverflowTooltip: true },
        { prop: 'workingsubclass', label: this.key('work_unit'), minWidth: 150, showOverflowTooltip: true },
        { prop: 'process_code', label: this.key('process_code'), minWidth: 150, showOverflowTooltip: true },
        { prop: 'finish_time', label: this.key('finish_time'), minWidth: 170, showOverflowTooltip: true }
      ], {
        selectionWidth: 0,
        indexWidth: 55,
        operationWidth: 120
      })
    },
    rowButtons () {
      return [
        {
          key: 'reverse',
          label: this.key('reverse'),
          type: 'primary',
          icon: 'el-icon-position',
          size: 'mini',
          onClick: this.goBackwardTraceability
        }
      ]
    },
    pagedData () {
      const start = (this.pagination.current - 1) * this.pagination.size
      return this.tableData.slice(start, start + this.pagination.size)
    }
  },
  created () {
    this.fetchData()
  },
  methods: {
    rowKey (row) {
      return row.id || `${row.battery_id || ''}-${row.item_code || ''}-${row.item_batch || ''}-${row.finish_time || ''}`
    },
    responseData (res) {
      return res && res.data !== undefined ? res.data : res
    },
    buildParams () {
      return {
        ...this.search,
        page_no: this.pagination.current,
        page_size: this.pagination.size
      }
    },
    validateSearch () {
      if (this.search.item_code && !this.search.item_batch) {
        this.$message.error(this.$t(this.key('enter_item_batch')))
        return false
      }
      return true
    },
    async fetchData () {
      if (!this.validateSearch()) return
      this.loading = true
      try {
        const res = await getForwardTraceabilityList(this.buildParams())
        const data = this.responseData(res)
        this.tableData = Array.isArray(data) ? data : []
        this.pagination.total = this.tableData.length
      } finally {
        this.loading = false
      }
    },
    onSearch () {
      this.pagination.current = 1
      this.fetchData()
    },
    onReset () {
      this.search = {
        item_code: '',
        item_batch: '',
        item_id: ''
      }
      this.pagination.current = 1
      this.fetchData()
    },
    onPageChange (page) {
      this.pagination = { ...this.pagination, ...page }
    },
    hasFilter () {
      return Object.keys(this.search).some(key => this.search[key])
    },
    async exportTask () {
      if (!this.hasFilter()) {
        this.$message.error(this.$t(this.key('please_select_filter_condition')))
        return
      }
      await this.$confirm(this.$t(this.key('export_confirm')), this.$t(this.key('prompt')), {
        type: 'warning',
        confirmButtonText: this.$t(this.key('confirm')),
        cancelButtonText: this.$t(this.key('cancel'))
      })
      await createForwardTraceabilityExportTask({
        ...this.search,
        total: this.pagination.total,
        action: 'download'
      })
      this.$message.success(this.$t(this.key('create_download_task_success')))
      this.$router.push({ name: 'task' })
    },
    goBackwardTraceability (row) {
      this.$router.push({
        name: 'data_middleground-basic_traceability-reverse_direction_traceability',
        params: { battery_id: row.battery_id }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.search-bar {
  margin-bottom: -18px;
}
</style>
