<template>
  <section class="page-grid">
    <section class="panel">
      <div class="page-hero-card operation-chain-hero operation-report-hero">
        <div class="page-hero-copy">
          <p class="eyebrow">小程序工序报工</p>
          <h3>报工数据同步与生产核算</h3>
          <p class="page-hero-subtitle">集中查看小程序回传的工序数量、批次匹配和 ERP 同步结果，辅助生产核算与异常追踪。</p>
        </div>
        <div class="page-hero-actions">
          <span class="panel-tag">扫码上报，ERP 同步核算</span>
        </div>
      </div>

      <div class="operation-filter-ribbon" aria-label="小程序报工日期筛选">
        <span class="operation-filter-default">默认最近15天</span>
        <label class="operation-filter-field">
          <span>开始日期</span>
          <input v-model="reportDateFilters.start_date" type="date" />
        </label>
        <label class="operation-filter-field">
          <span>结束日期</span>
          <input v-model="reportDateFilters.end_date" type="date" />
        </label>
        <button class="ghost-button" type="button" @click="loadReports">刷新</button>
        <button class="primary-button" type="button" :disabled="syncingReports" @click="syncReportsToErp">
          {{ syncingReports ? "同步中..." : "同步到 ERP" }}
        </button>
        <span class="operation-sync-hint">上次同步：{{ lastSyncedAt || "暂无" }}</span>
      </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="reportControls.search.value"
        v-model:sort-key="reportControls.sortKey.value"
        v-model:sort-direction="reportControls.sortDirection.value"
        :sort-options="reportControls.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>
              <th>报废数量</th>
              <th>状态</th>
              <th>ERP同步</th>
              <th>异常原因</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="report in paginatedReports" :key="report.source_item_id" :class="{ 'row-danger': report.abnormal_reason }">
              <td>{{ report.report_no }}</td>
              <td>{{ report.attendance_point_name || "-" }}</td>
              <td>{{ report.report_date }}</td>
              <td>{{ report.employee_name || report.employee_phone }}</td>
              <td>{{ report.product_name }}</td>
              <td>{{ report.device_no || "-" }}</td>
              <td>{{ report.raw_material_batch_no || "-" }}</td>
              <td>{{ report.process_name || "-" }}</td>
              <td>{{ formatQty(report.good_qty) }}</td>
              <td>{{ formatQty(report.erp_scrap_qty) }}</td>
              <td><StatusBadge :value="displayReportStatus(report)" :text="displayReportStatus(report)" /></td>
              <td><StatusBadge :value="report.is_synced_to_erp ? '已同步' : '未匹配'" /></td>
              <td>{{ report.abnormal_reason || report.reject_reason || "-" }}</td>
            </tr>
            <tr v-if="!filteredReports.length">
              <td colspan="13" class="empty-row">暂无小程序报工记录</td>
            </tr>
          </tbody>
        </table>
      </div>
      <PaginationBar v-model:page="reportPage" v-model:page-size="reportPageSize" :total="filteredReports.length" />
    </section>
  </section>
</template>

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

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

const reports = ref([]);
const syncingReports = ref(false);
const lastSyncedAt = ref("");
const feedbackMessage = ref("");
const errorMessage = ref("");
const RECENT_REPORT_DAYS = 15;
const reportDateFilters = reactive(buildDefaultReportDateRange());

const reportControls = useTableControls(reports, {
  searchFields: [
    "report_no",
    "attendance_point_name",
    "employee_phone",
    "employee_name",
    "project_no",
    "product_name",
    "device_no",
    "raw_material_batch_no",
    "process_name",
    (row) => displayReportStatus(row),
    "abnormal_reason"
  ],
  sortOptions: [
    { key: "report_no", label: "小程序报工号" },
    { key: "attendance_point_name", label: "考勤点" },
    { key: "report_date", label: "报工日期" },
    { key: "employee_name", label: "员工" },
    { key: "product_name", label: "产品" },
    { key: "raw_material_batch_no", label: "库存批次号" },
    { key: "good_qty", label: "成品数量" },
    { key: "erp_scrap_qty", label: "报废数量" },
    { key: "status", label: "状态" }
  ],
  defaultSortKey: "report_no",
  defaultSortDirection: "desc"
});
const filteredReports = reportControls.rows;
const {
  page: reportPage,
  pageSize: reportPageSize,
  rows: paginatedReports
} = usePagination(filteredReports);

async function loadReports() {
  feedbackMessage.value = "";
  errorMessage.value = "";
  if (reportDateFilters.start_date && reportDateFilters.end_date && reportDateFilters.start_date > reportDateFilters.end_date) {
    reports.value = [];
    errorMessage.value = "开始日期不能晚于结束日期";
    return;
  }
  try {
    const params = new URLSearchParams({
      limit: "800",
      sync_to_erp: "false"
    });
    if (reportDateFilters.start_date) {
      params.set("start_date", reportDateFilters.start_date);
    }
    if (reportDateFilters.end_date) {
      params.set("end_date", reportDateFilters.end_date);
    }
    reports.value = await fetchResource(`/production/miniapp-operation-reports?${params.toString()}`, []);
    feedbackMessage.value = "小程序报工列表已刷新";
  } catch (error) {
    errorMessage.value = error.message || "读取小程序报工失败";
  }
}

async function loadSyncState() {
  const result = await fetchResource("/production/miniapp-operation-reports/sync-state", {});
  lastSyncedAt.value = result?.last_synced_at || "";
}

async function syncReportsToErp() {
  if (syncingReports.value) {
    return;
  }
  feedbackMessage.value = "";
  errorMessage.value = "";
  syncingReports.value = true;
  try {
    const result = await postResource("/production/miniapp-operation-reports/sync", {});
    lastSyncedAt.value = result.last_synced_at || result.sync_to || "";
    const successMessage = [
      `同步完成：共 ${result.total || 0} 条`,
      `成功 ${result.synced || 0} 条`,
      `跳过 ${result.skipped || 0} 条`,
      `失败 ${result.failed || 0} 条`,
      `同步范围：${result.sync_from || "首次同步"} 至 ${result.sync_to || "-"}`
    ].join("，");
    await loadReports();
    feedbackMessage.value = successMessage;
  } catch (error) {
    errorMessage.value = error.message || "同步小程序报工到 ERP 失败，上次同步成功时间未更新，请稍后重试";
  } finally {
    syncingReports.value = false;
  }
}

function formatDateInput(date) {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  return `${year}-${month}-${day}`;
}

function buildDefaultReportDateRange() {
  const end = new Date();
  const start = new Date(end);
  start.setDate(end.getDate() - RECENT_REPORT_DAYS + 1);
  return {
    start_date: formatDateInput(start),
    end_date: formatDateInput(end)
  };
}

function displayReportStatus(report) {
  return formatStatusLabel(report?.status_name || report?.status);
}

onMounted(async () => {
  await Promise.all([loadSyncState(), loadReports()]);
});
</script>
