<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 === 0 ? 'off' : ''">
          <text>{{ (form.name || '?')[0] }}</text>
        </view>
        <view class="ac-info">
          <text class="ac-name">{{ form.name }}</text>
          <text class="ac-id" v-if="form.employeeId">工号 {{ form.employeeId }}</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.name"
            placeholder="请输入补货员姓名"
            placeholder-class="field-ph"
          />
        </view>

        <view class="field">
          <text class="field-label">手机号</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.employeeId"
            placeholder="请输入工号"
            placeholder-class="field-ph"
          />
        </view>
      </view>

      <!-- 状态 -->
      <view class="form-card">
        <view class="section-title">账号状态</view>

        <view class="field">
          <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 === 0 }"
              @click="form.status = 0"
            >
              <view class="so-dot off"></view>
              <text>禁用</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 绑定信息（仅编辑模式） -->
      <view class="form-card" v-if="isEdit">
        <view class="section-title">设备与绑定</view>

        <view class="field" @click="handleBindDevices">
          <view class="field-picker-row">
            <text class="field-picker-label">绑定设备</text>
            <view class="field-picker-right">
              <text class="picker-val">{{ boundDeviceCount > 0 ? boundDeviceCount + '台设备' : '未绑定' }}</text>
              <view class="picker-arrow"></view>
            </view>
          </view>
        </view>

        <view class="field" @click="handleGenBindingCode">
          <view class="field-picker-row">
            <text class="field-picker-label">微信绑定码</text>
            <view class="field-picker-right">
              <text class="picker-val" :class="{ active: !form.wechatOpenid }">{{ form.wechatOpenid ? '已绑定' : '生成绑定码' }}</text>
              <view class="picker-arrow"></view>
            </view>
          </view>
        </view>
      </view>

      <!-- 操作按钮 -->
      <view class="btn-area">
        <view class="btn-save" @click="handleSave">
          <text class="btn-save-text">{{ isEdit ? '保存修改' : '创建补货员' }}</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 class="overlay" v-if="showCodePanel" @click="showCodePanel = false">
      <view class="code-panel" @click.stop>
        <text class="cp-title">微信绑定码</text>
        <text class="cp-sub">24小时内有效，分享给补货员扫码绑定</text>
        <view class="cp-code" @click="copyCode">
          <text class="cp-code-text">{{ formatCode(bindingCode) }}</text>
        </view>
        <text class="cp-hint">点击绑定码可复制</text>
        <view class="cp-close" @click="showCodePanel = false">
          <text class="cp-close-text">关闭</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import NavBar from '@/components/NavBar.vue';
import {
  createReplenisher,
  updateReplenisher,
  getReplenisherById,
  deleteReplenisher,
  getBoundDevices,
  generateBindingCode,
  type ReplenisherForm
} from '@/api/replenisher';

const isEdit = ref(false);
const editId = ref<string | null>(null);
const saving = ref(false);
const boundDeviceCount = ref(0);

const form = reactive<ReplenisherForm>({
  name: '',
  phone: '',
  employeeId: '',
  status: 1
});

// 绑定码弹窗
const showCodePanel = ref(false);
const bindingCode = ref('');

const loadDetail = async (id: string) => {
  try {
    const data = await getReplenisherById(id);
    if (data) {
      form.id = data.id;
      form.name = data.name || '';
      form.phone = data.phone || '';
      form.employeeId = data.employeeId || '';
      form.status = data.status ?? 1;
      form.wechatOpenid = data.wechatOpenid || '';
      boundDeviceCount.value = data.boundDeviceCount || 0;
    }
  } catch (e) {
    uni.showToast({ title: '加载失败', icon: 'none' });
  }
};

const validate = (): string | null => {
  if (!form.name || !form.name.trim()) return '请输入姓名';
  if (form.phone && !/^1[3-9]\d{9}$/.test(form.phone.trim())) 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 {
    if (isEdit.value) {
      await updateReplenisher(editId.value!, {
        name: form.name.trim(),
        phone: form.phone?.trim() || undefined,
        employeeId: form.employeeId?.trim() || undefined,
        status: form.status
      });
    } else {
      await createReplenisher({
        name: form.name.trim(),
        phone: form.phone?.trim() || undefined,
        employeeId: form.employeeId?.trim() || undefined
      });
    }
    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 handleDelete = () => {
  uni.showModal({
    title: '确认删除',
    content: `确认删除补货员「${form.name}」？删除后不可恢复。`,
    success: async (res) => {
      if (!res.confirm) return;
      try {
        await deleteReplenisher(editId.value!);
        uni.showToast({ title: '已删除', icon: 'success' });
        setTimeout(() => {
          uni.navigateBack();
        }, 1200);
      } catch (e) {
        uni.showToast({ title: '删除失败', icon: 'none' });
      }
    }
  });
};

const handleBindDevices = () => {
  uni.navigateTo({ url: `/pages/replenisher/bind-device?id=${editId.value}&name=${encodeURIComponent(form.name)}` });
};

const handleGenBindingCode = async () => {
  if (!editId.value) return;
  uni.showLoading({ title: '生成中...', mask: true });
  try {
    const data = await generateBindingCode(editId.value);
    bindingCode.value = data.bindingCode || '';
    showCodePanel.value = true;
  } catch (e) {
    uni.showToast({ title: '生成失败', icon: 'none' });
  } finally {
    uni.hideLoading();
  }
};

const formatCode = (code: string): string => {
  if (!code) return '';
  return code.replace(/(.{4})/g, '$1 ').trim();
};

const copyCode = () => {
  if (!bindingCode.value) return;
  uni.setClipboardData({
    data: bindingCode.value,
    success: () => {
      uni.showToast({ title: '绑定码已复制', icon: 'success' });
    }
  });
};

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

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

  if (id) {
    isEdit.value = true;
    editId.value = id;
    uni.setNavigationBarTitle({ title: '编辑补货员' });
    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;
}

.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-id {
  font-size: 24rpx;
  color: $text-color-muted;
}

.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;
}

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

// ====== Picker row ======
.field-picker-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.field-picker-label {
  font-size: 28rpx;
  font-weight: 600;
  color: $text-color-primary;
}

.field-picker-right {
  display: flex;
  align-items: center;
  gap: 8rpx;
}

.picker-val {
  font-size: 28rpx;
  color: $text-color-muted;

  &.active {
    color: $primary-color-dark;
  }
}

.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;
}

// ====== 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-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;
}

// ====== Binding code overlay ======
.overlay {
  position: fixed;
  inset: 0;
  background: rgba(0, 0, 0, 0.45);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 100;
  padding: 48rpx;
}

.code-panel {
  background: $bg-color-card;
  border-radius: 24rpx;
  padding: 48rpx 40rpx 40rpx;
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16rpx;
}

.cp-title {
  font-size: 36rpx;
  font-weight: 700;
  color: $text-color-primary;
}

.cp-sub {
  font-size: 24rpx;
  color: $text-color-muted;
  text-align: center;
  line-height: 1.5;
}

.cp-code {
  background: $bg-color-page;
  border: 2rpx dashed $primary-color;
  border-radius: 12rpx;
  padding: 24rpx 32rpx;
  margin-top: 8rpx;
  width: 100%;
  box-sizing: border-box;
}

.cp-code-text {
  font-size: 32rpx;
  font-weight: 700;
  font-family: 'Courier New', Courier, monospace;
  letter-spacing: 4rpx;
  color: $primary-color-dark;
  text-align: center;
  word-break: break-all;
  user-select: all;
}

.cp-hint {
  font-size: 22rpx;
  color: $text-color-placeholder;
}

.cp-close {
  margin-top: 16rpx;
  padding: 16rpx 64rpx;
  background: $bg-color-page;
  border-radius: 40rpx;

  &:active { opacity: 0.7; }
}

.cp-close-text {
  font-size: 28rpx;
  color: $text-color-secondary;
  font-weight: 500;
}
</style>
