<template>
  <div class="app-container batch-page">
    <el-card shadow="never" class="batch-card">
      <div slot="header" class="card-head">
        <div>
          <span class="title">智能批量导入</span>
          <span class="subtitle">支持 Excel 和图片，解析后先确认明细，再写入库存业务表。</span>
        </div>
        <el-button icon="el-icon-refresh" size="mini" @click="loadJobs">刷新任务</el-button>
      </div>

      <el-upload
        class="upload-box"
        drag
        action="#"
        accept=".xls,.xlsx,.jpg,.jpeg,.png,.bmp"
        :show-file-list="false"
        :http-request="handleUpload"
        :disabled="uploading"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">拖入 Excel 或图片，或 <em>点击上传</em></div>
        <div slot="tip" class="el-upload__tip">Excel 支持 xls/xlsx；图片支持 jpg/png/bmp。图片会调用大模型识别，耗时可能更久。</div>
      </el-upload>

      <div v-if="currentJob" class="job-panel">
        <div class="job-main">
          <div>
            <div class="job-no">{{ currentJob.jobNo }}</div>
            <div class="job-meta">{{ currentJob.fileName }} ｜ {{ statusLabel(currentJob.status) }}</div>
          </div>
          <el-button
            type="danger"
            icon="el-icon-check"
            :loading="confirming"
            :disabled="currentJob.status !== 2 || currentJob.failCount > 0 || !items.length"
            @click="handleConfirm"
          >确认执行</el-button>
        </div>
        <el-progress :percentage="currentJob.progress || 0" :status="progressStatus(currentJob)" />
        <div class="job-stats">
          <el-tag size="small">总数 {{ currentJob.totalCount || 0 }}</el-tag>
          <el-tag size="small" type="success">可执行 {{ currentJob.successCount || 0 }}</el-tag>
          <el-tag size="small" type="danger">异常 {{ currentJob.failCount || 0 }}</el-tag>
          <el-alert v-if="currentJob.errorMsg" :title="currentJob.errorMsg" type="warning" show-icon :closable="false" />
        </div>
      </div>
    </el-card>

    <el-row :gutter="16">
      <el-col :xs="24" :lg="7">
        <el-card shadow="never" class="batch-card">
          <div slot="header" class="card-head">
            <span class="title">最近任务</span>
          </div>
          <el-table v-loading="jobLoading" :data="jobList" size="mini" height="420" @row-click="selectJob">
            <el-table-column label="任务号" prop="jobNo" min-width="150" show-overflow-tooltip />
            <el-table-column label="来源" width="72">
              <template slot-scope="scope">{{ sourceLabel(scope.row.sourceType) }}</template>
            </el-table-column>
            <el-table-column label="状态" width="86">
              <template slot-scope="scope">
                <el-tag :type="statusType(scope.row.status)" size="mini">{{ statusLabel(scope.row.status) }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="进度" prop="progress" width="70" align="right" />
          </el-table>
        </el-card>
      </el-col>

      <el-col :xs="24" :lg="17">
        <el-card shadow="never" class="batch-card">
          <div slot="header" class="card-head">
            <span class="title">待确认明细</span>
            <span class="subtitle">异常明细需要修改或删除后才能确认执行。</span>
          </div>
          <div class="batch-actions">
            <el-select v-model="batchActionType" size="small" placeholder="批量设置操作类型" clearable>
              <el-option label="新增库区" value="create_area" />
              <el-option label="新增产品" value="create_product" />
              <el-option label="入库登记" value="create_in_record" />
              <el-option label="出库" value="create_out_record" />
              <el-option label="盘库登记" value="create_stock_check" />
            </el-select>
            <el-button size="small" type="primary" plain :loading="batchSaving" :disabled="!canEditItems || !batchActionType || !items.length" @click="applyBatchAction(false)">应用到全部</el-button>
            <el-button size="small" type="primary" plain :loading="batchSaving" :disabled="!canEditItems || !batchActionType || !selectedItems.length" @click="applyBatchAction(true)">应用到已选 {{ selectedItems.length }}</el-button>
          </div>
          <el-table v-loading="itemLoading" :data="items" size="mini" height="520" @selection-change="handleItemSelectionChange">
            <el-table-column type="selection" width="45" />
            <el-table-column label="行" prop="rowNo" width="58" />
            <el-table-column label="操作" width="110">
              <template slot-scope="scope">{{ actionLabel(scope.row.actionType) }}</template>
            </el-table-column>
            <el-table-column label="状态" width="92">
              <template slot-scope="scope">
                <el-tag :type="itemStatusType(scope.row.status)" size="mini">{{ itemStatusLabel(scope.row.status) }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="库区" prop="areaName" width="110" show-overflow-tooltip />
            <el-table-column label="产品" min-width="190" show-overflow-tooltip>
              <template slot-scope="scope">
                <div>{{ scope.row.productName || '-' }}</div>
                <div class="meta">{{ productMeta(scope.row) }}</div>
              </template>
            </el-table-column>
            <el-table-column label="数量" prop="quantity" width="90" align="right" />
            <el-table-column label="人员" prop="operatorName" width="100" show-overflow-tooltip />
            <el-table-column label="提示/错误" min-width="220" show-overflow-tooltip>
              <template slot-scope="scope">
                <span class="error-text" v-if="scope.row.errorMsg">{{ scope.row.errorMsg }}</span>
                <span v-else>{{ scope.row.warningMsg || '-' }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="120" fixed="right">
              <template slot-scope="scope">
                <el-button type="text" size="mini" @click="openEdit(scope.row)">修改</el-button>
                <el-button type="text" size="mini" class="danger-link" @click="removeItem(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>

    <el-dialog title="修改明细" :visible.sync="editOpen" width="620px" append-to-body>
      <el-form ref="editForm" :model="editForm" label-width="90px">
        <el-form-item label="操作类型">
          <el-select v-model="editForm.actionType" placeholder="请选择操作类型" style="width: 100%">
            <el-option label="新增库区" value="create_area" />
            <el-option label="新增产品" value="create_product" />
            <el-option label="入库登记" value="create_in_record" />
            <el-option label="出库" value="create_out_record" />
            <el-option label="盘库登记" value="create_stock_check" />
          </el-select>
        </el-form-item>
        <el-form-item label="库区"><el-input v-model="editForm.areaName" /></el-form-item>
        <el-form-item label="产品名称"><el-input v-model="editForm.productName" /></el-form-item>
        <el-row :gutter="12">
          <el-col :span="12"><el-form-item label="品牌"><el-input v-model="editForm.brand" /></el-form-item></el-col>
          <el-col :span="12"><el-form-item label="类别"><el-input v-model="editForm.category" /></el-form-item></el-col>
        </el-row>
        <el-row :gutter="12">
          <el-col :span="12"><el-form-item label="规格"><el-input v-model="editForm.spec" /></el-form-item></el-col>
          <el-col :span="12"><el-form-item label="单位"><el-input v-model="editForm.unit" /></el-form-item></el-col>
        </el-row>
        <el-row :gutter="12">
          <el-col :span="12"><el-form-item label="数量"><el-input-number v-model="editForm.quantity" :precision="3" :min="0" style="width: 100%" /></el-form-item></el-col>
          <el-col :span="12"><el-form-item label="类型编码"><el-input-number v-model="editForm.typeCode" :min="1" :max="4" style="width: 100%" /></el-form-item></el-col>
        </el-row>
        <el-form-item label="操作人"><el-input v-model="editForm.operatorName" /></el-form-item>
        <el-form-item label="备注"><el-input v-model="editForm.remark" type="textarea" /></el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :loading="savingItem" @click="saveItem">保 存</el-button>
        <el-button @click="editOpen = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listBatchJob, uploadBatchFile, getBatchJob, listBatchItems, updateBatchItem, updateBatchItemAction, deleteBatchItem, confirmBatchJob } from '@/api/warehouse/batchImport'

export default {
  name: 'WmsBatchImport',
  data() {
    return {
      uploading: false,
      confirming: false,
      jobLoading: false,
      itemLoading: false,
      savingItem: false,
      batchSaving: false,
      batchActionType: undefined,
      jobList: [],
      currentJob: null,
      items: [],
      selectedItems: [],
      pollTimer: null,
      editOpen: false,
      editForm: {}
    }
  },
  created() {
    this.loadJobs()
  },
  beforeDestroy() {
    this.stopPolling()
  },
  methods: {
    handleUpload(option) {
      this.uploading = true
      uploadBatchFile(option.file).then(res => {
        this.currentJob = res.data
        this.items = []
        this.$modal.msgSuccess('上传成功，正在后台解析，请留意进度')
        this.startPolling(res.data.id)
        this.loadJobs()
      }).finally(() => {
        this.uploading = false
      })
    },
    loadJobs() {
      this.jobLoading = true
      listBatchJob({ pageNum: 1, pageSize: 20 }).then(res => {
        this.jobList = res.rows || []
      }).finally(() => {
        this.jobLoading = false
      })
    },
    selectJob(row) {
      this.currentJob = row
      this.loadItems(row.id)
      if ([0, 1, 3].includes(row.status)) {
        this.startPolling(row.id)
      }
    },
    startPolling(jobId) {
      this.stopPolling()
      this.pollTimer = setInterval(() => {
        this.refreshJob(jobId)
      }, 1500)
      this.refreshJob(jobId)
    },
    stopPolling() {
      if (this.pollTimer) {
        clearInterval(this.pollTimer)
        this.pollTimer = null
      }
    },
    refreshJob(jobId) {
      getBatchJob(jobId).then(res => {
        this.currentJob = res.data
        if (this.currentJob && [2, 4, 5, 6].includes(this.currentJob.status)) {
          this.stopPolling()
          this.loadItems(jobId)
          this.loadJobs()
        }
      })
    },
    loadItems(jobId) {
      this.itemLoading = true
      listBatchItems(jobId).then(res => {
        this.items = res.data || []
        this.selectedItems = []
      }).finally(() => {
        this.itemLoading = false
      })
    },
    handleItemSelectionChange(selection) {
      this.selectedItems = selection
    },
    openEdit(row) {
      this.editForm = Object.assign({}, row)
      this.editOpen = true
    },
    saveItem() {
      this.savingItem = true
      updateBatchItem(this.editForm).then(res => {
        this.$modal.msgSuccess('明细已更新')
        this.editOpen = false
        this.loadItems(this.currentJob.id)
        this.refreshJob(this.currentJob.id)
      }).finally(() => {
        this.savingItem = false
      })
    },
    removeItem(row) {
      this.$modal.confirm('确认删除第 ' + row.rowNo + ' 行明细？').then(() => deleteBatchItem(row.id)).then(() => {
        this.$modal.msgSuccess('删除成功')
        this.loadItems(this.currentJob.id)
        this.refreshJob(this.currentJob.id)
      })
    },
    applyBatchAction(onlySelected) {
      const rows = onlySelected ? this.selectedItems : this.items
      if (!rows.length || !this.batchActionType) {
        return
      }
      const label = this.actionLabel(this.batchActionType)
      this.$modal.confirm('确认将' + (onlySelected ? '已选' : '全部') + '明细的操作类型设置为“' + label + '”？').then(() => {
        this.batchSaving = true
        const itemIds = onlySelected ? rows.map(item => item.id) : undefined
        return updateBatchItemAction(this.currentJob.id, { actionType: this.batchActionType, itemIds })
      }).then(() => {
        this.$modal.msgSuccess('批量设置完成')
        this.loadItems(this.currentJob.id)
        this.refreshJob(this.currentJob.id)
      }).finally(() => {
        this.batchSaving = false
      })
    },
    handleConfirm() {
      this.$modal.confirm('确认执行当前批量任务？执行后会真正写入库存业务数据。').then(() => {
        this.confirming = true
        return confirmBatchJob(this.currentJob.id)
      }).then(res => {
        this.currentJob = res.data
        this.$modal.msgSuccess('执行完成')
        this.loadItems(this.currentJob.id)
        this.loadJobs()
      }).finally(() => {
        this.confirming = false
      })
    },
    statusLabel(status) {
      return { 0: '已上传', 1: '解析中', 2: '待确认', 3: '执行中', 4: '完成', 5: '失败', 6: '已取消' }[status] || '-'
    },
    statusType(status) {
      return { 2: 'warning', 4: 'success', 5: 'danger', 6: 'info' }[status] || 'info'
    },
    sourceLabel(sourceType) {
      return { excel: 'Excel', image: '图片', file: '文件' }[sourceType] || sourceType || '-'
    },
    itemStatusLabel(status) {
      return { 1: '可执行', 2: '异常', 3: '已执行', 4: '失败' }[status] || '-'
    },
    itemStatusType(status) {
      return { 1: 'success', 2: 'danger', 3: 'success', 4: 'danger' }[status] || 'info'
    },
    progressStatus(job) {
      if (!job) return undefined
      if (job.status === 4) return 'success'
      if (job.status === 5) return 'exception'
      return undefined
    },
    actionLabel(action) {
      return {
        create_area: '新增库区',
        create_product: '新增产品',
        create_in_record: '入库登记',
        create_out_record: '出库',
        create_stock_check: '盘库登记',
        unknown: '未识别'
      }[action] || action || '-'
    },
    productMeta(row) {
      return [row.brand, row.category, row.spec, row.unit].filter(Boolean).join(' / ')
    }
  },
  computed: {
    canEditItems() {
      return this.currentJob && ![3, 4].includes(this.currentJob.status)
    }
  }
}
</script>

<style scoped lang="scss">
.batch-page {
  background: #f5f7fb;
}
.batch-card {
  margin-bottom: 16px;
}
.card-head {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
}
.title {
  font-weight: 700;
  color: #1f2d3d;
}
.subtitle {
  margin-left: 10px;
  color: #7a8794;
  font-size: 12px;
}
.upload-box {
  max-width: 620px;
}
.job-panel {
  margin-top: 16px;
  padding: 14px;
  border: 1px solid #e6ebf2;
  border-radius: 6px;
  background: #fbfcfe;
}
.job-main {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 16px;
  margin-bottom: 12px;
}
.job-no {
  font-weight: 700;
  color: #1f2d3d;
}
.job-meta,
.meta {
  color: #909399;
  font-size: 12px;
}
.job-stats {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 8px;
  margin-top: 10px;
}
.batch-actions {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 8px;
  margin-bottom: 10px;
}
.error-text,
.danger-link {
  color: #f56c6c;
}
</style>
