<template>
  <section class="page-grid">
    <section class="panel">
      <div class="panel-header">
        <div>
          <p class="eyebrow">小程序人员清单</p>
          <h3>ERP 与报工小程序共用同一张人员表</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="personControls.search.value"
        v-model:sort-key="personControls.sortKey.value"
        v-model:sort-direction="personControls.sortDirection.value"
        :sort-options="personControls.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="person in paginatedPeople" :key="person.phone">
              <td>
                <button class="link-button" type="button" @click="openDetailDrawer(person)">
                  {{ person.phone }}
                </button>
              </td>
              <td>{{ person.name }}</td>
              <td>{{ formatPersonRoles(person) }}</td>
              <td>{{ formatAttendancePoints(person.attendance_point_names) }}</td>
              <td>{{ person.is_temporary ? "是" : "否" }}</td>
              <td>{{ formatDateTime(person.temporary_expires_at) }}</td>
              <td>{{ person.temporary_expired ? "已过期" : "可用" }}</td>
              <td>{{ formatDateTime(person.updated_at) }}</td>
              <td class="action-row">
                <button class="ghost-button" type="button" @click="startEdit(person)">编辑</button>
                <button class="ghost-button danger-ghost" type="button" @click="removePerson(person)">删除</button>
              </td>
            </tr>
            <tr v-if="!filteredPeople.length">
              <td colspan="9" class="empty-row">暂无小程序人员</td>
            </tr>
          </tbody>
        </table>
      </div>
      <PaginationBar v-model:page="personPage" v-model:page-size="personPageSize" :total="filteredPeople.length" />
    </section>

    <FormDrawer
      :open="drawerOpen"
      eyebrow="人员资料"
      :title="editingPhone ? '编辑小程序人员' : '新增小程序人员'"
      description="该页面直接维护报工小程序人员，保存后小程序和 ERP 同步可见。"
      :tag="editingPhone ? '编辑模式' : '新建模式'"
      @close="closeDrawer"
    >
      <form class="stack-form" @submit.prevent="submitPerson">
        <label class="form-field">
          <span>手机号 <i class="required-mark">*</i></span>
          <input v-model.trim="form.phone" type="text" required :disabled="Boolean(editingPhone)" />
        </label>

        <label class="form-field">
          <span>姓名 <i class="required-mark">*</i></span>
          <input v-model.trim="form.name" type="text" required />
        </label>

        <div class="checkbox-grid">
          <label v-for="role in roleOptions" :key="role.value" class="checkbox-field">
            <input v-model="form.roles" type="checkbox" :value="role.value" />
            <span>{{ role.label }}</span>
          </label>
        </div>

        <div class="subsection-head">
          <strong>考勤点权限 <i class="required-mark">*</i></strong>
        </div>
        <div class="checkbox-grid">
          <label v-for="point in attendancePoints" :key="point.name" class="checkbox-field">
            <input v-model="form.attendance_point_names" type="checkbox" :value="point.name" />
            <span>{{ point.name }}</span>
          </label>
        </div>

        <div class="double-field">
          <label class="checkbox-field">
            <input v-model="form.is_temporary" type="checkbox" />
            <span>临时人员</span>
          </label>
          <label class="form-field">
            <span>临时到期时间</span>
            <input v-model="form.temporary_expires_at" type="datetime-local" :disabled="!form.is_temporary" />
          </label>
        </div>

        <div class="form-toolbar">
          <button class="primary-button" type="submit" :disabled="submitting">
            {{ submitting ? "保存中..." : "保存人员" }}
          </button>
        </div>
      </form>
    </FormDrawer>

    <FormDrawer
      :open="detailDrawerOpen"
      eyebrow="人员详情"
      :title="detailPerson ? `${detailPerson.phone} · ${detailPerson.name}` : '人员详情'"
      tag="小程序同表"
      @close="closeDetailDrawer"
    >
      <div v-if="detailPerson" class="detail-grid">
        <div class="detail-item">
          <span>手机号</span>
          <strong>{{ detailPerson.phone }}</strong>
        </div>
        <div class="detail-item">
          <span>姓名</span>
          <strong>{{ detailPerson.name }}</strong>
        </div>
        <div class="detail-item">
          <span>角色</span>
          <strong>{{ formatPersonRoles(detailPerson) }}</strong>
        </div>
        <div class="detail-item">
          <span>考勤点</span>
          <strong>{{ formatAttendancePoints(detailPerson.attendance_point_names) }}</strong>
        </div>
        <div class="detail-item">
          <span>临时人员</span>
          <strong>{{ detailPerson.is_temporary ? "是" : "否" }}</strong>
        </div>
        <div class="detail-item">
          <span>临时到期</span>
          <strong>{{ formatDateTime(detailPerson.temporary_expires_at) }}</strong>
        </div>
        <div class="detail-item">
          <span>创建时间</span>
          <strong>{{ formatDateTime(detailPerson.created_at) }}</strong>
        </div>
      </div>
    </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 { deleteResource, fetchResource, postResource, putResource } from "../services/api";
import { formatMiniappRoleLabel } from "../utils/dictionaries";
import { formatDateTime } from "../utils/formatters";
import { usePagination } from "../utils/pagination";
import { useTableControls } from "../utils/tableControls";

const people = ref([]);
const attendancePoints = ref([]);
const editingPhone = ref("");
const drawerOpen = ref(false);
const detailDrawerOpen = ref(false);
const detailPerson = ref(null);
const submitting = ref(false);
const feedbackMessage = ref("");
const errorMessage = ref("");

const roleOptions = [
  { value: "worker", label: formatMiniappRoleLabel("worker") },
  { value: "manager", label: formatMiniappRoleLabel("manager") },
  { value: "admin", label: formatMiniappRoleLabel("admin") }
];

const form = reactive(buildEmptyForm());

const personControls = useTableControls(people, {
  searchFields: ["phone", "name", formatPersonRoles, (row) => row.attendance_point_names?.join(" / ")],
  sortOptions: [
    { key: "phone", label: "手机号" },
    { key: "name", label: "姓名" },
    { key: "updated_at", label: "更新时间" }
  ],
  defaultSortKey: "updated_at",
  defaultSortDirection: "desc"
});
const filteredPeople = personControls.rows;
const {
  page: personPage,
  pageSize: personPageSize,
  rows: paginatedPeople
} = usePagination(filteredPeople);

function buildEmptyForm() {
  return {
    phone: "",
    name: "",
    roles: ["worker"],
    attendance_point_names: [],
    is_temporary: false,
    temporary_expires_at: ""
  };
}

function toDateTimeInput(value) {
  return value ? String(value).replace("T", " ").slice(0, 16).replace(" ", "T") : "";
}

function normalizeDateTime(value) {
  return value ? `${value}:00` : null;
}

function resetForm() {
  editingPhone.value = "";
  Object.assign(form, buildEmptyForm());
  if (attendancePoints.value.length) {
    form.attendance_point_names = attendancePoints.value.map((point) => point.name);
  }
}

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

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

function openDetailDrawer(person) {
  detailPerson.value = { ...person };
  detailDrawerOpen.value = true;
}

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

function startEdit(person) {
  feedbackMessage.value = "";
  errorMessage.value = "";
  editingPhone.value = person.phone;
  Object.assign(form, {
    phone: person.phone,
    name: person.name,
    roles: person.roles?.length ? [...person.roles] : ["worker"],
    attendance_point_names: person.attendance_point_names?.length
      ? [...person.attendance_point_names]
      : attendancePoints.value.map((point) => point.name),
    is_temporary: Boolean(person.is_temporary),
    temporary_expires_at: toDateTimeInput(person.temporary_expires_at)
  });
  drawerOpen.value = true;
}

async function loadPeople() {
  const [pointRows, peopleRows] = await Promise.all([
    fetchResource("/master-data/miniapp-attendance-points", []),
    fetchResource("/master-data/miniapp-personnel?limit=500", [])
  ]);
  attendancePoints.value = pointRows;
  people.value = peopleRows;
}

function buildPayload() {
  if (!form.attendance_point_names.length) {
    throw new Error("请至少选择一个考勤点");
  }
  return {
    phone: form.phone,
    name: form.name,
    roles: form.roles?.length ? form.roles : ["worker"],
    attendance_point_names: form.attendance_point_names,
    is_temporary: Boolean(form.is_temporary),
    temporary_expires_at: form.is_temporary ? normalizeDateTime(form.temporary_expires_at) : null
  };
}

function formatAttendancePoints(pointNames) {
  return pointNames?.length ? pointNames.join(" / ") : "-";
}

function formatPersonRoles(person) {
  const roleValues = person?.roles?.length ? person.roles : person?.role_names || [];
  const labels = roleValues.map((role) => formatMiniappRoleLabel(role)).filter(Boolean);
  return labels.length ? Array.from(new Set(labels)).join(" / ") : "-";
}

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

  try {
    const payload = buildPayload();
    const result = editingPhone.value
      ? await putResource(`/master-data/miniapp-personnel/${editingPhone.value}`, payload)
      : await postResource("/master-data/miniapp-personnel", payload);

    feedbackMessage.value = `人员 ${result.name} 已保存`;
    await loadPeople();
    resetForm();
    drawerOpen.value = false;
  } catch (error) {
    errorMessage.value = error.message || "保存人员失败";
  } finally {
    submitting.value = false;
  }
}

async function removePerson(person) {
  feedbackMessage.value = "";
  errorMessage.value = "";

  if (!window.confirm(`确认删除小程序人员“${person.name}”吗？已有报工记录的人员不能删除。`)) {
    return;
  }

  try {
    const result = await deleteResource(`/master-data/miniapp-personnel/${person.phone}`);
    feedbackMessage.value = result.message || `人员 ${person.name} 已删除`;
    await loadPeople();
  } catch (error) {
    errorMessage.value = error.message || "删除人员失败";
  }
}

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