<template>
  <view class="guest-page">
    <view v-if="loading" class="loading">加载中...</view>
    <view v-else-if="list.length === 0" class="empty">
      <view class="empty-icon">👤</view>
      <view class="empty-text">暂无常住人</view>
      <view class="empty-tip">添加常住人，下次预订更便捷</view>
    </view>
    <view v-else class="guest-list">
      <view
        v-for="item in list"
        :key="item.id"
        class="guest-item"
        @tap="handleEdit(item)"
      >
        <view class="guest-info">
          <view class="guest-header">
            <view class="guest-name">{{ item.name }}</view>
            <view v-if="item.isDefault" class="default-badge">默认</view>
          </view>
          <view class="guest-phone">{{ item.phone }}</view>
          <view v-if="item.idCard" class="guest-id">{{ maskIdCard(item.idCard) }}</view>
        </view>
        <view class="guest-actions">
          <view class="action-btn" @tap.stop="handleSetDefault(item)" v-if="!item.isDefault">
            设为默认
          </view>
          <view class="action-btn delete" @tap.stop="handleDelete(item)">
            删除
          </view>
        </view>
      </view>
    </view>

    <view class="add-btn" @tap="handleAdd">
      <text class="add-icon">+</text>
      <text class="add-text">添加常住人</text>
    </view>

    <!-- 编辑弹窗 -->
    <u-popup v-model:show="showForm" mode="bottom" :round="20">
      <view class="form-popup">
        <view class="form-header">
          <text class="form-title">{{ formData.id ? '编辑常住人' : '添加常住人' }}</text>
          <text class="form-close" @tap="closeForm">✕</text>
        </view>

        <view class="form-body">
          <view class="form-item">
            <view class="form-label">姓名 <text class="required">*</text></view>
            <input
              class="form-input"
              v-model="formData.name"
              placeholder="请输入姓名"
              maxlength="50"
            />
          </view>

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

          <view class="form-item">
            <view class="form-label">身份证号 <text class="required">*</text></view>
            <input
              class="form-input"
              v-model="formData.idCard"
              placeholder="请输入身份证号"
              maxlength="18"
            />
          </view>

          <view class="form-item">
            <view class="form-label">性别</view>
            <view class="gender-group">
              <view
                class="gender-item"
                :class="{ active: formData.gender === 'male' }"
                @tap="formData.gender = 'male'"
              >
                男
              </view>
              <view
                class="gender-item"
                :class="{ active: formData.gender === 'female' }"
                @tap="formData.gender = 'female'"
              >
                女
              </view>
            </view>
          </view>

          <view class="form-item">
            <view class="form-checkbox" @tap="formData.isDefault = !formData.isDefault">
              <view class="checkbox" :class="{ checked: formData.isDefault }">
                <text v-if="formData.isDefault" class="checkbox-icon">✓</text>
              </view>
              <text class="checkbox-label">设为默认常住人</text>
            </view>
          </view>
        </view>

        <view class="form-footer">
          <button class="submit-btn" @tap="handleSubmit">保存</button>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import {
  getGuestList,
  createGuest,
  updateGuest,
  deleteGuest,
  setDefaultGuest,
} from '@/api/guest';

const list = ref<any[]>([]);
const loading = ref(false);
const showForm = ref(false);
const formData = ref<any>({
  id: null,
  name: '',
  phone: '',
  idCard: '',
  gender: 'male',
  isDefault: false,
});

onMounted(() => {
  fetchList();
});

const fetchList = async () => {
  loading.value = true;
  try {
    const res: any = await getGuestList();
    list.value = res.data?.data || [];
  } catch (e: any) {
    uni.showToast({ title: e.message || '加载失败', icon: 'none' });
  } finally {
    loading.value = false;
  }
};

const maskIdCard = (idCard: string) => {
  if (!idCard || idCard.length < 8) return idCard;
  return idCard.substring(0, 6) + '********' + idCard.substring(idCard.length - 4);
};

const handleAdd = () => {
  formData.value = {
    id: null,
    name: '',
    phone: '',
    idCard: '',
    gender: 'male',
    isDefault: false,
  };
  showForm.value = true;
};

const handleEdit = (item: any) => {
  formData.value = {
    id: item.id,
    name: item.name,
    phone: item.phone,
    idCard: item.idCard || '',
    gender: item.gender || 'male',
    isDefault: item.isDefault,
  };
  showForm.value = true;
};

const closeForm = () => {
  showForm.value = false;
};

const handleSubmit = async () => {
  if (!formData.value.name) {
    uni.showToast({ title: '请输入姓名', icon: 'none' });
    return;
  }
  if (!formData.value.phone || !/^1[3-9]\d{9}$/.test(formData.value.phone)) {
    uni.showToast({ title: '请输入正确的手机号', icon: 'none' });
    return;
  }
  if (!formData.value.idCard) {
    uni.showToast({ title: '请输入身份证号', icon: 'none' });
    return;
  }
  if (!/^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dXx]$/.test(formData.value.idCard)) {
    uni.showToast({ title: '请输入正确的身份证号', icon: 'none' });
    return;
  }

  try {
    const data = {
      name: formData.value.name,
      phone: formData.value.phone,
      idCard: formData.value.idCard,
      gender: formData.value.gender,
      isDefault: formData.value.isDefault,
    };

    if (formData.value.id) {
      await updateGuest(formData.value.id, data);
      uni.showToast({ title: '更新成功', icon: 'success' });
    } else {
      await createGuest(data);
      uni.showToast({ title: '添加成功', icon: 'success' });
    }

    closeForm();
    fetchList();
  } catch (e: any) {
    uni.showToast({ title: e.message || '操作失败', icon: 'none' });
  }
};

const handleSetDefault = async (item: any) => {
  try {
    await setDefaultGuest(item.id);
    uni.showToast({ title: '设置成功', icon: 'success' });
    fetchList();
  } catch (e: any) {
    uni.showToast({ title: e.message || '设置失败', icon: 'none' });
  }
};

const handleDelete = (item: any) => {
  uni.showModal({
    title: '确认删除',
    content: `确定要删除常住人"${item.name}"吗？`,
    success: async (res) => {
      if (res.confirm) {
        try {
          await deleteGuest(item.id);
          uni.showToast({ title: '删除成功', icon: 'success' });
          fetchList();
        } catch (e: any) {
          uni.showToast({ title: e.message || '删除失败', icon: 'none' });
        }
      }
    },
  });
};
</script>

<style scoped lang="scss">
.guest-page {
  min-height: 100vh;
  background: #f5f5f5;
  padding: 24rpx;
  padding-bottom: 160rpx;
}

.loading,
.empty {
  text-align: center;
  padding: 100rpx 0;
}

.empty-icon {
  font-size: 120rpx;
  margin-bottom: 24rpx;
}

.empty-text {
  font-size: 32rpx;
  color: #333;
  margin-bottom: 12rpx;
}

.empty-tip {
  font-size: 26rpx;
  color: #999;
}

.guest-list {
  display: flex;
  flex-direction: column;
  gap: 24rpx;
}

.guest-item {
  background: #fff;
  border-radius: 16rpx;
  padding: 32rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.guest-info {
  flex: 1;
}

.guest-header {
  display: flex;
  align-items: center;
  gap: 12rpx;
  margin-bottom: 12rpx;
}

.guest-name {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.default-badge {
  padding: 4rpx 12rpx;
  background: #1890ff;
  color: #fff;
  font-size: 20rpx;
  border-radius: 8rpx;
}

.guest-phone,
.guest-id {
  font-size: 26rpx;
  color: #666;
  margin-bottom: 8rpx;
}

.guest-actions {
  display: flex;
  gap: 16rpx;
}

.action-btn {
  padding: 12rpx 24rpx;
  background: #f0f0f0;
  color: #333;
  font-size: 24rpx;
  border-radius: 8rpx;

  &.delete {
    color: #ff4d4f;
  }
}

.add-btn {
  position: fixed;
  bottom: 32rpx;
  left: 32rpx;
  right: 32rpx;
  height: 96rpx;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 48rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12rpx;
  color: #fff;
  font-size: 32rpx;
  font-weight: bold;
  box-shadow: 0 8rpx 24rpx rgba(102, 126, 234, 0.4);
}

.add-icon {
  font-size: 40rpx;
}

.form-popup {
  background: #fff;
  border-radius: 32rpx 32rpx 0 0;
  max-height: 80vh;
  display: flex;
  flex-direction: column;
}

.form-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 32rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.form-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.form-close {
  font-size: 40rpx;
  color: #999;
}

.form-body {
  flex: 1;
  overflow-y: auto;
  padding: 32rpx;
}

.form-item {
  margin-bottom: 32rpx;
}

.form-label {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 16rpx;
}

.required {
  color: #ff4d4f;
}

.form-input {
  width: 100%;
  height: 88rpx;
  padding: 0 24rpx;
  background: #f5f5f5;
  border-radius: 12rpx;
  font-size: 28rpx;
  box-sizing: border-box;
}

.gender-group {
  display: flex;
  gap: 24rpx;
}

.gender-item {
  flex: 1;
  height: 88rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f5f5;
  border-radius: 12rpx;
  font-size: 28rpx;
  color: #666;

  &.active {
    background: #1890ff;
    color: #fff;
  }
}

.form-checkbox {
  display: flex;
  align-items: center;
  gap: 12rpx;
}

.checkbox {
  width: 40rpx;
  height: 40rpx;
  border: 2rpx solid #d9d9d9;
  border-radius: 8rpx;
  display: flex;
  align-items: center;
  justify-content: center;

  &.checked {
    background: #1890ff;
    border-color: #1890ff;
  }
}

.checkbox-icon {
  color: #fff;
  font-size: 24rpx;
  font-weight: bold;
}

.checkbox-label {
  font-size: 28rpx;
  color: #333;
}

.form-footer {
  padding: 32rpx;
  border-top: 1rpx solid #f0f0f0;
}

.submit-btn {
  width: 100%;
  height: 88rpx;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: #fff;
  font-size: 32rpx;
  font-weight: bold;
  border-radius: 12rpx;
  border: none;
}
</style>
