<template>
  <div class="backward1-container">
    <el-card class="query-card" shadow="never">
      <el-form :model="queryParams" :inline="true" label-width="80px">
        <el-form-item label="条码类型">
          <el-select v-model="queryParams.barcodeType" placeholder="请选择" style="width: 150px" @change="handleBarcodeTypeChange">
            <el-option label="架子号" value="1" />
            <el-option label="半制品卡号" value="2" />
            <el-option label="成型号" value="3" />
            <el-option label="硫化号" value="4" />
          </el-select>
        </el-form-item>
        <el-form-item label="条码号">
          <el-input v-model="queryParams.barcodeNo" placeholder="请输入条码号" clearable style="width: 220px" />
        </el-form-item>
        <el-form-item label="开始时间">
          <el-date-picker
            v-model="queryParams.startTime"
            type="datetime"
            placeholder="开始时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="结束时间">
          <el-date-picker
            v-model="queryParams.endTime"
            type="datetime"
            placeholder="结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="班次">
          <el-select v-model="queryParams.shift" placeholder="全部" clearable style="width: 120px">
            <el-option label="早" value="早" />
            <el-option label="中" value="中" />
            <el-option label="夜" value="夜" />
          </el-select>
        </el-form-item>
        <el-form-item label="班组">
          <el-select v-model="queryParams.team" placeholder="全部" clearable style="width: 120px">
            <el-option label="甲班" value="甲班" />
            <el-option label="乙班" value="乙班" />
            <el-option label="丙班" value="丙班" />
          </el-select>
        </el-form-item>
        <el-form-item label="机台">
          <el-input v-model="queryParams.machine" placeholder="请输入机台" clearable style="width: 150px" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">查询</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="table-card" shadow="never">
      <div class="table-scroll">
        <el-table
          :data="tableData"
          border
          stripe
          :fit="false"
          :scrollbar-always-on="true"
          height="520"
          @row-click="handleRowClick"
          :row-style="{ cursor: 'pointer' }"
        >
          <el-table-column type="index" label="序号" width="60" align="center" />

          <template v-if="queryParams.barcodeType === '1'">
            <el-table-column prop="vulcanizationNo" label="硫化号" min-width="150" align="center" show-overflow-tooltip />
            <el-table-column prop="planDate" label="计划日期" min-width="120" align="center" show-overflow-tooltip />
            <el-table-column prop="shift" label="班次" min-width="80" align="center" />
            <el-table-column prop="team" label="班组" min-width="90" align="center" />
            <el-table-column prop="machineNo" label="机台号" min-width="110" align="center" show-overflow-tooltip />
            <el-table-column prop="materialSpec" label="物料规格" min-width="260" align="center" show-overflow-tooltip />
          </template>

          <template v-else-if="queryParams.barcodeType === '2'">
            <el-table-column prop="cardNo" label="流转卡号" min-width="180" align="center" show-overflow-tooltip />
            <el-table-column prop="toolingNo" label="工装号" min-width="180" align="center" show-overflow-tooltip />
            <el-table-column prop="shift" label="班次" min-width="80" align="center" />
            <el-table-column prop="team" label="班组" min-width="90" align="center" />
            <el-table-column prop="recorder" label="记录人" min-width="90" align="center" />
            <el-table-column prop="startTime" label="开始时间" min-width="180" align="center" show-overflow-tooltip />
            <el-table-column prop="endTime" label="结束时间" min-width="180" align="center" show-overflow-tooltip />
            <el-table-column prop="machineNo" label="机台号" min-width="120" align="center" show-overflow-tooltip />
            <el-table-column prop="qty" label="数量" min-width="90" align="right" />
            <el-table-column prop="leftQty" label="剩余数量" min-width="100" align="right" />
          </template>

          <template v-else-if="queryParams.barcodeType === '3'">
            <el-table-column prop="greenTyreNo" label="成型号" min-width="170" align="center" show-overflow-tooltip />
            <el-table-column prop="materialSpec" label="物料规格" min-width="260" align="center" show-overflow-tooltip />
            <el-table-column prop="shift" label="班次" min-width="80" align="center" />
            <el-table-column prop="team" label="班组" min-width="90" align="center" />
            <el-table-column prop="recorder" label="记录人" min-width="90" align="center" />
            <el-table-column prop="startTime" label="开始时间" min-width="180" align="center" show-overflow-tooltip />
            <el-table-column prop="endTime" label="结束时间" min-width="180" align="center" show-overflow-tooltip />
            <el-table-column prop="machineNo" label="机台号" min-width="120" align="center" show-overflow-tooltip />
          </template>

          <template v-else>
            <el-table-column prop="vulcanizationNo" label="硫化号" min-width="150" align="center" show-overflow-tooltip />
            <el-table-column prop="moldingNo" label="成型号" min-width="150" align="center" show-overflow-tooltip />
            <el-table-column prop="materialSpec" label="物料规格" min-width="260" align="center" show-overflow-tooltip />
            <el-table-column prop="shift" label="班次" min-width="80" align="center" />
            <el-table-column prop="team" label="班组" min-width="90" align="center" />
            <el-table-column prop="startTime" label="开始时间" min-width="180" align="center" show-overflow-tooltip />
            <el-table-column prop="endTime" label="结束时间" min-width="180" align="center" show-overflow-tooltip />
            <el-table-column prop="machineNo" label="机台号" min-width="120" align="center" show-overflow-tooltip />
            <el-table-column prop="moldPosition" label="左右模" min-width="90" align="center" />
          </template>
        </el-table>
      </div>

      <el-pagination
        v-model:current-page="queryParams.pageNum"
        v-model:page-size="queryParams.pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        style="margin-top: 16px; text-align: right"
      />
    </el-card>
  </div>
</template>

<script setup lang="ts" name="MixTraceBackward1">
import { onMounted, reactive, ref } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import backwardData from './data/backward1.json';
import backwardDetailData from './data/backward2.json';

type BarcodeType = '1' | '2' | '3' | '4';

interface BackwardRow {
  id: string;
  detailId?: string;
  barcodeType: BarcodeType;
  vulcanizationNo?: string;
  cardNo?: string;
  greenTyreNo?: string;
  planDate?: string;
  startTime?: string;
  endTime?: string;
  shift?: string;
  team?: string;
  machineNo?: string;
}

const router = useRouter();
const detailMap = (backwardDetailData as any).detailMap || {};

const queryParams = reactive({
  startTime: '',
  endTime: '',
  shift: '',
  barcodeType: '4' as BarcodeType,
  barcodeNo: '',
  team: '',
  machine: '',
  pageNum: 1,
  pageSize: 10
});

const tableData = ref<BackwardRow[]>([]);
const total = ref(0);

const getDataByType = (type: BarcodeType): BackwardRow[] => {
  const data = backwardData as any;
  if (type === '1') return data.shelfData || [];
  if (type === '2') return data.semiCardData || [];
  if (type === '3') return data.moldingData || [];
  return data.curingData || [];
};

const getRowBarcode = (row: BackwardRow): string => {
  return String(row.vulcanizationNo || row.cardNo || row.greenTyreNo || '');
};

const toTimestamp = (timeStr?: string): number | null => {
  if (!timeStr) return null;
  const ms = Date.parse(timeStr.replace(/\//g, '-'));
  return Number.isNaN(ms) ? null : ms;
};

const getRowTime = (row: BackwardRow): number | null => {
  if (row.startTime) return toTimestamp(row.startTime);
  if (row.planDate) return toTimestamp(`${row.planDate} 00:00:00`);
  return null;
};

const refreshTable = () => {
  const all = getDataByType(queryParams.barcodeType);
  const barcodeKeyword = queryParams.barcodeNo.trim().toLowerCase();
  const machineKeyword = queryParams.machine.trim().toLowerCase();
  const startTs = toTimestamp(queryParams.startTime);
  const endTs = toTimestamp(queryParams.endTime);

  const filtered = all.filter((row) => {
    const rowBarcode = getRowBarcode(row).toLowerCase();
    const machine = String(row.machineNo || '').toLowerCase();
    const rowTs = getRowTime(row);

    if (barcodeKeyword && !rowBarcode.includes(barcodeKeyword)) return false;
    if (queryParams.shift && row.shift !== queryParams.shift) return false;
    if (queryParams.team && row.team !== queryParams.team) return false;
    if (machineKeyword && !machine.includes(machineKeyword)) return false;
    if (startTs !== null && rowTs !== null && rowTs < startTs) return false;
    if (endTs !== null && rowTs !== null && rowTs > endTs) return false;
    return true;
  });

  total.value = filtered.length;
  const start = (queryParams.pageNum - 1) * queryParams.pageSize;
  tableData.value = filtered.slice(start, start + queryParams.pageSize);
};

const handleQuery = () => {
  queryParams.pageNum = 1;
  refreshTable();
};

const handleBarcodeTypeChange = () => {
  handleQuery();
};

const resetQuery = () => {
  queryParams.startTime = '';
  queryParams.endTime = '';
  queryParams.shift = '';
  queryParams.barcodeType = '4';
  queryParams.barcodeNo = '';
  queryParams.team = '';
  queryParams.machine = '';
  queryParams.pageNum = 1;
  queryParams.pageSize = 10;
  refreshTable();
};

const handleSizeChange = () => {
  queryParams.pageNum = 1;
  refreshTable();
};

const handleCurrentChange = () => {
  refreshTable();
};

const handleRowClick = (row: BackwardRow) => {
  const detailId = String(row.detailId || row.id || '');
  if (!detailId) {
    ElMessage.error('当前行缺少 detailId，无法跳转详情');
    return;
  }

  const detail = detailMap[detailId];
  if (!detail) {
    ElMessage.error(`未找到详情数据: ${detailId}`);
    return;
  }

  const rowType = String(row.barcodeType || queryParams.barcodeType || '4');
  const detailType = String(detail.barcodeType || rowType || '4');
  if (rowType !== detailType) {
    ElMessage.warning(`条码类型已按详情修正: ${rowType} -> ${detailType}`);
  }

  router.push({
    path: '/mes/mixTrace/show/backward2',
    query: {
      id: detailId,
      barcodeType: detailType
    }
  });
};

onMounted(() => {
  refreshTable();
});
</script>

<style scoped lang="scss">
.backward1-container {
  padding: 20px;

  .query-card {
    margin-bottom: 16px;
    :deep(.el-card__body) {
      padding: 16px;
    }
  }

  .table-card {
    :deep(.el-card__body) {
      padding: 16px;
    }
  }

  .table-scroll {
    width: 100%;
    min-width: 0;
  }

  :deep(.el-table__body td) {
    padding: 8px 0;
  }
}
</style>
