<template>
  <section class="page-grid">
    <section class="panel panel-hero master-compact-hero">
      <div class="hero-copy">
        <p class="eyebrow">工艺路线管理</p>
        <span
          class="title-with-help"
          title="参考节拍用于和实际报工节拍对比，人工成本、设备成本、委外成本由后续报工与成本核算自动归集。"
        >
          <h3>按编码维护多版本工序链，默认版本驱动工单与报工</h3>
        </span>
      </div>
    </section>

    <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="routeControls.search.value"
          v-model:sort-key="routeControls.sortKey.value"
          v-model:sort-direction="routeControls.sortDirection.value"
          :sort-options="routeControls.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>
              </tr>
            </thead>
            <tbody>
              <tr
                v-for="route in paginatedRoutes"
                :key="route.route_code"
                :class="{ 'row-selected': selectedRouteId === Number(versionSelections[route.route_code] || route.route_id) }"
              >
                <td>
                  <button class="link-button" type="button" @click="openDetailDrawer(route)">
                    {{ route.route_code }}
                  </button>
                </td>
                <td>{{ formatProductLabel(route) }}</td>
                <td>
                  <select v-model.number="versionSelections[route.route_code]" @change="applyRouteVersion(route.route_code)">
                    <option v-for="option in route.version_options" :key="option.route_id" :value="option.route_id">
                      {{ option.version_no }}
                    </option>
                  </select>
                </td>
                <td>{{ route.is_default ? "是" : "否" }}</td>
                <td>{{ route.operation_count }}</td>
                <td>{{ formatStatusLabel(route.status) }}</td>
                <td class="action-row">
                  <button class="ghost-button" type="button" @click="startEdit(route)">编辑</button>
                  <button class="ghost-button danger-ghost" type="button" @click="removeRoute(route)">删除</button>
                </td>
              </tr>
              <tr v-if="!filteredRoutes.length">
                <td colspan="7" class="empty-row">暂无工艺路线</td>
              </tr>
            </tbody>
          </table>
        </div>
        <PaginationBar v-model:page="routePage" v-model:page-size="routePageSize" :total="filteredRoutes.length" />
    </section>

    <FormDrawer
      :open="drawerOpen"
      eyebrow="工艺路线资料"
      :title="editingRouteId ? '编辑工艺路线' : '新增工艺路线'"
      description="维护产品工序链、参考节拍、关键工序和报工要求。"
      :tag="editingRouteId ? '编辑模式' : '新建模式'"
      wide
      @close="closeDrawer"
    >
      <form class="stack-form" @submit.prevent="submitRoute">
        <div class="double-field">
          <label class="form-field">
            <span>路线编码</span>
            <input :value="routeCodePreview" type="text" disabled readonly />
          </label>
          <label class="form-field">
            <span>路线名称 <i class="required-mark">*</i></span>
            <input v-model.trim="form.route_name" type="text" required />
          </label>
        </div>

        <div class="triple-field">
          <label class="form-field">
            <span>产品 <i class="required-mark">*</i></span>
            <select v-model.number="form.product_item_id" required>
              <option disabled value="">请选择产品</option>
              <option v-for="product in products" :key="product.item_id" :value="product.item_id">
                {{ formatProductLabel(product) }}
              </option>
            </select>
          </label>
          <label class="form-field">
            <span>版本号 <i class="required-mark">*</i></span>
            <input v-model.trim="form.version_no" type="text" required />
          </label>
          <label class="form-field">
            <span>状态</span>
            <select v-model="form.status">
              <option v-for="option in statusOptions" :key="option.value" :value="option.value">
                {{ option.label }}
              </option>
            </select>
          </label>
        </div>

        <div class="checkbox-grid">
          <label class="checkbox-field">
            <input v-model="form.is_default" type="checkbox" />
            <span>设为默认工艺路线</span>
          </label>
        </div>

        <label class="form-field">
          <span>备注</span>
          <textarea v-model.trim="form.remark" rows="2"></textarea>
        </label>

        <div class="subsection-head">
          <strong>工序明细</strong>
          <button class="ghost-button" type="button" @click="addOperationRow">增加一行</button>
        </div>

        <div class="order-item-stack">
          <article v-for="(operation, index) in form.operations" :key="index" class="order-item-card">
            <div class="subsection-head">
              <strong>工序 {{ index + 1 }}</strong>
              <button
                v-if="form.operations.length > 1"
                class="ghost-button danger-ghost"
                type="button"
                @click="removeOperationRow(index)"
              >
                删除
              </button>
            </div>

            <div class="triple-field">
              <label class="form-field">
                <span>序号 <i class="required-mark">*</i></span>
                <input v-model.number="operation.seq_no" type="number" min="1" step="1" required />
              </label>
              <label class="form-field">
                <span>工序模板 <i class="required-mark">*</i></span>
                <select v-model.number="operation.process_id" @change="applyProcess(index)" required>
                  <option disabled value="">请选择工序</option>
                  <option v-for="process in processes" :key="process.process_id" :value="process.process_id">
                    {{ process.process_code }} · {{ process.process_name }}
                  </option>
                </select>
              </label>
              <label class="form-field">
                <span>工作中心 <i class="required-mark">*</i></span>
                <select v-model.number="operation.work_center_id" required>
                  <option disabled value="">请选择工作中心</option>
                  <option v-for="center in workCenters" :key="center.id" :value="center.id">
                    {{ center.center_name }}
                  </option>
                </select>
              </label>
            </div>

            <div class="double-field">
              <label class="form-field">
                <span>工序名称 <i class="required-mark">*</i></span>
                <input v-model.trim="operation.operation_name" type="text" required />
              </label>
              <label class="form-field">
                <span>状态</span>
                <select v-model="operation.status">
                  <option v-for="option in statusOptions" :key="option.value" :value="option.value">
                    {{ option.label }}
                  </option>
                </select>
              </label>
            </div>

            <div class="triple-field">
              <label class="form-field">
                <span>准备时长(分钟)</span>
                <input v-model.number="operation.std_setup_minutes" type="number" min="0" step="0.01" />
              </label>
              <label class="form-field">
                <span>参考节拍(秒/件)</span>
                <input v-model.number="operation.std_cycle_seconds" type="number" min="0" step="0.01" />
              </label>
              <label class="form-field">
                <span>允许报废率</span>
                <input v-model.number="operation.allowed_scrap_rate" type="number" min="0" step="0.0001" />
              </label>
            </div>

            <div class="checkbox-grid">
              <label class="checkbox-field">
                <input v-model="operation.report_required" type="checkbox" />
                <span>要求报工</span>
              </label>
              <label class="checkbox-field">
                <input v-model="operation.is_key_operation" type="checkbox" />
                <span>关键工序</span>
              </label>
            </div>

            <label class="form-field">
              <span>备注</span>
              <input v-model.trim="operation.remark" type="text" />
            </label>
          </article>
        </div>

        <div class="form-toolbar">
          <button class="primary-button" type="submit" :disabled="submitting">
            {{ submitting ? "保存中..." : editingRouteId ? "更新工艺路线" : "新增工艺路线" }}
          </button>
        </div>
      </form>
    </FormDrawer>

    <FormDrawer
      :open="detailDrawerOpen"
      eyebrow="工艺路线详情"
      :title="detailRoute ? `${detailRoute.route_code} · ${detailRoute.route_name}` : '工艺路线详情'"
      tag="只读详情"
      size="xl"
      @close="closeDetailDrawer"
    >
      <div v-if="detailRoute" class="detail-grid">
        <div class="detail-item">
          <span>路线编码</span>
          <strong>{{ detailRoute.route_code }}</strong>
        </div>
        <div class="detail-item">
          <span>路线名称</span>
          <strong>{{ detailRoute.route_name }}</strong>
        </div>
        <div class="detail-item">
          <span>产品</span>
          <strong>{{ formatProductLabel(detailRoute) }}</strong>
        </div>
        <div class="detail-item">
          <span>版本号</span>
          <strong>{{ detailRoute.version_no }}</strong>
        </div>
        <div class="detail-item">
          <span>默认路线</span>
          <strong>{{ detailRoute.is_default ? "是" : "否" }}</strong>
        </div>
        <div class="detail-item">
          <span>状态</span>
          <strong>{{ formatStatusLabel(detailRoute.status) }}</strong>
        </div>
        <div class="detail-block">
          <span>备注</span>
          <strong>{{ detailRoute.remark || "-" }}</strong>
        </div>
        <div class="detail-block">
          <span>工序明细</span>
          <DrawerDataTable
            v-model:expanded-rows="expandedRouteOperationRows"
            :rows="paginatedDetailOperations"
            :columns="routeOperationDrawerColumns"
            :row-key="routeOperationRowKey"
            empty-text="暂无工序明细"
          >
            <template #detail="{ row }">
              <div class="drawer-row-detail-grid">
                <article><span>准备时长</span><strong>{{ formatMinutes(row.std_setup_minutes) }}</strong></article>
                <article><span>要求报工</span><strong>{{ row.report_required ? "是" : "否" }}</strong></article>
                <article><span>关键工序</span><strong>{{ row.is_key_operation ? "是" : "否" }}</strong></article>
                <article><span>备注</span><strong>{{ row.remark || "-" }}</strong></article>
              </div>
            </template>
          </DrawerDataTable>
          <PaginationBar
            v-model:page="detailOperationPage"
            :total="detailOperations.length"
            v-model:page-size="detailOperationPageSize"
          />
        </div>
      </div>
    </FormDrawer>
  </section>
</template>

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

import DrawerDataTable from "../components/DrawerDataTable.vue";
import FormDrawer from "../components/FormDrawer.vue";
import PaginationBar from "../components/PaginationBar.vue";
import TableControls from "../components/TableControls.vue";
import { deleteResource, fetchResource, postResource, putResource } from "../services/api";
import { buildRouteCodePreview } from "../utils/codeRules";
import { STATUS_LABELS, buildVersionedRows, formatProductLabel, formatStatusLabel } from "../utils/dictionaries";
import { usePagination } from "../utils/pagination";
import { useTableControls } from "../utils/tableControls";

const routes = ref([]);
const products = ref([]);
const processes = ref([]);
const workCenters = ref([]);
const editingRouteId = ref(null);
const selectedRouteId = ref(null);
const drawerOpen = ref(false);
const detailDrawerOpen = ref(false);
const detailRoute = ref(null);
const expandedRouteOperationRows = ref([]);
const submitting = ref(false);
const feedbackMessage = ref("");
const errorMessage = ref("");
const versionSelections = reactive({});

const statusOptions = [
  { value: "ACTIVE", label: STATUS_LABELS.ACTIVE },
  { value: "INACTIVE", label: STATUS_LABELS.INACTIVE }
];

const form = reactive(buildEmptyForm());

const routeGroups = computed(() => buildVersionedRows(routes.value, { codeKey: "route_code", idKey: "route_id" }));
const selectedProduct = computed(() => products.value.find((item) => item.item_id === Number(form.product_item_id || 0)) || null);
const routeCodePreview = computed(() => buildRouteCodePreview(selectedProduct.value?.item_code, form.route_code));
const visibleRoutes = computed(() =>
  routeGroups.value.map((group) => {
    const selectedId = Number(versionSelections[group.code] || group.active_id);
    const activeRow = group.rows.find((row) => row.route_id === selectedId) || group.rows[0];
    return {
      ...activeRow,
      version_options: group.rows.map((row) => ({
        route_id: row.route_id,
        version_no: row.version_no,
        status: row.status
      }))
    };
  })
);
const routeControls = useTableControls(visibleRoutes, {
  searchFields: ["route_code", "route_name", "product_code", "product_name", "version_no", "status"],
  sortOptions: [
    { key: "route_code", label: "路线编码" },
    { key: "product_name", label: "产品" },
    { key: "version_no", label: "版本" },
    { key: "operation_count", label: "工序数" },
    { key: "status", label: "状态" }
  ],
  defaultSortKey: "route_code",
  defaultSortDirection: "asc"
});
const currentRoute = computed(() => routes.value.find((item) => item.route_id === selectedRouteId.value) || null);
const currentOperations = computed(() => currentRoute.value?.operations || []);
const detailOperations = computed(() => detailRoute.value?.operations || []);
const filteredRoutes = routeControls.rows;
const routeOperationDrawerColumns = computed(() => [
  { key: "seq_no", label: "序号", type: "number", width: "70px" },
  { key: "operation_name", label: "工序", type: "longText", width: "24%" },
  { key: "work_center_name", label: "工作中心", type: "longText", width: "22%" },
  { key: "std_cycle_seconds", label: "参考节拍", type: "number", width: "104px", format: (value) => formatSeconds(value) },
  { key: "allowed_scrap_rate", label: "允许报废率", compactLabel: "报废率", type: "number", width: "98px", format: (value) => formatRate(value) },
  { key: "is_key_operation", label: "关键工序", compactLabel: "关键", width: "78px", format: (value) => (value ? "是" : "否") },
  { key: "std_setup_minutes", label: "准备时长", detailOnly: true, format: (value) => formatMinutes(value) },
  { key: "report_required", label: "要求报工", detailOnly: true, format: (value) => (value ? "是" : "否") },
  { key: "remark", label: "备注", detailOnly: true }
]);
const {
  page: routePage,
  pageSize: routePageSize,
  rows: paginatedRoutes
} = usePagination(filteredRoutes);
const {
  page: detailOperationPage,
  pageSize: detailOperationPageSize,
  rows: paginatedDetailOperations
} = usePagination(detailOperations);

function buildEmptyOperation(seqNo = 10) {
  return {
    seq_no: seqNo,
    process_id: "",
    work_center_id: "",
    operation_name: "",
    std_setup_minutes: 0,
    std_cycle_seconds: 0,
    std_labor_cost: 0,
    std_machine_cost: 0,
    std_outsource_cost: 0,
    allowed_scrap_rate: 0,
    report_required: true,
    is_key_operation: false,
    status: "ACTIVE",
    remark: ""
  };
}

function buildEmptyForm() {
  return {
    route_code: "",
    route_name: "",
    product_item_id: "",
    version_no: "V1.0",
    is_default: true,
    status: "ACTIVE",
    remark: "",
    operations: [buildEmptyOperation()]
  };
}

function resetForm() {
  editingRouteId.value = null;
  Object.assign(form, buildEmptyForm());
}

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

function closeDrawer() {
  drawerOpen.value = false;
  resetForm();
}

function openDetailDrawer(route) {
  selectedRouteId.value = route.route_id;
  detailRoute.value = { ...route, operations: [...(route.operations || [])] };
  expandedRouteOperationRows.value = [];
  detailDrawerOpen.value = true;
}

function closeDetailDrawer() {
  detailDrawerOpen.value = false;
  detailRoute.value = null;
}

function addOperationRow() {
  const nextSeq = form.operations.length
    ? Math.max(...form.operations.map((item) => Number(item.seq_no || 0))) + 10
    : 10;
  form.operations.push(buildEmptyOperation(nextSeq));
}

function removeOperationRow(index) {
  form.operations.splice(index, 1);
}

function applyProcess(index) {
  const process = processes.value.find((item) => item.process_id === Number(form.operations[index].process_id));
  if (!process) {
    return;
  }
  if (!form.operations[index].operation_name) {
    form.operations[index].operation_name = process.process_name;
  }
}

function applyRouteVersion(routeCode) {
  selectedRouteId.value = Number(versionSelections[routeCode] || 0);
}

function startEdit(route) {
  feedbackMessage.value = "";
  errorMessage.value = "";
  editingRouteId.value = route.route_id;
  selectedRouteId.value = route.route_id;
  versionSelections[route.route_code] = route.route_id;
  Object.assign(form, {
    route_code: route.route_code,
    route_name: route.route_name,
    product_item_id: route.product_item_id,
    version_no: route.version_no,
    is_default: Boolean(route.is_default),
    status: route.status,
    remark: route.remark || "",
    operations: (route.operations || []).map((item) => ({
      seq_no: Number(item.seq_no),
      process_id: item.process_id,
      work_center_id: item.work_center_id,
      operation_name: item.operation_name,
      std_setup_minutes: Number(item.std_setup_minutes || 0),
      std_cycle_seconds: Number(item.std_cycle_seconds || 0),
      std_labor_cost: 0,
      std_machine_cost: 0,
      std_outsource_cost: 0,
      allowed_scrap_rate: Number(item.allowed_scrap_rate || 0),
      report_required: Boolean(item.report_required),
      is_key_operation: Boolean(item.is_key_operation),
      status: item.status,
      remark: item.remark || ""
    }))
  });
  drawerOpen.value = true;
}

function formatRate(value) {
  return `${(Number(value || 0) * 100).toFixed(2)}%`;
}

function formatSeconds(value) {
  return Number(value || 0) > 0 ? `${Number(value).toFixed(2)} s` : "-";
}

function formatMinutes(value) {
  return Number(value || 0) > 0 ? `${Number(value).toFixed(2)} 分钟` : "-";
}

function routeOperationRowKey(row) {
  return `${detailRoute.value?.route_id || "route"}-${row.seq_no}`;
}

function syncVersionSelections(rows) {
  const groups = buildVersionedRows(rows, { codeKey: "route_code", idKey: "route_id" });
  const validCodes = new Set(groups.map((group) => group.code));
  Object.keys(versionSelections).forEach((code) => {
    if (!validCodes.has(code)) {
      delete versionSelections[code];
    }
  });
  groups.forEach((group) => {
    const currentSelection = Number(versionSelections[group.code] || 0);
    if (!group.rows.some((row) => row.route_id === currentSelection)) {
      versionSelections[group.code] = group.active_id;
    }
  });
}

async function loadAll() {
  const [routeRows, productRows, processRows, centerRows] = await Promise.all([
    fetchResource("/master-data/process-routes", []),
    fetchResource("/master-data/products", []),
    fetchResource("/master-data/processes", []),
    fetchResource("/master-data/work-centers", [])
  ]);
  routes.value = routeRows;
  products.value = productRows;
  processes.value = processRows;
  workCenters.value = centerRows;
  syncVersionSelections(routeRows);
  if (selectedRouteId.value && !routeRows.some((item) => item.route_id === selectedRouteId.value)) {
    selectedRouteId.value = null;
  }
  if (!selectedRouteId.value && visibleRoutes.value.length) {
    selectedRouteId.value = visibleRoutes.value[0].route_id;
  }
}

async function submitRoute() {
  feedbackMessage.value = "";
  errorMessage.value = "";
  submitting.value = true;

  try {
    const payload = {
      route_code: form.route_code || null,
      route_name: form.route_name,
      product_item_id: Number(form.product_item_id),
      version_no: form.version_no,
      is_default: Boolean(form.is_default),
      status: form.status,
      effective_date: null,
      expire_date: null,
      remark: form.remark || null,
      operations: form.operations.map((item) => ({
        seq_no: Number(item.seq_no),
        process_id: Number(item.process_id),
        work_center_id: Number(item.work_center_id),
        operation_name: item.operation_name,
        std_setup_minutes: Number(item.std_setup_minutes || 0),
        std_cycle_seconds: Number(item.std_cycle_seconds || 0),
        std_labor_cost: 0,
        std_machine_cost: 0,
        std_outsource_cost: 0,
        allowed_scrap_rate: Number(item.allowed_scrap_rate || 0),
        report_required: Boolean(item.report_required),
        is_key_operation: Boolean(item.is_key_operation),
        status: item.status,
        remark: item.remark || null
      }))
    };

    const result = editingRouteId.value
      ? await putResource(`/master-data/process-routes/${editingRouteId.value}`, payload)
      : await postResource("/master-data/process-routes", payload);

    feedbackMessage.value = `工艺路线 ${result.route_code} ${result.version_no} 已保存`;
    await loadAll();
    selectedRouteId.value = result.route_id;
    versionSelections[result.route_code] = result.route_id;
    resetForm();
    drawerOpen.value = false;
  } catch (error) {
    errorMessage.value = error.message || "保存工艺路线失败";
  } finally {
    submitting.value = false;
  }
}

async function removeRoute(route) {
  feedbackMessage.value = "";
  errorMessage.value = "";

  if (!window.confirm(`确认删除工艺路线“${route.route_code} ${route.version_no}”吗？`)) {
    return;
  }

  try {
    const result = await deleteResource(`/master-data/process-routes/${route.route_id}`);
    feedbackMessage.value = result.message || `工艺路线 ${route.route_code} 已删除`;
    if (editingRouteId.value === route.route_id) {
      resetForm();
      drawerOpen.value = false;
    }
    if (selectedRouteId.value === route.route_id) {
      selectedRouteId.value = null;
    }
    await loadAll();
  } catch (error) {
    errorMessage.value = error.message || "删除工艺路线失败";
  }
}

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