<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('battery_code'))" prop="battery_id">
            <el-input v-model.trim="search.battery_id" :placeholder="$t(key('enter_battery_code'))" clearable style="width:240px" @keyup.enter.native="fetchData" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" :disabled="loading" @click="fetchData">{{ $t(key('query')) }}</el-button>
            <el-button icon="el-icon-refresh" :disabled="loading" @click="resetSearch">{{ $t(key('reset')) }}</el-button>
          </el-form-item>
        </el-form>
      </div>
    </template>

    <page-table
      :columns="columns"
      :data="tableData"
      :loading="loading"
      :toolbar-buttons="[]"
      :row-buttons="rowButtons"
      :pagination="pagination"
      :table-attrs="{ size: 'mini', rowKey: 'battery_id', highlightCurrentRow: true }"
      auto-height
      @page-change="onPageChange"
    >
      <template #col-active="{ row }">
        <el-tag :type="Number(row.active) === 1 ? 'success' : 'warning'" size="mini">{{ Number(row.active) === 1 ? $t(key('activated')) : $t(key('stopped')) }}</el-tag>
      </template>
      <template #col-class="{ row }">
        <el-tag v-if="row.class === 'GOOD'" type="success" size="mini">GOOD</el-tag>
        <el-tag v-else-if="row.class === 'NG'" type="warning" size="mini">NG</el-tag>
        <span v-else>{{ row.class || '-' }}</span>
      </template>
      <template #empty>
        <el-empty :description="$t(key('no_data'))" :image-size="80" />
      </template>
    </page-table>

    <el-dialog :visible.sync="detailVisible" :show-close="false" fullscreen append-to-body>
      <div slot="title">
        <el-page-header @back="closeDetail" :content="detailTitle" />
      </div>
      <div class="detail-layout">
        <aside class="process-list">
          <el-card shadow="never">
            <div slot="header">{{ $t(key('process_label')) }}</div>
            <el-button
              v-for="(item, index) in processList"
              :key="index"
              class="process-button"
              :type="activeProcessIndex === index ? 'primary' : 'default'"
              @click="selectProcess(index)"
            >
              {{ item.process_name || item.process_code || '-' }}
            </el-button>
          </el-card>
        </aside>
        <main class="process-detail">
          <el-card shadow="never">
            <div slot="header">【{{ activeProcessName }}】{{ $t(key('process_data')) }}</div>
            <el-input v-model.trim="detailKeyword" size="mini" clearable :placeholder="$t(key('search_item_name'))" class="detail-search" />
            <el-table :data="filteredGridData" border size="mini" height="calc(100vh - 230px)">
              <el-table-column type="index" width="60" />
              <el-table-column prop="name" :label="$t(key('item_name'))" min-width="180" show-overflow-tooltip />
              <el-table-column prop="content" :label="$t(key('content'))" min-width="220" show-overflow-tooltip />
            </el-table>
          </el-card>
        </main>
      </div>
    </el-dialog>
  </d2-container>
</template>

<script>
import { useTableColumns } from '@/composables/useTableColumns'
import { i18nMixin } from '@/composables/useI18n'
import PageTable from '@/components/page-table'
import { sendWorkerman } from '@/api/production-master-data/workerman'
import { cancelBatteryActive, getBatteryProcessData, getBatteryTraceList } from '@/api/data-platform/traceability/battery'

export default {
  name: 'data-platform-traceability-battery',
  components: { PageTable },
  mixins: [i18nMixin('page.data_platform.traceability.battery')],
  data () {
    return {
      loading: false,
      search: { battery_id: this.$route.query.battery_id || '' },
      tableData: [],
      pagination: { current: 1, size: 10, total: 0 },
      detailVisible: false,
      activeBattery: {},
      processList: [],
      activeProcessIndex: -1,
      gridData: [],
      detailKeyword: ''
    }
  },
  computed: {
    columns () {
      return useTableColumns([
        { prop: 'battery_id', label: this.key('battery_code'), minWidth: 180, showOverflowTooltip: true },
        { prop: 'batch', label: this.key('login_batch'), minWidth: 140, showOverflowTooltip: true },
        { prop: 'tray', label: this.key('tray_no'), minWidth: 130, showOverflowTooltip: true },
        { prop: 'lot', label: this.key('lot'), minWidth: 120, showOverflowTooltip: true },
        { prop: 'active', label: this.key('is_active'), minWidth: 110, slot: 'active' },
        { prop: 'class', label: this.key('good_or_ng'), minWidth: 110, slot: 'class' },
        { prop: 'classname', label: this.key('grade'), minWidth: 120, showOverflowTooltip: true },
        { prop: 'explain', label: this.key('ng_info'), minWidth: 160, showOverflowTooltip: true },
        { prop: 'next_process_code', label: this.key('current_process_code'), minWidth: 160, showOverflowTooltip: true }
      ], { selectionWidth: 0, indexWidth: 55, operationWidth: 260 })
    },
    rowButtons () {
      return [
        { key: 'detail', label: this.key('battery_detail'), type: 'primary', icon: 'el-icon-document', size: 'mini', onClick: this.openDetail },
        { key: 'cancel', label: this.key('cancel_activation'), type: 'warning', icon: 'el-icon-close', size: 'mini', visible: row => Number(row.active) === 1, onClick: this.cancelActive },
        { key: 'rebatch', label: this.key('reinvestment_activation'), type: 'success', icon: 'el-icon-refresh-right', size: 'mini', visible: row => Number(row.active) === 0 && row.class === 'NG', onClick: this.reinvestmentActivation }
      ]
    },
    detailTitle () {
      return this.$t(this.key('title'), { battery_id: this.activeBattery.battery_id || '' })
    },
    activeProcessName () {
      const item = this.processList[this.activeProcessIndex] || {}
      return item.process_name || item.process_code || '-'
    },
    filteredGridData () {
      const keyword = String(this.detailKeyword || '').toLowerCase()
      return this.gridData.filter(item => !keyword || String(item.name || '').toLowerCase().includes(keyword))
    }
  },
  watch: {
    '$route.query.battery_id' (value) {
      if (value) {
        this.search.battery_id = value
        this.fetchData()
      }
    }
  },
  mounted () {
    if (this.search.battery_id) this.fetchData()
  },
  methods: {
    responseData (res) { return res && res.data !== undefined ? res.data : res },
    async fetchData () {
      this.loading = true
      try {
        const res = await getBatteryTraceList({ ...this.search, action: 'battery_traceability_search', page_no: this.pagination.current, page_size: this.pagination.size })
        const data = this.responseData(res)
        this.tableData = Array.isArray(data) ? data : []
        this.pagination.total = Number(data && data.count) || this.tableData.length
      } finally {
        this.loading = false
      }
    },
    resetSearch () {
      this.search.battery_id = ''
      this.tableData = []
      this.pagination.current = 1
      this.pagination.total = 0
    },
    onPageChange (page) {
      this.pagination = { ...this.pagination, ...page }
      this.fetchData()
    },
    openDetail (row) {
      this.activeBattery = row
      this.processList = Array.isArray(row.process) ? row.process : []
      this.activeProcessIndex = -1
      this.gridData = []
      this.detailKeyword = ''
      this.detailVisible = true
      if (this.processList.length) this.selectProcess(0)
    },
    closeDetail () {
      this.detailVisible = false
    },
    async selectProcess (index) {
      const process = this.processList[index]
      if (!process) return
      this.activeProcessIndex = index
      const res = await getBatteryProcessData({
        process_code: process.process_code,
        process_id: process.process_id,
        batch: this.activeBattery.batch,
        battery_id: this.activeBattery.battery_id,
        tray: this.activeBattery.tray,
        lot: this.activeBattery.lot,
        action: 'get_one_battery_data'
      })
      const data = this.responseData(res)
      this.gridData = Array.isArray(data) ? data : []
    },
    async cancelActive (row) {
      await this.$confirm(this.$t(this.key('cancel_active_confirm')), this.$t(this.key('prompt')), { type: 'warning' })
      const batterData = [{ batch: row.batch, tray: row.tray, lot: row.lot, battery_id: row.battery_id }]
      await cancelBatteryActive({ batterData: JSON.stringify(batterData) })
      row.active = 0
      this.$message.success(this.$t(this.key('cancel_success')))
    },
    async reinvestmentActivation (row) {
      await this.$confirm(this.$t(this.key('activation_confirm')), this.$t(this.key('prompt')), { type: 'warning' })
      const sendData = { action: 'set_battery_rebatch', param: { battery_ids: [row.battery_id] } }
      await sendWorkerman({ sendData })
      this.$message.success(this.$t(this.key('activation_success')))
      this.search.battery_id = row.battery_id
      this.fetchData()
    }
  }
}
</script>

<style lang="scss" scoped>
.search-bar { margin-bottom: -18px; }
.detail-layout { display: grid; grid-template-columns: 260px minmax(0, 1fr); gap: 16px; }
.process-list { max-height: calc(100vh - 150px); overflow: auto; }
.process-button { display: block; width: 100%; margin: 0 0 10px; }
.process-detail { min-width: 0; }
.detail-search { width: 260px; margin-bottom: 12px; }
</style>
