<template>
  <div class="app-container acid-op-page">
    <el-row :gutter="16">

      <!-- ── 左侧：合卷表单 ── -->
      <el-col :span="15">
        <div class="op-card">
          <div class="op-header">
            <span class="op-title">合卷操作</span>
            <el-tag size="mini" type="info" style="margin-left:8px">actionType = 200</el-tag>
          </div>

          <el-form ref="form" :model="form" :rules="rules" label-width="110px" size="small">

            <!-- 源卷列表（动态） -->
            <div class="sub-section-label">源卷列表</div>
            <div v-for="(item, idx) in form.sourceCoils" :key="idx" class="source-row">
              <el-form-item
                :label="'源卷 ' + (idx + 1)"
                :prop="'sourceCoils.' + idx + '.enterCoilNo'"
                :rules="[{ required: true, message: '请输入源卷号', trigger: 'blur' }]"
                style="margin-bottom:8px"
              >
                <el-input v-model="item.enterCoilNo" :placeholder="'入场钢卷号 ' + (idx + 1)"
                  clearable style="width:calc(100% - 36px)"
                  @keyup.enter.native="onSourceCoilInput(item)"
                  @blur="onSourceCoilInput(item)" />
                <el-button icon="el-icon-minus" size="mini" type="danger" circle
                  style="margin-left:6px" :disabled="form.sourceCoils.length <= 1"
                  @click="removeSourceCoil(idx)" />
              </el-form-item>
            </div>
            <el-button size="mini" type="primary" plain icon="el-icon-plus"
              style="margin-left:110px;margin-bottom:12px" @click="addSourceCoil">
              添加源卷
            </el-button>

            <el-divider content-position="left" style="margin:4px 0 12px">合卷结果</el-divider>

            <el-row :gutter="16">
              <el-col :span="12">
                <el-form-item label="合卷后卷号" prop="targetCoilNo">
                  <el-input v-model="form.targetCoilNo" placeholder="请输入合卷后钢卷号" clearable />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="合卷后重量(t)" prop="mergedWeight">
                  <el-input-number v-model="form.mergedWeight" :precision="3" :min="0"
                    :controls="false" style="width:100%" placeholder="—" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="16">
              <el-col :span="12">
                <el-form-item label="出口厚度(mm)" prop="exitThickness">
                  <el-input-number v-model="form.exitThickness" :precision="3" :min="0"
                    :controls="false" style="width:100%" placeholder="—" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="出口宽度(mm)" prop="exitWidth">
                  <el-input-number v-model="form.exitWidth" :precision="1" :min="0"
                    :controls="false" style="width:100%" placeholder="—" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="16">
              <el-col :span="12">
                <el-form-item label="班组" prop="team">
                  <el-select v-model="form.team" placeholder="请选择" style="width:100%" clearable>
                    <el-option label="甲班" value="甲" />
                    <el-option label="乙班" value="乙" />
                    <el-option label="丙班" value="丙" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="备注">
                  <el-input v-model="form.remark" placeholder="选填" clearable />
                </el-form-item>
              </el-col>
            </el-row>

            <div style="text-align:right;padding-top:4px">
              <el-button @click="resetForm">重置</el-button>
              <el-button type="primary" :loading="submitting" @click="submitForm">确认合卷</el-button>
            </div>
          </el-form>
        </div>

        <!-- 历史记录 -->
        <div class="op-card" style="margin-top:12px">
          <div class="op-header">
            <span class="op-title">最近合卷记录</span>
            <el-button size="mini" icon="el-icon-refresh" style="margin-left:auto" @click="loadHistory">刷新</el-button>
          </div>
          <el-table v-loading="historyLoading" :data="historyList" size="mini" border style="width:100%">
            <el-table-column prop="enterCoilNo"   label="源卷号"     min-width="120" show-overflow-tooltip />
            <el-table-column prop="currentCoilNo" label="合卷后卷号" min-width="120" show-overflow-tooltip />
            <el-table-column prop="exitThickness"  label="出口厚(mm)" width="90" align="right" />
            <el-table-column prop="exitWidth"      label="出口宽(mm)" width="90" align="right" />
            <el-table-column prop="netWeight"      label="重量(t)"    width="80" align="right" />
            <el-table-column prop="team"           label="班组"       width="60" align="center" />
            <el-table-column prop="createTime"     label="录入时间"   width="150" />
          </el-table>
          <pagination v-show="historyTotal > 0" :total="historyTotal"
            :page.sync="historyQuery.pageNum" :limit.sync="historyQuery.pageSize"
            @pagination="loadHistory" style="margin-top:6px" />
        </div>
      </el-col>

      <!-- ── 右侧：L2 匹配面板（以第一个源卷为锚点） ── -->
      <el-col :span="9">
        <l2-match-panel :hot-coil-id="l2HotCoilId" @fill="applyL2Fill" />
      </el-col>

    </el-row>
  </div>
</template>

<script>
import { addCoilWarehouseOperationLog, listCoilWarehouseOperationLog } from '@/api/wms/coilWarehouseOperationLog'
import L2MatchPanel from '../panels/L2MatchPanel.vue'

export default {
  name: 'AcidMerge',
  components: { L2MatchPanel },
  data() {
    return {
      form: this.defaultForm(),
      rules: {
        targetCoilNo: [{ required: true, message: '合卷后卷号不能为空', trigger: 'blur' }],
      },
      submitting: false,
      l2HotCoilId: '',

      historyLoading: false,
      historyList: [],
      historyTotal: 0,
      historyQuery: { pageNum: 1, pageSize: 10, actionType: 200 },
    }
  },
  created() {
    this.loadHistory()
  },
  methods: {
    defaultForm() {
      return {
        sourceCoils:   [{ enterCoilNo: '' }],
        targetCoilNo:  '',
        mergedWeight:  undefined,
        exitThickness: undefined,
        exitWidth:     undefined,
        team:          undefined,
        remark:        '',
        actionType:    200,
      }
    },

    addSourceCoil() {
      this.form.sourceCoils.push({ enterCoilNo: '' })
    },
    removeSourceCoil(idx) {
      this.form.sourceCoils.splice(idx, 1)
      // 重新推算锚点
      this.l2HotCoilId = (this.form.sourceCoils[0]?.enterCoilNo || '').trim()
    },
    onSourceCoilInput(item) {
      // 以列表第一个源卷的卷号作为 L2 查询锚点
      const first = (this.form.sourceCoils[0]?.enterCoilNo || '').trim()
      this.l2HotCoilId = first
    },

    applyL2Fill(data) {
      if (data.exit_thick   != null) this.form.exitThickness = parseFloat(data.exit_thick)
      if (data.exit_width   != null) this.form.exitWidth     = parseFloat(data.exit_width)
      if (data.entry_weight != null) this.form.mergedWeight  = parseFloat(data.entry_weight)
      this.$message.success('L2 数据已写入表单')
    },

    submitForm() {
      this.$refs.form.validate(valid => {
        if (!valid) return
        this.submitting = true
        // 将源卷列表序列化放入 remark 或 enterCoilNo（多对一合卷用逗号分隔）
        const sourceNos = this.form.sourceCoils.map(s => s.enterCoilNo).filter(Boolean).join(',')
        const payload = {
          enterCoilNo:   sourceNos,
          currentCoilNo: this.form.targetCoilNo,
          exitThickness: this.form.exitThickness,
          exitWidth:     this.form.exitWidth,
          netWeight:     this.form.mergedWeight,
          team:          this.form.team,
          remark:        this.form.remark,
          actionType:    200,
        }
        addCoilWarehouseOperationLog(payload).then(() => {
          this.$modal.msgSuccess('合卷操作已记录')
          this.resetForm()
          this.loadHistory()
        }).finally(() => { this.submitting = false })
      })
    },

    resetForm() {
      this.form = this.defaultForm()
      this.l2HotCoilId = ''
      this.$nextTick(() => { this.$refs.form && this.$refs.form.clearValidate() })
    },

    loadHistory() {
      this.historyLoading = true
      listCoilWarehouseOperationLog(this.historyQuery).then(res => {
        this.historyList  = res.rows  || []
        this.historyTotal = res.total || 0
      }).finally(() => { this.historyLoading = false })
    },
  }
}
</script>

<style scoped>
.acid-op-page { background: #f5f7fa; }
.op-card {
  background: #fff;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 16px;
}
.op-header {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 10px;
  border-bottom: 2px solid #67c23a;
}
.op-title { font-size: 15px; font-weight: 600; color: #303133; }
.sub-section-label {
  font-size: 12px;
  color: #909399;
  margin: 0 0 8px 110px;
  font-weight: 500;
}
.source-row { position: relative; }
</style>
