<template>
  <view class="page">
    <NavBar :title="isEdit ? '编辑人员' : '新增人员'" :showBack="true" @back="goBack" />

    <scroll-view class="form-scroll" scroll-y>
      <!-- 编辑模式：头像区 -->
      <view class="avatar-card" v-if="isEdit">
        <view class="ac-avatar" :class="form.status === 2 ? 'off' : ''">
          <text>{{ (form.realName || form.username || '?')[0] }}</text>
        </view>
        <view class="ac-info">
          <text class="ac-name">{{ form.realName || form.username }}</text>
          <text class="ac-username">@{{ form.username }}</text>
          <view class="ac-status" :class="form.status === 1 ? 'on' : 'off'">
            <view class="ac-dot" :class="form.status === 1 ? 'on' : 'off'"></view>
            <text>{{ form.status === 1 ? '已启用' : '已停用' }}</text>
          </view>
        </view>
      </view>

      <!-- 表单卡片 -->
      <view class="form-card">
        <!-- 基本信息 -->
        <view class="section-title">基本信息</view>

        <view class="field">
          <text class="field-label">用户名<text class="required">*</text></text>
          <input
            class="field-input"
            v-model="form.username"
            placeholder="登录账号"
            placeholder-class="field-ph"
            :disabled="isEdit"
          />
          <text class="field-hint" v-if="isEdit">用户名不可修改</text>
        </view>

        <view class="field" v-if="!isEdit">
          <text class="field-label">登录密码<text class="required">*</text></text>
          <input
            class="field-input"
            v-model="form.password"
            placeholder="设置登录密码"
            placeholder-class="field-ph"
            password
          />
        </view>

        <view class="field">
          <text class="field-label">真实姓名<text class="required">*</text></text>
          <input
            class="field-input"
            v-model="form.realName"
            placeholder="请输入真实姓名"
            placeholder-class="field-ph"
          />
        </view>

        <view class="field">
          <text class="field-label">手机号<text class="required">*</text></text>
          <input
            class="field-input"
            v-model="form.phone"
            placeholder="请输入手机号"
            placeholder-class="field-ph"
            type="number"
            maxlength="11"
          />
        </view>

        <view class="field">
          <text class="field-label">邮箱</text>
          <input
            class="field-input"
            v-model="form.email"
            placeholder="选填"
            placeholder-class="field-ph"
          />
        </view>
      </view>

      <!-- 权限与状态 -->
      <view class="form-card">
        <view class="section-title">权限与状态</view>

        <view class="field" @click="showRolePicker">
          <text class="field-label">角色<text class="required">*</text></text>
          <view class="field-picker">
            <text class="picker-text" :class="{ placeholder: !selectedRoleName }">
              {{ selectedRoleName || '请选择角色' }}
            </text>
            <view class="picker-arrow"></view>
          </view>
          <text class="field-hint">分配角色以授予对应的操作权限</text>
        </view>

        <view class="field">
          <text class="field-label">账号状态</text>
          <view class="field-switch-row">
            <view
              class="switch-opt"
              :class="{ on: form.status === 1 }"
              @click="form.status = 1"
            >
              <view class="so-dot on"></view>
              <text>启用</text>
            </view>
            <view
              class="switch-opt"
              :class="{ on: form.status === 2 }"
              @click="form.status = 2"
            >
              <view class="so-dot off"></view>
              <text>停用</text>
            </view>
          </view>
        </view>

        <view class="field">
          <text class="field-label">备注</text>
          <textarea
            class="field-textarea"
            v-model="form.remark"
            placeholder="备注信息（选填）"
            placeholder-class="field-ph"
            :maxlength="200"
          />
          <text class="field-hint right">{{ form.remark ? form.remark.length : 0 }}/200</text>
        </view>
      </view>

      <!-- 操作按钮 -->
      <view class="btn-area">
        <view class="btn-save" @click="handleSave">
          <text class="btn-save-text">{{ isEdit ? '保存修改' : '创建人员' }}</text>
        </view>
        <view class="btn-reset" v-if="isEdit" @click="handleResetPwd">
          <text class="btn-reset-text">重置密码</text>
        </view>
        <view class="btn-delete" v-if="isEdit" @click="handleDelete">
          <text class="btn-delete-text">删除人员</text>
        </view>
      </view>

      <view class="bottom-safe"></view>
    </scroll-view>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import NavBar from '@/components/NavBar.vue';
import {
  addStaff,
  updateStaff,
  getStaffById,
  deleteStaff,
  resetStaffPassword,
  getAllRoles,
  type RoleOption,
  type StaffForm
} from '@/api/staff';

const isEdit = ref(false);
const editId = ref<number | null>(null);
const roleOptions = ref<RoleOption[]>([]);
const saving = ref(false);

const form = reactive<StaffForm>({
  username: '',
  password: '',
  realName: '',
  phone: '',
  email: '',
  roleIds: '',
  status: 1,
  remark: ''
});

const selectedRoleName = ref('');

const loadRoles = async () => {
  try {
    roleOptions.value = await getAllRoles();
  } catch (e) {
    // ignore
  }
};

const loadDetail = async (id: number) => {
  try {
    const data = await getStaffById(id);
    if (data) {
      form.id = data.id;
      form.username = data.username || '';
      form.realName = data.realName || '';
      form.phone = data.phone || '';
      form.email = data.email || '';
      form.roleIds = data.roleIds ? data.roleIds.split(',')[0] : '';
      form.status = data.status || 1;
      form.remark = data.remark || '';

      if (data.roleIds && roleOptions.value.length > 0) {
        const firstRoleId = data.roleIds.split(',')[0];
        const role = roleOptions.value.find(r => String(r.id) === String(firstRoleId));
        if (role) selectedRoleName.value = role.name;
      }
    }
  } catch (e) {
    uni.showToast({ title: '加载失败', icon: 'none' });
  }
};

const showRolePicker = () => {
  if (roleOptions.value.length === 0) {
    uni.showToast({ title: '暂无可用角色', icon: 'none' });
    return;
  }
  const names = roleOptions.value.map(r => r.name);
  uni.showActionSheet({
    itemList: names,
    itemColor: '#1E293B',
    success: (res) => {
      const role = roleOptions.value[res.tapIndex];
      if (role) {
        form.roleIds = String(role.id);
        selectedRoleName.value = role.name;
      }
    }
  });
};

const validate = (): string | null => {
  if (!form.username || !form.username.trim()) return '请输入用户名';
  if (!isEdit.value && (!form.password || !form.password.trim())) return '请输入登录密码';
  if (!form.realName || !form.realName.trim()) return '请输入真实姓名';
  if (!form.phone || !form.phone.trim()) return '请输入手机号';
  if (!/^1[3-9]\d{9}$/.test(form.phone.trim())) return '请输入正确的手机号';
  if (form.email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email.trim())) return '请输入正确的邮箱';
  if (!form.roleIds) return '请选择角色';
  return null;
};

const handleSave = async () => {
  if (saving.value) return;
  const err = validate();
  if (err) {
    uni.showToast({ title: err, icon: 'none' });
    return;
  }
  saving.value = true;
  uni.showLoading({ title: '保存中...', mask: true });

  try {
    const data: StaffForm = { ...form };
    if (isEdit.value) {
      delete data.password;
      await updateStaff(data);
    } else {
      await addStaff(data);
    }
    uni.hideLoading();
    uni.showToast({ title: isEdit.value ? '修改成功' : '新增成功', icon: 'success' });
    setTimeout(() => {
      uni.navigateBack();
    }, 1200);
  } catch (e) {
    uni.hideLoading();
    uni.showToast({ title: '保存失败', icon: 'none' });
  } finally {
    saving.value = false;
  }
};

const handleResetPwd = () => {
  uni.showModal({
    title: '重置密码',
    content: '确认重置该人员的登录密码？密码将重置为默认值。',
    success: async (res) => {
      if (!res.confirm) return;
      try {
        await resetStaffPassword(editId.value!, '123456');
        uni.showToast({ title: '密码已重置', icon: 'success' });
      } catch (e) {
        uni.showToast({ title: '操作失败', icon: 'none' });
      }
    }
  });
};

const handleDelete = () => {
  uni.showModal({
    title: '确认删除',
    content: `确认删除人员「${form.realName || form.username}」？删除后不可恢复。`,
    success: async (res) => {
      if (!res.confirm) return;
      try {
        await deleteStaff(editId.value!);
        uni.showToast({ title: '已删除', icon: 'success' });
        setTimeout(() => {
          uni.navigateBack();
        }, 1200);
      } catch (e) {
        uni.showToast({ title: '删除失败', icon: 'none' });
      }
    }
  });
};

const goBack = () => {
  uni.navigateBack();
};

onMounted(async () => {
  const pages = getCurrentPages();
  const page = pages[pages.length - 1];
  const options = (page as any).options || {};
  const id = options.id ? Number(options.id) : null;

  await loadRoles();

  if (id) {
    isEdit.value = true;
    editId.value = id;
    uni.setNavigationBarTitle({ title: '编辑人员' });
    await loadDetail(id);
  }
});
</script>

<style lang="scss" scoped>
$font-stack: -apple-system, BlinkMacSystemFont, 'PingFang SC', 'Helvetica Neue', system-ui, sans-serif;

.page {
  height: 100vh;
  width: 100vw;
  overflow-x: hidden;
  background: $bg-color-page;
  display: flex;
  flex-direction: column;
  font-family: $font-stack;
}

// ====== Scroll ======
.form-scroll {
  flex: 1;
  width: 100%;
  padding: 24rpx;
  box-sizing: border-box;
}

// ====== Avatar card (edit mode) ======
.avatar-card {
  display: flex;
  align-items: center;
  background: $bg-color-card;
  border-radius: 20rpx;
  padding: 32rpx;
  margin-bottom: 24rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
  gap: 24rpx;
  overflow: hidden;
}

.ac-avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  background: $primary-color-bg;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;

  text {
    font-size: 36rpx;
    font-weight: 700;
    color: $primary-color-dark;
  }

  &.off {
    background: $bg-color-page;
    text { color: $text-color-placeholder; }
  }
}

.ac-info {
  flex: 1;
  min-width: 0;
  display: flex;
  flex-direction: column;
  gap: 8rpx;
}

.ac-name {
  font-size: 32rpx;
  font-weight: 600;
  color: $text-color-primary;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.ac-username {
  font-size: 24rpx;
  color: $text-color-muted;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.ac-status {
  display: flex;
  align-items: center;
  gap: 8rpx;
  margin-top: 8rpx;

  text { font-size: 24rpx; font-weight: 500; }
  &.on text { color: $success-color; }
  &.off text { color: $text-color-muted; }
}

.ac-dot {
  width: 12rpx; height: 12rpx; border-radius: 50%;
  flex-shrink: 0;
  &.on { background: $success-color; }
  &.off { background: $text-color-placeholder; }
}

// ====== Form card ======
.form-card {
  background: $bg-color-card;
  border-radius: 20rpx;
  padding: 32rpx;
  margin-bottom: 24rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

.section-title {
  font-size: 32rpx;
  font-weight: 700;
  color: $text-color-primary;
  margin-bottom: 16rpx;
  letter-spacing: 2rpx;
}

// ====== Field ======
.field {
  padding: 24rpx 0;

  &:first-of-type {
    padding-top: 16rpx;
  }

  &:not(:last-of-type) {
    border-bottom: 1rpx solid $border-color-light;
  }

  &:last-child {
    padding-bottom: 0;
  }
}

.field-label {
  font-size: 28rpx;
  font-weight: 600;
  color: $text-color-primary;
  margin-bottom: 16rpx;
  display: block;
}

.required {
  color: $error-color;
  margin-left: 4rpx;
  font-weight: 400;
}

.field-input {
  font-size: 28rpx;
  color: $text-color-primary;
  background: $bg-color-page;
  border-radius: 12rpx;
  padding: 0 24rpx;
  height: 80rpx;
  line-height: 80rpx;
  width: 100%;
  box-sizing: border-box;

  &[disabled] {
    color: $text-color-muted;
    background: $bg-color-secondary;
  }
}

.field-ph {
  color: $text-color-placeholder;
  font-size: 24rpx;
}

.field-textarea {
  font-size: 28rpx;
  color: $text-color-primary;
  background: $bg-color-page;
  border-radius: 12rpx;
  padding: 24rpx;
  width: 100%;
  box-sizing: border-box;
  min-height: 180rpx;
}

.field-hint {
  font-size: 22rpx;
  color: $text-color-muted;
  margin-top: 12rpx;
  display: block;
  line-height: 1.5;

  &.right {
    text-align: right;
  }
}

// ====== Role picker ======
.field-picker {
  display: flex;
  align-items: center;
  background: $bg-color-page;
  border-radius: 12rpx;
  padding: 0 24rpx;
  height: 80rpx;
  transition: opacity 0.15s ease;
  overflow: hidden;

  &:active { opacity: 0.7; }
}

.picker-text {
  flex: 1;
  font-size: 28rpx;
  color: $text-color-primary;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;

  &.placeholder {
    color: $text-color-placeholder;
  }
}

.picker-arrow {
  width: 12rpx; height: 12rpx;
  border-top: 3rpx solid $text-color-placeholder;
  border-right: 3rpx solid $text-color-placeholder;
  transform: rotate(45deg);
  flex-shrink: 0;
  margin-left: 8rpx;
}

// ====== Status switch ======
.field-switch-row {
  display: flex;
  gap: 16rpx;
}

.switch-opt {
  flex: 1;
  min-width: 0;
  padding: 24rpx 0;
  border-radius: 16rpx;
  background: $bg-color-page;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10rpx;
  transition: background 0.2s ease;

  text {
    font-size: 28rpx;
    font-weight: 500;
    color: $text-color-muted;
    transition: color 0.2s ease;
  }

  &.on {
    background: $primary-color-bg;
    box-shadow: inset 0 0 0 2rpx rgba(255, 193, 7, 0.2);
    text { color: $primary-color-dark; font-weight: 600; }
  }

  &:active { opacity: 0.7; }
}

.so-dot {
  width: 16rpx; height: 16rpx; border-radius: 50%;
  flex-shrink: 0;
  &.on { background: $success-color; box-shadow: 0 0 8rpx rgba(16, 185, 129, 0.3); }
  &.off { background: $text-color-placeholder; }
}

// ====== Buttons ======
.btn-area {
  display: flex;
  flex-direction: column;
  gap: 16rpx;
  margin-top: 16rpx;
  align-items: center;
}

.btn-save {
  width: 100%;
  background: $primary-color;
  border-radius: 48rpx;
  padding: 28rpx 0;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4rpx 16rpx rgba(255, 193, 7, 0.3);
  transition: opacity 0.15s ease;

  &:active { opacity: 0.8; }

  .btn-save-text {
    font-size: 32rpx;
    font-weight: 600;
    color: $text-color-primary;
  }
}

.btn-reset {
  width: 100%;
  background: $bg-color-card;
  border-radius: 48rpx;
  padding: 24rpx 0;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1rpx solid $border-color;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.04);
  transition: opacity 0.15s ease;

  &:active { opacity: 0.7; }

  .btn-reset-text {
    font-size: 28rpx;
    font-weight: 500;
    color: $info-color;
  }
}

.btn-delete {
  width: 100%;
  padding: 24rpx 0;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: opacity 0.15s ease;

  &:active { opacity: 0.7; }

  .btn-delete-text {
    font-size: 28rpx;
    font-weight: 500;
    color: $error-color;
  }
}

.bottom-safe {
  height: 64rpx;
}
</style>
