<template>
  <div class="record-container">
    <!-- 特殊筛选区，通过currentCoilNo，和enterCoilNo追溯 -->
    <el-form :model="traceParams" inline>
      <el-form-item label="入场卷号">
        <el-input v-model="traceParams.enterCoilNo" placeholder="请输入入场卷号"></el-input>
      </el-form-item>
      <el-form-item label="当前卷号">
        <el-input v-model="traceParams.currentCoilNo" placeholder="请输入当前卷号"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleTraceSearch">追溯查询</el-button>
      </el-form-item>
    </el-form>

    <!-- 常规筛选区, 通过调拨前库区和调拨后库区查询 -->
    <el-form :model="queryParams" inline>
      <el-form-item label="调拨前库区">
        <WarehouseSelect v-model="queryParams.warehouseIdBefore" placeholder="请选择调拨前库区">
        </WarehouseSelect>
      </el-form-item>
      <el-form-item label="调拨后库区">
        <WarehouseSelect v-model="queryParams.warehouseIdAfter" placeholder="请选择调拨后库区">
        </WarehouseSelect>
      </el-form-item>
      <el-form-item label="生效状态">
        <el-select v-model="queryParams.isTransferred" @change="handleRegularSearch">
          <el-option :label="1">已生效</el-option>
          <el-option :label="0">未生效</el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleRegularSearch">查询</el-button>
      </el-form-item>
    </el-form>

    <!-- 调拨表格, 显示调拨记录, 常规筛选作用下生效 -->
    <TransferItemTable :data="transferList" :canEdit="false" v-loading="loading"></TransferItemTable>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="handleRegularSearch" />
    <!-- 弹窗: 展示通过特殊筛选区查询到的钢卷和相关的调拨记录,分组展示 -->
    <el-dialog title="钢卷调拨记录追溯" :visible.sync="dialogVisible" width="80%" v-loading="loading">
      <div v-for="coil in tracedCoils" :key="coil.id" class="coil-group">
        <h3>
          <!-- 更全面的展示钢卷的信息, 例如dataType: 0表示历史卷,1表示当前卷.  createTime, createBy, quantityStatus, actualLength, netWeight, coilNo, enterCoilNo, status: 0未发货,1已发货. -->
          <current-coil-no :currentCoilNo="coil.currentCoilNo"></current-coil-no>
          ({{ coil.enterCoilNo }})
          <span style="margin-left: 20px; font-size: 14px; font-weight: normal;">
            {{ coil.dataType === 1 ? '当前卷' : '历史卷' }} | 
            {{ coil.status === 1 ? '已发货' : '未发货' }}
          </span>
        </h3>
        <el-descriptions :column="4" border style="margin-bottom: 20px;">
          <el-descriptions-item label="创建时间">{{ coil.createTime || '-' }}</el-descriptions-item>
          <el-descriptions-item label="创建人">{{ coil.createBy || '-' }}</el-descriptions-item>
          <el-descriptions-item label="质量状态">{{ coil.qualityStatus || '-' }}</el-descriptions-item>
          <el-descriptions-item label="净重">{{ coil.netWeight || '-' }}</el-descriptions-item>
          <el-descriptions-item label="物料名称">{{ coil.itemName || '-' }}</el-descriptions-item>
          <el-descriptions-item label="规格">{{ coil.specification || '-' }}</el-descriptions-item>
          <el-descriptions-item label="材质">{{ coil.material || '-' }}</el-descriptions-item>
          <el-descriptions-item label="厂家">{{ coil.manufacturer || '-' }}</el-descriptions-item>
        </el-descriptions>
        <TransferItemTable :data="coil.transferRecords" :canEdit="false"></TransferItemTable>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import TransferItemTable from "@/views/wms/move/components/tranferItemTable.vue";
import WarehouseSelect from "@/components/KLPService/WarehouseSelect";
import { listTransferOrderItem } from "@/api/wms/transferOrderItem";
import { listMaterialCoil } from "@/api/wms/coil";

export default {
  components: {
    TransferItemTable,
    WarehouseSelect,
  },
  data() {
    return {
      traceParams: {
        currentCoilNo: '',
        enterCoilNo: '',
      },
      queryParams: {
        warehouseIdBefore: '',
        warehouseIdAfter: '',
        isTransferred: '',
        pageSize: 20,
        pageNum: 1,
      },
      transferList: [],
      tracedCoils: [],
      warehouseList: [],
      loading: false,
      total: 0,
      dialogVisible: false,
    };
  },
  methods: {
    async handleTraceSearch() {
      if (!this.traceParams.currentCoilNo && !this.traceParams.enterCoilNo) {
        this.$message.warning('请输入当前卷号或入库卷号');
        return;
      }
      this.loading = true;
      this.dialogVisible = true;
      try {
        // 查询符合条件的钢卷
        const coilRes = await listMaterialCoil(this.traceParams);
        if (coilRes.rows && coilRes.rows.length > 0) {
          // 遍历钢卷，查询每个钢卷的调拨记录
          const tracedCoilsData = await Promise.all(
            coilRes.rows.map(async (coil) => {
              const transferRes = await listTransferOrderItem({ coilId: coil.coilId });
              return {
                ...coil,
                transferRecords: transferRes.rows || [],
              };
            })
          );
          this.tracedCoils = tracedCoilsData.filter(coil => coil.transferRecords.length > 0);
          
        } else {
          this.$message.info('未找到符合条件的钢卷');
        }
      } catch (error) {
        this.$message.error('查询失败，请重试');
        console.error(error);
      } finally {
        this.loading = false;
      }
    },
    async handleRegularSearch() {
      this.loading = true;
      try {
        const res = await listTransferOrderItem(this.queryParams);
        this.transferList = res.rows || [];
        this.total = res.total || 0;
      } catch (error) {
        this.$message.error('查询失败，请重试');
        console.error(error);
      } finally {
        this.loading = false;
      }
    },
  },
  mounted() {

    this.handleRegularSearch();
  },
};
</script>

<style scoped>
.record-container {
  padding: 20px;
}

.special-filter-card,
.regular-filter-card {
  margin-bottom: 20px;
}

.coil-group {
  margin-bottom: 30px;
}

.coil-group h3 {
  margin-bottom: 15px;
  color: #333;
  font-size: 16px;
  font-weight: bold;
}
</style>