<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('flow'))" prop="flow_idx">
            <el-select v-model="search.flow_idx" :placeholder="$t(key('select_flow'))" clearable filterable style="width:180px" @change="onFlowChange">
              <el-option v-for="(item, index) in flowOptions" :key="item.id || index" :label="item.name" :value="index" />
            </el-select>
          </el-form-item>
          <el-form-item :label="$t(key('batch'))" prop="batch">
            <el-select v-model="search.batch" :placeholder="$t(key('select_batch'))" multiple collapse-tags clearable filterable style="width:220px">
              <el-option v-for="item in batchOptions" :key="item.id || item.batch" :label="item.batch" :value="item.batch" />
            </el-select>
          </el-form-item>
          <el-form-item :label="$t(key('process'))" prop="process_id">
            <el-select v-model="search.process_id" :placeholder="$t(key('select_process'))" multiple collapse-tags clearable filterable style="width:220px">
              <el-option v-for="item in processOptions" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item :label="$t(key('tray_no'))" prop="tray">
            <el-input v-model.trim="search.tray" :placeholder="$t(key('enter_tray_no'))" clearable style="width:180px" />
          </el-form-item>
          <el-form-item :label="$t(key('time'))" prop="time">
            <el-date-picker v-model="search.time" type="datetimerange" value-format="yyyy-MM-dd HH:mm:ss" :start-placeholder="$t(key('start_date'))" :end-placeholder="$t(key('end_date'))" style="width:330px" />
          </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-refresh" :disabled="loading" @click="onReset">{{ $t(key('reset')) }}</el-button>
            <el-button type="primary" icon="el-icon-download" :disabled="loading" @click="exportTask">{{ $t(key('export')) }}</el-button>
          </el-form-item>
        </el-form>
      </div>
    </template>

    <el-table v-loading="loading" :data="tableData" size="mini" border height="calc(100vh - 220px)">
      <el-table-column type="index" width="55" />
      <el-table-column v-for="column in flatColumns" :key="column.prop" :prop="column.prop" :label="column.label" min-width="160" show-overflow-tooltip />
      <template #empty><el-empty :description="$t(key('no_data'))" :image-size="80" /></template>
    </el-table>
    <div class="pager">
      <el-pagination background layout="total, sizes, prev, pager, next, jumper" :current-page="pagination.current" :page-size="pagination.size" :total="pagination.total" @current-change="changePage" @size-change="changeSize" />
    </div>
  </d2-container>
</template>

<script>
import { i18nMixin } from '@/composables/useI18n'
import { createBatteryDetailExportTask, getBatteryDetailFlowBatch, getBatteryDetailList, getBatteryDetailTitle } from '@/api/data-platform/production-reports/battery-detail'

export default {
  name: 'data-platform-production-reports-battery-detail',
  mixins: [i18nMixin('page.data_platform.production_reports.battery_detail')],
  data () {
    return { loading: false, search: { flow_idx: '', flow_id: '', batch: [], process_id: [], tray: '', time: [] }, flowOptions: [], batchOptions: [], processOptions: [], title: [], tableData: [], pagination: { current: 1, size: 10, total: 0 } }
  },
  computed: {
    flatColumns () {
      const result = []
      const walk = list => {
        ;(Array.isArray(list) ? list : []).forEach(item => {
          if (Array.isArray(item.child) && item.child.length) walk(item.child)
          else if (item.prop) result.push({ prop: item.prop, label: item.label || item.prop })
        })
      }
      walk(this.title)
      if (result.length) return result
      const first = this.tableData[0] || {}
      return Object.keys(first).slice(0, 30).map(key => ({ prop: key, label: key }))
    }
  },
  mounted () { this.loadOptions() },
  methods: {
    responseData (res) { return res && res.data !== undefined ? res.data : res },
    async loadOptions () {
      const res = await getBatteryDetailFlowBatch({ action: 'where_data', batch: 'batch' })
      this.flowOptions = this.responseData(res) || []
    },
    onFlowChange (index) {
      const flow = this.flowOptions[index] || {}
      this.search.flow_id = flow.id || ''
      this.search.batch = []
      this.search.process_id = []
      this.batchOptions = Array.isArray(flow.batch_manage) ? flow.batch_manage : []
      this.processOptions = Array.isArray(flow.process) ? flow.process : []
    },
    buildParams () {
      const time = Array.isArray(this.search.time) ? this.search.time : []
      return { ...this.search, start_time: time[0], end_time: time[1], page_no: this.pagination.current, page_size: this.pagination.size }
    },
    async fetchData () {
      if (!this.search.batch || !this.search.batch.length) { this.$message.warning(this.$t(this.key('please_select_batch'))); return }
      this.loading = true
      try {
        const params = this.buildParams()
        const titleRes = await getBatteryDetailTitle(params)
        this.title = this.responseData(titleRes) || []
        const res = await getBatteryDetailList({ ...params, action: 'get_data' })
        const data = this.responseData(res)
        const list = data && data.data && Array.isArray(data.data.data) ? data.data.data : (Array.isArray(data && data.data) ? data.data : (Array.isArray(data) ? data : []))
        this.tableData = list
        this.pagination.total = Number(data && data.data && data.data.count) || Number(data && data.count) || list.length
      } finally { this.loading = false }
    },
    onSearch () { this.pagination.current = 1; this.fetchData() },
    onReset () { this.search = { flow_idx: '', flow_id: '', batch: [], process_id: [], tray: '', time: [] }; this.batchOptions = []; this.processOptions = []; this.title = []; this.tableData = []; this.pagination.current = 1; this.pagination.total = 0 },
    changePage (page) { this.pagination.current = page; this.fetchData() },
    changeSize (size) { this.pagination.size = size; this.pagination.current = 1; this.fetchData() },
    async exportTask () {
      if (!this.search.batch || !this.search.batch.length) { this.$message.warning(this.$t(this.key('please_select_batch'))); return }
      await this.$confirm(this.$t(this.key('export_confirm')), this.$t(this.key('prompt')), { type: 'warning' })
      await createBatteryDetailExportTask({ ...this.buildParams(), action: 'download' })
      this.$message.success(this.$t(this.key('create_download_task_success')))
      this.$router.push({ name: 'task' })
    }
  }
}
</script>

<style lang="scss" scoped>
.search-bar { margin-bottom: -18px; }
.pager { padding-top: 10px; text-align: right; }
</style>
