<template>
  <d2-container>
    <template #header>
      <div class="search-bar">
        <el-form ref="form" :inline="true" :model="form" size="mini">
          <el-form-item :label="$t(key('battery_id'))" prop="battery_ids">
            <el-input
              v-model="form.battery_ids"
              :placeholder="$t(key('enter_battery_id'))"
              class="battery-input"
              clearable
              @keyup.enter.native="verifyData"
            >
              <el-button slot="append" icon="el-icon-document-add" @click="openBatchInput" />
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              :disabled="loading"
              :loading="loading"
              @click="verifyData"
            >
              {{ $t(key('verify_data')) }}
            </el-button>
            <el-button icon="el-icon-refresh" :disabled="loading" @click="resetForm">
              {{ $t(key('reset')) }}
            </el-button>
            <el-button type="warning" :disabled="loading" @click="setBatteryRebatch">
              {{ $t(key('re_activate')) }}
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </template>

    <page-table
      :columns="columns"
      :data="tableData"
      :loading="loading"
      :toolbar-buttons="[]"
      :row-buttons="[]"
      :pagination="null"
      :table-attrs="{ size: 'mini', rowKey: 'battery_id', highlightCurrentRow: true }"
      auto-height
    >
      <template #col-active="{ row }">
        <el-tag :type="Number(row.active) === 0 ? 'info' : 'success'" size="mini">
          {{ Number(row.active) === 0 ? $t(key('not_activated')) : $t(key('active')) }}
        </el-tag>
      </template>
      <template #empty>
        <el-empty :description="$t('暂无数据')" :image-size="80" />
      </template>
    </page-table>

    <battery-input-dialog
      :visible.sync="dialogVisible"
      :value="dialogBatteryIds"
      @confirm="confirmBatchInput"
    />
  </d2-container>
</template>

<script>
import { useTableColumns } from '@/composables/useTableColumns'
import { i18nMixin } from '@/composables/useI18n'
import PageTable from '@/components/page-table'
import BatteryInputDialog from './components/BatteryInputDialog'
import { sendWorkerman } from '@/api/production-master-data/workerman'
import { verifyBatteryRebatchInfo } from '@/api/planning-production/rework-management'

export default {
  name: 'planning-production-rework-management',
  components: { PageTable, BatteryInputDialog },
  mixins: [i18nMixin('page.planning_production.production_monitoring.rework_management')],
  data () {
    return {
      loading: false,
      form: {
        battery_ids: ''
      },
      tableData: [],
      dialogVisible: false,
      dialogBatteryIds: ''
    }
  },
  computed: {
    columns () {
      return useTableColumns([
        { prop: 'battery_id', label: this.key('battery_id'), minWidth: 180, showOverflowTooltip: true },
        { prop: 'batch', label: this.key('batch'), minWidth: 150, showOverflowTooltip: true },
        { prop: 'tray', label: this.key('tray'), minWidth: 110, showOverflowTooltip: true },
        { prop: 'lot', label: this.key('lot'), minWidth: 90, showOverflowTooltip: true },
        { prop: 'active', label: this.key('active_status'), width: 120, slot: 'active' },
        { prop: 'class', label: this.key('class_type'), minWidth: 90, showOverflowTooltip: true },
        { prop: 'classname', label: this.key('class'), minWidth: 90, showOverflowTooltip: true },
        { prop: 'process_code', label: this.key('previous_process'), minWidth: 180, showOverflowTooltip: true },
        { prop: 'next_process_code', label: this.key('current_process'), minWidth: 180, showOverflowTooltip: true }
      ], {
        selectionWidth: 55,
        indexWidth: 55
      }).map(col => {
        if (col.type === 'index') col.label = this.key('sort')
        return col
      })
    }
  },
  methods: {
    normalizeBatteryIds (value) {
      return String(value || '')
        .split(/[\n,，\s]+/)
        .map(item => item.trim())
        .filter(Boolean)
        .join(',')
    },
    ensureBatteryInput () {
      this.form.battery_ids = this.normalizeBatteryIds(this.form.battery_ids)
      if (this.form.battery_ids) return true
      this.$message.warning(this.$t(this.key('enter_battery_data')))
      return false
    },
    openBatchInput () {
      this.form.battery_ids = ''
      this.dialogBatteryIds = ''
      this.dialogVisible = true
    },
    confirmBatchInput (value) {
      this.dialogBatteryIds = value
      this.form.battery_ids = this.normalizeBatteryIds(value)
    },
    normalizeVerifyPayload (res) {
      const payload = res && res.code !== undefined && res.data !== undefined ? res.data : res
      if (
        payload &&
        !Array.isArray(payload) &&
        payload.data &&
        !Array.isArray(payload.data) &&
        payload.data.data
      ) {
        return payload.data
      }
      return payload || {}
    },
    normalizeVerifyRows (payload) {
      if (Array.isArray(payload)) return payload
      return Array.isArray(payload.data) ? payload.data : []
    },
    verifyData () {
      if (!this.ensureBatteryInput()) return
      this.loading = true
      verifyBatteryRebatchInfo(this.form)
        .then(res => {
          const data = this.normalizeVerifyPayload(res)
          this.tableData = this.normalizeVerifyRows(data)
        })
        .finally(() => {
          this.loading = false
        })
    },
    setBatteryRebatch () {
      if (!this.ensureBatteryInput()) return
      const batteryIds = this.tableData.map(item => item.battery_id).filter(Boolean)
      if (!batteryIds.length) {
        this.$message.warning(this.$t(this.key('verify_data_before_action')))
        return
      }

      this.$confirm(this.$t(this.key('re_activate_warning')), this.$t(this.key('prompt')), {
        confirmButtonText: this.$t(this.key('confirm')),
        cancelButtonText: this.$t(this.key('cancel')),
        type: 'warning',
        closeOnClickModal: false
      }).then(() => {
        this.loading = true
        return sendWorkerman({
          sendData: {
            action: 'set_battery_rebatch',
            param: {
              battery_ids: batteryIds
            }
          }
        }).then(res => {
          const data = res && res.data ? res.data : res
          if (data.code !== undefined && Number(data.code) !== 0) {
            this.$message.warning(data.errmsg || data.msg || this.$t(this.key('rethrow_activation_failed')))
            return
          }
          this.$message.success(this.$t(this.key('re_activate_success')))
          this.tableData = []
        }).catch(error => {
          this.$message.warning(`${this.$t(this.key('rethrow_activation_failed'))}: ${error}`)
        }).finally(() => {
          this.loading = false
        })
      }).catch(() => {})
    },
    resetForm () {
      if (this.$refs.form) this.$refs.form.resetFields()
      this.tableData = []
      this.dialogBatteryIds = ''
    }
  }
}
</script>

<style scoped>
.search-bar {
  margin-bottom: -18px;
}
.battery-input {
  width: 360px;
}
</style>
