<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="openEquipmentDrawer">新增设备</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="equipmentControls.search.value"
        v-model:sort-key="equipmentControls.sortKey.value"
        v-model:sort-direction="equipmentControls.sortDirection.value"
        :sort-options="equipmentControls.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>
            </tr>
          </thead>
          <tbody>
            <tr v-for="equipment in paginatedEquipments" :key="equipment.equipment_id">
              <td>{{ equipment.equipment_code }}</td>
              <td>{{ equipment.equipment_name }}</td>
              <td>{{ equipment.work_center_name }}</td>
              <td>{{ Number(equipment.occupied_area_sqm || 0).toFixed(2) }} m²</td>
              <td>{{ formatStatusLabel(equipment.status) }}</td>
              <td>{{ formatDateTime(equipment.last_maintenance_at) }}</td>
              <td>{{ formatDateTime(resolveNextMaintenanceAt(equipment)) }}</td>
              <td>{{ Number(equipment.maintenance_cycle_hours || 0).toFixed(0) }} 小时</td>
            </tr>
            <tr v-if="!filteredEquipments.length">
              <td colspan="8" class="empty-row">暂无设备资料</td>
            </tr>
          </tbody>
        </table>
      </div>
      <PaginationBar v-model:page="equipmentPage" v-model:page-size="equipmentPageSize" :total="filteredEquipments.length" />
    </section>

    <section class="panel">
      <div class="panel-header">
        <div>
          <p class="eyebrow">保养记录</p>
          <h3>最近保养执行记录</h3>
        </div>
        <button class="primary-button" type="button" @click="openMaintenanceDrawer">新增保养记录</button>
      </div>

      <TableControls
        v-model:search="orderControls.search.value"
        v-model:sort-key="orderControls.sortKey.value"
        v-model:sort-direction="orderControls.sortDirection.value"
        :sort-options="orderControls.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="order in paginatedOrders" :key="order.maintenance_order_id">
              <td>{{ order.order_no }}</td>
              <td>{{ order.equipment_name }}</td>
              <td>{{ formatMaintenanceTypeLabel(order.maintenance_type) }}</td>
              <td>{{ formatDateTime(order.start_time) }}</td>
              <td>{{ order.downtime_minutes }}</td>
              <td>¥{{ formatAmount(order.cost_amount) }}</td>
              <td>{{ formatStatusLabel(order.status) }}</td>
            </tr>
            <tr v-if="!filteredOrders.length">
              <td colspan="7" class="empty-row">暂无保养记录</td>
            </tr>
          </tbody>
        </table>
      </div>
      <PaginationBar v-model:page="orderPage" v-model:page-size="orderPageSize" :total="filteredOrders.length" />
    </section>

    <FormDrawer
      :open="equipmentDrawerOpen"
      eyebrow="设备台账"
      title="新增设备"
      description="维护设备基础信息和保养周期，下次保养时间由最近保养时间加保养周期计算。"
      tag="设备主档"
      @close="equipmentDrawerOpen = false"
    >
      <form class="stack-form" @submit.prevent="submitEquipment">
        <label class="form-field">
          <span>设备名称</span>
          <input v-model.trim="equipmentForm.equipment_name" type="text" required />
        </label>

        <div class="double-field">
          <label class="form-field">
            <span>分类</span>
            <input v-model.trim="equipmentForm.category_name" type="text" />
          </label>
          <label class="form-field">
            <span>工作中心</span>
            <select v-model.number="equipmentForm.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>制造商</span>
            <input v-model.trim="equipmentForm.manufacturer" type="text" />
          </label>
          <label class="form-field">
            <span>型号</span>
            <input v-model.trim="equipmentForm.model_no" type="text" />
          </label>
        </div>

        <div class="triple-field">
          <label class="form-field">
            <span>安装日期</span>
            <input v-model="equipmentForm.install_date" type="date" />
          </label>
          <label class="form-field">
            <span>额定功率(kW)</span>
            <input v-model.number="equipmentForm.rated_power_kw" type="number" min="0" step="0.01" />
          </label>
          <label class="form-field">
            <span>占用场地面积(m²)</span>
            <input v-model.number="equipmentForm.occupied_area_sqm" type="number" min="0" step="0.01" />
          </label>
        </div>

        <div class="double-field">
          <label class="form-field">
            <span>保养周期(小时)</span>
            <input v-model.number="equipmentForm.maintenance_cycle_hours" type="number" min="0" step="0.01" />
          </label>
          <label class="form-field">
            <span>财务分摊说明</span>
            <input value="用于厂房租金/场地成本按设备占地面积做参考分摊" type="text" disabled readonly />
          </label>
        </div>

        <button class="primary-button" type="submit">新增设备</button>
      </form>
    </FormDrawer>

    <FormDrawer
      :open="maintenanceDrawerOpen"
      eyebrow="保养记录"
      title="新增保养记录"
      description="登记实际保养执行情况，完成后会更新设备最近一次保养和下次保养时间。"
      tag="执行记录"
      @close="maintenanceDrawerOpen = false"
    >
      <form class="stack-form" @submit.prevent="submitOrder">
        <label class="form-field">
          <span>设备</span>
          <select v-model.number="orderForm.equipment_id" required @change="applyEquipmentDefaults">
            <option disabled value="">请选择设备</option>
            <option v-for="equipment in equipments" :key="equipment.equipment_id" :value="equipment.equipment_id">
              {{ equipment.equipment_name }}
            </option>
          </select>
        </label>

        <div class="double-field">
          <label class="form-field">
            <span>保养类型</span>
            <input v-model.trim="orderForm.maintenance_type" type="text" required />
          </label>
          <label class="form-field">
            <span>负责人</span>
            <select v-model.number="orderForm.owner_employee_id">
              <option value="">请选择</option>
              <option v-for="employee in employees" :key="employee.id" :value="employee.id">
                {{ employeeOptionLabel(employee) }}
              </option>
            </select>
          </label>
        </div>

        <div class="double-field">
          <label class="form-field">
            <span>开始时间</span>
            <input v-model="orderForm.start_time" type="datetime-local" />
          </label>
          <label class="form-field">
            <span>结束时间</span>
            <input v-model="orderForm.end_time" type="datetime-local" />
          </label>
        </div>

        <div class="double-field">
          <label class="form-field">
            <span>停机时长(分钟)</span>
            <input v-model.number="orderForm.downtime_minutes" type="number" min="0" step="0.01" />
          </label>
          <label class="form-field">
            <span>成本金额</span>
            <input v-model.number="orderForm.cost_amount" type="number" min="0" step="0.01" />
          </label>
        </div>

        <label class="form-field">
          <span>执行结果</span>
          <textarea v-model.trim="orderForm.result_summary" rows="2"></textarea>
        </label>

        <label class="form-field">
          <span>状态</span>
          <select v-model="orderForm.status">
            <option value="CREATED">已创建</option>
            <option value="COMPLETED">已完成</option>
          </select>
        </label>

        <button class="primary-button" type="submit">登记保养记录</button>
      </form>
    </FormDrawer>
  </section>
</template>

<script setup>
import { 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 { PERSONNEL_PERMISSION_CODES, employeeOptionLabel, fetchPermissionEmployeeOptions } from "../services/employeeOptions";
import { formatAmount, formatDateTime } from "../utils/formatters";
import { formatMaintenanceTypeLabel, formatStatusLabel } from "../utils/dictionaries";
import { usePagination } from "../utils/pagination";
import { useTableControls } from "../utils/tableControls";

const equipments = ref([]);
const orders = ref([]);
const workCenters = ref([]);
const employees = ref([]);
const feedbackMessage = ref("");
const errorMessage = ref("");
const equipmentDrawerOpen = ref(false);
const maintenanceDrawerOpen = ref(false);

const equipmentControls = useTableControls(equipments, {
  searchFields: ["equipment_code", "equipment_name", "work_center_name", "occupied_area_sqm", "status"],
  sortOptions: [
    { key: "equipment_code", label: "设备编码" },
    { key: "equipment_name", label: "设备名称" },
    { key: "work_center_name", label: "工作中心" },
    { key: "occupied_area_sqm", label: "占用面积" },
    { key: "last_maintenance_at", label: "最近保养" },
    { key: "next_maintenance_at", label: "下次保养" },
    { key: "status", label: "状态" }
  ],
  defaultSortKey: "equipment_code",
  defaultSortDirection: "desc"
});
const orderControls = useTableControls(orders, {
  searchFields: ["order_no", "equipment_name", "maintenance_type", "status", (row) => formatMaintenanceTypeLabel(row.maintenance_type)],
  sortOptions: [
    { key: "order_no", label: "保养单号" },
    { key: "equipment_name", label: "设备" },
    { key: "start_time", label: "开始时间" },
    { key: "cost_amount", label: "成本" },
    { key: "status", label: "状态" }
  ],
  defaultSortKey: "start_time",
  defaultSortDirection: "desc"
});
const filteredEquipments = equipmentControls.rows;
const filteredOrders = orderControls.rows;
const {
  page: equipmentPage,
  pageSize: equipmentPageSize,
  rows: paginatedEquipments
} = usePagination(filteredEquipments);
const {
  page: orderPage,
  pageSize: orderPageSize,
  rows: paginatedOrders
} = usePagination(filteredOrders);

const now = new Date().toISOString().slice(0, 16);

const equipmentForm = reactive(buildEmptyEquipmentForm());
const orderForm = reactive(buildEmptyOrderForm());

function buildEmptyEquipmentForm() {
  return {
    equipment_name: "",
    category_name: "",
    work_center_id: "",
    manufacturer: "",
    model_no: "",
    install_date: "",
    rated_power_kw: 0,
    occupied_area_sqm: 0,
    maintenance_cycle_hours: 0
  };
}

function buildEmptyOrderForm() {
  return {
    equipment_id: "",
    maintenance_type: "",
    start_time: now,
    end_time: now,
    downtime_minutes: 0,
    owner_employee_id: "",
    result_summary: "",
    cost_amount: 0,
    status: "COMPLETED"
  };
}

function resolveNextMaintenanceAt(equipment) {
  if (equipment.last_maintenance_at && Number(equipment.maintenance_cycle_hours || 0) > 0) {
    const next = new Date(equipment.last_maintenance_at);
    next.setHours(next.getHours() + Number(equipment.maintenance_cycle_hours || 0));
    return next.toISOString();
  }
  return equipment.next_maintenance_at;
}

function openEquipmentDrawer() {
  Object.assign(equipmentForm, buildEmptyEquipmentForm());
  equipmentDrawerOpen.value = true;
}

function openMaintenanceDrawer() {
  Object.assign(orderForm, buildEmptyOrderForm());
  maintenanceDrawerOpen.value = true;
}

function applyEquipmentDefaults() {
  const equipment = equipments.value.find((item) => item.equipment_id === Number(orderForm.equipment_id));
  if (equipment && !orderForm.maintenance_type) {
    orderForm.maintenance_type = "周期保养";
  }
}

async function loadAll() {
  const [equipmentRows, orderRows, centerRows, employeeRows] = await Promise.all([
    fetchResource("/equipment/assets", []),
    fetchResource("/equipment/maintenance-orders", []),
    fetchResource("/master-data/work-centers", []),
    fetchPermissionEmployeeOptions(PERSONNEL_PERMISSION_CODES.EQUIPMENT_MANAGEMENT)
  ]);
  equipments.value = equipmentRows;
  orders.value = orderRows;
  workCenters.value = centerRows;
  employees.value = employeeRows;
}

async function submitEquipment() {
  feedbackMessage.value = "";
  errorMessage.value = "";
  try {
    const result = await postResource("/equipment/assets", {
      equipment_name: equipmentForm.equipment_name,
      category_name: equipmentForm.category_name || null,
      work_center_id: Number(equipmentForm.work_center_id),
      manufacturer: equipmentForm.manufacturer || null,
      model_no: equipmentForm.model_no || null,
      install_date: equipmentForm.install_date || null,
      rated_power_kw: Number(equipmentForm.rated_power_kw || 0),
      occupied_area_sqm: Number(equipmentForm.occupied_area_sqm || 0),
      maintenance_cycle_hours: Number(equipmentForm.maintenance_cycle_hours || 0),
      status: "IDLE"
    });
    feedbackMessage.value = `设备 ${result.equipment_name} 已建立`;
    equipmentDrawerOpen.value = false;
    await loadAll();
  } catch (error) {
    errorMessage.value = error.message || "设备新增失败";
  }
}

async function submitOrder() {
  feedbackMessage.value = "";
  errorMessage.value = "";
  try {
    const result = await postResource("/equipment/maintenance-orders", {
      equipment_id: Number(orderForm.equipment_id),
      maintenance_type: orderForm.maintenance_type,
      start_time: orderForm.start_time ? `${orderForm.start_time}:00` : null,
      end_time: orderForm.end_time ? `${orderForm.end_time}:00` : null,
      downtime_minutes: Number(orderForm.downtime_minutes || 0),
      owner_employee_id: orderForm.owner_employee_id ? Number(orderForm.owner_employee_id) : null,
      result_summary: orderForm.result_summary || null,
      cost_amount: Number(orderForm.cost_amount || 0),
      status: orderForm.status
    });
    feedbackMessage.value = `保养记录 ${result.order_no} 已登记`;
    maintenanceDrawerOpen.value = false;
    await loadAll();
  } catch (error) {
    errorMessage.value = error.message || "保养记录登记失败";
  }
}

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