<template>
  <section class="page-grid">
    <section class="panel">
      <div class="panel-header">
        <div>
          <p class="eyebrow">生产报废</p>
          <h3>最近生产报废记录</h3>
        </div>
        <div class="workflow-inline-actions">
          <span class="panel-tag">异常闭环</span>
          <button class="primary-button" type="button" @click="openCreateDrawer">新增处置记录</button>
        </div>
      </div>

      <div v-if="feedbackMessage" class="feedback-banner">{{ feedbackMessage }}</div>
      <div v-if="errorMessage" class="feedback-banner error-banner">{{ errorMessage }}</div>

      <TableControls
        v-model:search="recordControls.search.value"
        v-model:sort-key="recordControls.sortKey.value"
        v-model:sort-direction="recordControls.sortDirection.value"
        :sort-options="recordControls.sortOptions"
        placeholder="搜索报废单号、库存批次号、工序、产品、状态"
      />

      <div class="table-wrap">
        <table class="data-table compact-table">
          <thead>
            <tr>
              <th>处置单号</th>
              <th>库存批次号</th>
              <th>工序</th>
              <th>产品</th>
              <th>处置数量</th>
              <th>处置重量</th>
              <th>处置方式</th>
              <th>成本</th>
              <th>状态</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="record in paginatedRecords" :key="record.scrap_record_id" :class="{ 'row-danger': record.disposal_type === 'SCRAP' }">
              <td>{{ record.scrap_no }}</td>
              <td>{{ record.work_order_no }}</td>
              <td>{{ record.operation_name }}</td>
              <td>{{ record.item_name }}</td>
              <td>{{ formatQty(record.scrap_qty) }}</td>
              <td>{{ formatWeight(record.scrap_weight_kg) }}</td>
              <td>{{ formatDisposalTypeLabel(record.disposal_type) }}</td>
              <td>¥{{ formatAmount(record.scrap_cost_amount) }}</td>
              <td>{{ formatStatusLabel(record.status) }}</td>
            </tr>
            <tr v-if="!filteredRecords.length">
              <td colspan="9" class="empty-row">暂无处置记录</td>
            </tr>
          </tbody>
        </table>
      </div>
      <PaginationBar v-model:page="recordPage" v-model:page-size="recordPageSize" :total="filteredRecords.length" />
    </section>

    <FormDrawer
      :open="drawerOpen"
      eyebrow="生产报废"
      title="新增生产报废记录"
      description="生产过程中只登记报废。客户退货产生的返工或报废，请到发货概览模块处理。"
      tag="报废闭环"
      wide
      @close="drawerOpen = false"
    >
      <form class="stack-form" @submit.prevent="submitRecord">
        <label class="form-field">
          <span>来源报工</span>
          <select v-model.number="form.source_item_id" @change="applyReport" required>
            <option disabled value="">请选择报工记录</option>
            <option v-for="report in unprocessedReports" :key="`open-${report.source_item_id}`" :value="report.source_item_id">
              {{ formatReportLabel(report) }}
            </option>
            <option v-if="processedReports.length" disabled value="">──────── 已处理记录 ────────</option>
            <option
              v-for="report in processedReports"
              :key="`done-${report.source_item_id}`"
              :value="report.source_item_id"
              class="muted-option"
            >
              {{ formatReportLabel(report, true) }}
            </option>
          </select>
        </label>

        <div class="double-field">
          <label class="form-field">
            <span>库存批次号</span>
            <select v-model.number="form.work_order_id" required>
              <option disabled value="">请选择库存批次号</option>
              <option v-for="workOrder in workOrders" :key="workOrder.work_order_id" :value="workOrder.work_order_id">
                {{ workOrder.work_order_no }} · {{ workOrder.product_name }}
              </option>
            </select>
          </label>
          <label class="form-field">
            <span>工序</span>
            <select v-model.number="form.work_order_operation_id" required>
              <option disabled value="">请选择工序</option>
              <option v-for="operation in currentOperations" :key="operation.work_order_operation_id" :value="operation.work_order_operation_id">
                {{ operation.seq_no }} · {{ operation.operation_name }}
              </option>
            </select>
          </label>
        </div>

        <div class="double-field">
          <label class="form-field">
            <span>产品</span>
            <select v-model.number="form.item_id" required @change="hydrateDispositionValues">
              <option disabled value="">请选择产品</option>
              <option v-for="product in products" :key="product.item_id" :value="product.item_id">
                {{ formatProductLabel(product) }}
              </option>
            </select>
          </label>
        </div>

        <div class="double-field">
          <label class="form-field">
            <span>报废数量</span>
            <input v-model.number="form.scrap_qty" type="number" min="0" step="1" />
          </label>
          <label class="form-field">
            <span>报废重量(kg)</span>
            <input v-model.number="form.scrap_weight_kg" type="number" min="0" step="0.001" />
          </label>
        </div>

        <div class="double-field">
          <label class="form-field">
            <span>可售废料重量(kg)</span>
            <input v-model.number="form.saleable_scrap_weight_kg" type="number" min="0" step="0.001" />
          </label>
          <label class="form-field">
            <span>废料成本(自动计算)</span>
            <input v-model.number="form.scrap_cost_amount" type="number" min="0" step="0.01" readonly />
          </label>
        </div>

        <label class="form-field">
          <span>原因说明</span>
          <textarea v-model.trim="form.scrap_reason" rows="3"></textarea>
        </label>

        <button class="primary-button" type="submit" :disabled="submitting">
          {{ submitting ? "提交中..." : "登记处置" }}
        </button>
      </form>
    </FormDrawer>
  </section>
</template>

<script setup>
import { computed, onMounted, reactive, ref } from "vue";

import FormDrawer from "../components/FormDrawer.vue";
import PaginationBar from "../components/PaginationBar.vue";
import TableControls from "../components/TableControls.vue";
import { fetchResource, postResource } from "../services/api";
import { formatDisposalTypeLabel, formatProductLabel, formatStatusLabel } from "../utils/dictionaries";
import { formatAmount, formatQty, formatWeight } from "../utils/formatters";
import { usePagination } from "../utils/pagination";
import { useTableControls } from "../utils/tableControls";

const reports = ref([]);
const workOrders = ref([]);
const operations = ref([]);
const products = ref([]);
const records = ref([]);
const feedbackMessage = ref("");
const errorMessage = ref("");
const submitting = ref(false);
const drawerOpen = ref(false);

const form = reactive(buildEmptyForm());

const eligibleReports = computed(() =>
  reports.value.filter((item) => Number(item.erp_scrap_qty || item.scrap_qty || 0) > 0)
);
const activeRecordMap = computed(() => {
  const map = new Map();
  records.value
    .filter((item) => item.status === "CONFIRMED")
    .forEach((item) => {
      if (!map.has(Number(item.report_id))) {
        map.set(Number(item.report_id), item);
      }
    });
  return map;
});
const unprocessedReports = computed(() =>
  eligibleReports.value.filter((item) => !item.erp_report_id || !activeRecordMap.value.has(Number(item.erp_report_id)))
);
const processedReports = computed(() =>
  eligibleReports.value.filter((item) => item.erp_report_id && activeRecordMap.value.has(Number(item.erp_report_id)))
);
const currentOperations = computed(() =>
  operations.value.filter((item) => item.work_order_id === Number(form.work_order_id))
);
const recordControls = useTableControls(records, {
  searchFields: ["scrap_no", "work_order_no", "operation_name", "item_name", "disposal_type", "status", "scrap_reason"],
  sortOptions: [
    { key: "scrap_no", label: "处置单号" },
    { key: "work_order_no", label: "库存批次号" },
    { key: "operation_name", label: "工序" },
    { key: "item_name", label: "产品" },
    { key: "scrap_qty", label: "处置数量" },
    { key: "scrap_weight_kg", label: "处置重量" },
    { key: "disposal_type", label: "方式" },
    { key: "status", label: "状态" }
  ],
  defaultSortKey: "scrap_no",
  defaultSortDirection: "desc"
});
const filteredRecords = recordControls.rows;
const {
  page: recordPage,
  pageSize: recordPageSize,
  rows: paginatedRecords
} = usePagination(filteredRecords);

function buildEmptyForm() {
  return {
    source_item_id: "",
    work_order_id: "",
    work_order_operation_id: "",
    item_id: "",
    scrap_qty: 0,
    scrap_weight_kg: 0,
    disposal_type: "SCRAP",
    saleable_scrap_weight_kg: 0,
    scrap_cost_amount: 0,
    scrap_reason: ""
  };
}

function selectedReport() {
  return reports.value.find((item) => item.source_item_id === Number(form.source_item_id)) || null;
}

function selectedProduct() {
  return products.value.find((item) => item.item_id === Number(form.item_id)) || null;
}

function formatReportLabel(report, processed = false) {
  const activeRecord = report.erp_report_id ? activeRecordMap.value.get(Number(report.erp_report_id)) : null;
  const pointText = report.attendance_point_name ? `${report.attendance_point_name} · ` : "";
  const baseLabel = `${pointText}${report.report_no} · ${report.raw_material_batch_no || report.work_order_no || "未匹配库存批次"} · ${report.process_name || report.operation_name || "-"}`;
  if (!processed || !activeRecord) {
    return baseLabel;
  }
  return `${baseLabel} · 当前${formatDisposalTypeLabel(activeRecord.disposal_type)}`;
}

function hydrateDispositionValues() {
  const report = selectedReport();
  const product = selectedProduct();
  if (!report || !product) {
    return;
  }
  const sourceQty = Number(report.erp_scrap_qty || report.scrap_qty || 0);
  const sourceWeight = sourceQty * Number(product.unit_weight_kg || 0);
  form.scrap_qty = sourceQty;
  form.scrap_weight_kg = Number(sourceWeight.toFixed(3));
  form.saleable_scrap_weight_kg = Number(sourceWeight.toFixed(3));
  form.scrap_cost_amount = 0;
}

function applyExistingRecord(record) {
  if (!record) {
    hydrateDispositionValues();
    return;
  }
  form.disposal_type = "SCRAP";
  form.scrap_qty = Number(record.scrap_qty || 0);
  form.scrap_weight_kg = Number(record.scrap_weight_kg || 0);
  form.saleable_scrap_weight_kg = Number(record.saleable_scrap_weight_kg || 0);
  form.scrap_cost_amount = Number(record.scrap_cost_amount || 0);
  form.scrap_reason = record.scrap_reason || "";
}

function applyReport() {
  const report = selectedReport();
  if (!report) {
    return;
  }
  form.work_order_id = report.work_order_id || "";
  form.work_order_operation_id = report.work_order_operation_id || "";
  const workOrder = workOrders.value.find((item) => item.work_order_id === report.work_order_id);
  form.item_id = workOrder?.product_item_id || "";
  form.scrap_reason = report.scrap_reason || report.abnormal_reason || "";
  applyExistingRecord(report.erp_report_id ? activeRecordMap.value.get(Number(report.erp_report_id)) : null);
}

function resetForm() {
  Object.assign(form, buildEmptyForm());
}

function openCreateDrawer() {
  resetForm();
  feedbackMessage.value = "";
  errorMessage.value = "";
  drawerOpen.value = true;
}

async function loadAll() {
  const [reportRows, workOrderRows, operationRows, productRows, recordRows] = await Promise.all([
    fetchResource("/production/miniapp-operation-reports?limit=800&sync_to_erp=true", []),
    fetchResource("/production/work-orders", []),
    fetchResource("/production/work-order-operations", []),
    fetchResource("/master-data/products", []),
    fetchResource("/production/scrap-records", [])
  ]);
  reports.value = reportRows;
  workOrders.value = workOrderRows;
  operations.value = operationRows;
  products.value = productRows;
  records.value = recordRows;
}

async function submitRecord() {
  feedbackMessage.value = "";
  errorMessage.value = "";
  submitting.value = true;
  try {
    const result = await postResource("/production/miniapp-scrap-records", {
      source_item_id: Number(form.source_item_id),
      scrap_qty: Number(form.scrap_qty || 0),
      scrap_weight_kg: Number(form.scrap_weight_kg || 0),
      saleable_scrap_weight_kg: Number(form.saleable_scrap_weight_kg || 0),
      scrap_cost_amount: Number(form.scrap_cost_amount || 0),
      scrap_reason: form.scrap_reason || null
    });
    feedbackMessage.value = `处置单 ${result.scrap_no} 已登记`;
    drawerOpen.value = false;
    await loadAll();
    resetForm();
  } catch (error) {
    errorMessage.value = error.message || "处置登记失败";
  } finally {
    submitting.value = false;
  }
}

onMounted(async () => {
  await loadAll();
});
</script>
