<template>
  <view class="page-room-form">
    <!-- 基本信息 -->
    <view class="form-card">
      <view class="card-header">
        <text class="card-title">基本信息</text>
      </view>

      <view class="form-group">
        <view class="field-label">
          <text class="label-text">房源名称</text>
          <text class="label-required">*</text>
        </view>
        <input
          class="field-input"
          type="text"
          v-model="form.name"
          placeholder="如：豪华海景大床房"
          maxlength="100"
        />
      </view>

      <view class="form-row">
        <view class="form-group half">
          <view class="field-label">
            <text class="label-text">房型</text>
            <text class="label-required">*</text>
          </view>
          <picker :range="typeOptions" range-key="label" :value="typeIndex" @change="onTypeChange">
            <view class="field-picker">
              <text class="picker-text">{{ typeOptions[typeIndex].label }}</text>
              <text class="picker-arrow">▼</text>
            </view>
          </picker>
        </view>

        <view class="form-group half">
          <view class="field-label">
            <text class="label-text">价格</text>
            <text class="label-required">*</text>
          </view>
          <view class="field-input-wrapper">
            <text class="input-prefix">¥</text>
            <input class="field-input with-prefix" type="digit" v-model="form.price" placeholder="0" />
            <text class="input-suffix">/晚</text>
          </view>
        </view>
      </view>

      <view class="form-row">
        <view class="form-group half">
          <view class="field-label">
            <text class="label-text">床型</text>
          </view>
          <picker :range="bedTypeOptions" range-key="label" :value="bedTypeIndex" @change="onBedTypeChange">
            <view class="field-picker">
              <text class="picker-text">{{ bedTypeOptions[bedTypeIndex].label }}</text>
              <text class="picker-arrow">▼</text>
            </view>
          </picker>
        </view>

        <view class="form-group half">
          <view class="field-label">
            <text class="label-text">面积</text>
          </view>
          <view class="field-input-wrapper">
            <input class="field-input" type="digit" v-model="form.area" placeholder="0" />
            <text class="input-suffix">m²</text>
          </view>
        </view>
      </view>

      <view class="form-row">
        <view class="form-group half">
          <view class="field-label">
            <text class="label-text">最多入住</text>
          </view>
          <view class="field-input-wrapper">
            <input class="field-input" type="number" v-model="form.maxGuests" placeholder="1" />
            <text class="input-suffix">人</text>
          </view>
        </view>

        <view class="form-group half">
          <view class="field-label">
            <text class="label-text">取消政策</text>
          </view>
          <picker :range="policyOptions" range-key="label" :value="policyIndex" @change="onPolicyChange">
            <view class="field-picker">
              <text class="picker-text">{{ policyOptions[policyIndex].label }}</text>
              <text class="picker-arrow">▼</text>
            </view>
          </picker>
        </view>
      </view>
    </view>

    <!-- 房源图片 -->
    <view class="form-card">
      <view class="card-header">
        <text class="card-title">房源图片</text>
        <text class="card-subtitle">{{ imageList.length }}/20</text>
      </view>

      <view class="image-grid">
        <view v-for="(img, i) in imageList" :key="i" class="image-box">
          <image class="room-image" :src="img" mode="aspectFill" />
          <view v-if="i === 0" class="cover-badge">封面</view>
          <view class="delete-btn" @tap="removeImage(i)">
            <text class="delete-icon">×</text>
          </view>
        </view>
        <view v-if="imageList.length < 20" class="image-upload" @tap="chooseImage">
          <text class="upload-icon">+</text>
          <text class="upload-text">添加图片</text>
        </view>
      </view>
      <text class="field-hint">第一张为封面图，建议上传至少3张图片</text>
    </view>

    <!-- 设施服务 -->
    <view class="form-card">
      <view class="card-header">
        <text class="card-title">设施服务</text>
        <text class="card-subtitle">已选 {{ form.facilities.length }}</text>
      </view>

      <view class="facility-grid">
        <view
          v-for="f in facilityOptions"
          :key="f"
          :class="['facility-item', { selected: form.facilities.includes(f) }]"
          @tap="toggleFacility(f)"
        >
          <text class="facility-name">{{ f }}</text>
        </view>
      </view>
    </view>

    <!-- 房源描述 -->
    <view class="form-card">
      <view class="card-header">
        <text class="card-title">房源描述</text>
      </view>

      <textarea
        class="field-textarea"
        v-model="form.description"
        placeholder="介绍房源的特色、周边环境、交通等信息，让客人更了解您的房源"
        maxlength="1000"
      />
      <text class="field-hint">{{ form.description.length }}/1000</text>
    </view>

    <!-- 底部按钮 -->
    <view class="bottom-bar">
      <button class="submit-button" :disabled="loading" @tap="handleSubmit">
        {{ loading ? '保存中...' : '保存房源' }}
      </button>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { createMerchantRoom, updateMerchantRoom, getMerchantRoom } from '@/api/seller/room';
import { chooseAndUpload } from '@/utils/upload';

const loading = ref(false);
const roomId = ref<number | null>(null);
const imageList = ref<string[]>([]);

const typeOptions = [
  { label: '酒店', value: 'hotel' },
  { label: '民宿', value: 'homestay' },
  { label: '公寓', value: 'apartment' },
  { label: '青旅', value: 'hostel' },
];
const typeIndex = ref(0);

const bedTypeOptions = [
  { label: '大床房', value: '大床房' },
  { label: '双床房', value: '双床房' },
  { label: '三床房', value: '三床房' },
  { label: '榻榻米', value: '榻榻米' },
  { label: '其他', value: '其他' },
];
const bedTypeIndex = ref(0);

const policyOptions = [
  { label: '灵活取消', value: 'flexible' },
  { label: '免费取消', value: 'free' },
  { label: '严格取消', value: 'strict' },
];
const policyIndex = ref(0);

const facilityOptions = ['WiFi', '空调', '热水', '电视', '冰箱', '洗衣机', '停车场', '电梯', '厨房', '阳台', '泳池', '健身房'];

const form = ref({
  name: '',
  type: 'hotel',
  price: '',
  bedType: '大床房',
  area: '',
  maxGuests: '',
  cancelPolicy: 'flexible',
  facilities: [] as string[],
  description: '',
});

onMounted(() => {
  const pages = getCurrentPages();
  const page = pages[pages.length - 1] as any;
  const id = page.options?.id || page.$page?.options?.id;
  if (id) {
    roomId.value = Number(id);
    uni.setNavigationBarTitle({ title: '编辑房源' });
    loadRoom(Number(id));
  } else {
    uni.setNavigationBarTitle({ title: '新建房源' });
  }
});

async function loadRoom(id: number) {
  try {
    const res = await getMerchantRoom(id);
    const room = res.data;
    form.value = {
      name: room.name || '',
      type: room.type || 'hotel',
      price: room.price?.toString() || '',
      bedType: room.bedType || '大床房',
      area: room.area?.toString() || '',
      maxGuests: room.maxGuests?.toString() || '',
      cancelPolicy: room.cancelPolicy || 'flexible',
      facilities: room.facilities || [],
      description: room.description || '',
    };
    imageList.value = room.images || [];
    typeIndex.value = typeOptions.findIndex((t) => t.value === room.type);
    bedTypeIndex.value = bedTypeOptions.findIndex((b) => b.value === room.bedType) || 0;
    policyIndex.value = policyOptions.findIndex((p) => p.value === room.cancelPolicy);
  } catch (e) {
    console.error(e);
  }
}

function onTypeChange(e: any) {
  typeIndex.value = e.detail.value;
  form.value.type = typeOptions[e.detail.value].value;
}

function onBedTypeChange(e: any) {
  bedTypeIndex.value = e.detail.value;
  form.value.bedType = bedTypeOptions[e.detail.value].value;
}

function onPolicyChange(e: any) {
  policyIndex.value = e.detail.value;
  form.value.cancelPolicy = policyOptions[e.detail.value].value;
}

function toggleFacility(f: string) {
  const idx = form.value.facilities.indexOf(f);
  if (idx > -1) {
    form.value.facilities.splice(idx, 1);
  } else {
    form.value.facilities.push(f);
  }
}

async function chooseImage() {
  const remaining = 20 - imageList.value.length;
  if (remaining <= 0) {
    uni.showToast({ title: '最多20张', icon: 'none' });
    return;
  }
  try {
    uni.showLoading({ title: '上传中' });
    const urls = await chooseAndUpload({ count: remaining, useSellerToken: true });
    imageList.value.push(...urls);
  } catch (err: any) {
    uni.showToast({ title: err.message || '上传失败', icon: 'none' });
  } finally {
    uni.hideLoading();
  }
}

function removeImage(index: number) {
  imageList.value.splice(index, 1);
}

function validate(): boolean {
  if (!form.value.name) {
    uni.showToast({ title: '请输入房源名称', icon: 'none' });
    return false;
  }
  if (!form.value.price || Number(form.value.price) <= 0) {
    uni.showToast({ title: '请输入有效价格', icon: 'none' });
    return false;
  }
  if (imageList.value.length === 0) {
    uni.showToast({ title: '请至少上传一张图片', icon: 'none' });
    return false;
  }
  return true;
}

async function handleSubmit() {
  if (!validate()) return;
  loading.value = true;

  const data = {
    name: form.value.name,
    type: form.value.type,
    price: Number(form.value.price),
    bedType: form.value.bedType || undefined,
    area: form.value.area ? Number(form.value.area) : undefined,
    maxGuests: form.value.maxGuests ? Number(form.value.maxGuests) : undefined,
    cancelPolicy: form.value.cancelPolicy,
    facilities: form.value.facilities,
    images: imageList.value,
    coverImage: imageList.value[0] || '',
    description: form.value.description || undefined,
  };

  try {
    if (roomId.value) {
      await updateMerchantRoom(roomId.value, data);
      uni.showToast({ title: '更新成功', icon: 'success' });
    } else {
      await createMerchantRoom(data);
      uni.showToast({ title: '创建成功', icon: 'success' });
    }
    setTimeout(() => {
      uni.navigateBack();
    }, 1500);
  } catch (e: any) {
    uni.showToast({ title: e.message || '操作失败', icon: 'none' });
  } finally {
    loading.value = false;
  }
}
</script>

<style lang="scss" scoped>
@import '@/static/styles/common.scss';

.page-room-form {
  min-height: 100vh;
  background: #f5f6fa;
  padding: 24rpx;
  padding-bottom: 140rpx;
}

// 表单卡片
.form-card {
  background: #fff;
  border-radius: 16rpx;
  padding: 32rpx 24rpx;
  margin-bottom: 24rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04);
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 28rpx;
  padding-bottom: 20rpx;
  border-bottom: 1rpx solid #f1f3f5;
}

.card-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #1a1a1a;
}

.card-subtitle {
  font-size: 24rpx;
  color: #868e96;
}

// 表单组
.form-group {
  margin-bottom: 28rpx;

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

  &.half {
    flex: 1;
  }
}

.form-row {
  display: flex;
  gap: 20rpx;
}

.field-label {
  display: flex;
  align-items: center;
  margin-bottom: 12rpx;
}

.label-text {
  font-size: 28rpx;
  color: #495057;
  font-weight: 500;
}

.label-required {
  color: #fa5252;
  margin-left: 4rpx;
  font-size: 28rpx;
}

// 输入框
.field-input {
  width: 100%;
  height: 80rpx;
  background: #f8f9fa;
  border-radius: 12rpx;
  padding: 0 20rpx;
  font-size: 28rpx;
  color: #212529;
  border: 1rpx solid #e9ecef;
  transition: all 0.2s;
  box-sizing: border-box;

  &:focus {
    border-color: #4263eb;
    background: #fff;
  }

  &.with-prefix {
    padding-left: 56rpx;
  }
}

.field-input-wrapper {
  position: relative;
  display: flex;
  align-items: center;
  background: #f8f9fa;
  border-radius: 12rpx;
  border: 1rpx solid #e9ecef;
  transition: all 0.2s;
  overflow: hidden;

  &:focus-within {
    border-color: #4263eb;
    background: #fff;
  }

  .field-input {
    flex: 1;
    min-width: 0;
    border: none;
    background: transparent;
    padding: 0 12rpx;
  }
}

.input-prefix,
.input-suffix {
  flex-shrink: 0;
  font-size: 26rpx;
  color: #868e96;
  padding: 0 16rpx;
  font-weight: 500;
}

// 选择器
.field-picker {
  height: 80rpx;
  background: #f8f9fa;
  border-radius: 12rpx;
  padding: 0 20rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border: 1rpx solid #e9ecef;
}

.picker-text {
  font-size: 28rpx;
  color: #212529;
}

.picker-arrow {
  font-size: 20rpx;
  color: #adb5bd;
}

// 文本域
.field-textarea {
  width: 100%;
  min-height: 200rpx;
  background: #f8f9fa;
  border-radius: 12rpx;
  padding: 20rpx;
  font-size: 28rpx;
  color: #212529;
  border: 1rpx solid #e9ecef;
  line-height: 1.6;
  transition: all 0.2s;
  box-sizing: border-box;

  &:focus {
    border-color: #4263eb;
    background: #fff;
  }
}

.field-hint {
  display: block;
  font-size: 24rpx;
  color: #868e96;
  margin-top: 12rpx;
}

// 图片网格
.image-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16rpx;
  margin-bottom: 12rpx;
}

.image-box {
  position: relative;
  width: 100%;
  padding-bottom: 100%;
  border-radius: 12rpx;
  overflow: hidden;
}

.room-image {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  border-radius: 12rpx;
}

.cover-badge {
  position: absolute;
  top: 8rpx;
  left: 8rpx;
  background: rgba(66, 99, 235, 0.9);
  color: #fff;
  font-size: 20rpx;
  padding: 4rpx 12rpx;
  border-radius: 6rpx;
  font-weight: 500;
}

.delete-btn {
  position: absolute;
  top: 8rpx;
  right: 8rpx;
  width: 44rpx;
  height: 44rpx;
  background: rgba(0, 0, 0, 0.6);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  backdrop-filter: blur(4rpx);

  &:active {
    background: rgba(0, 0, 0, 0.8);
  }
}

.delete-icon {
  color: #fff;
  font-size: 32rpx;
  line-height: 1;
}

.image-upload {
  position: relative;
  width: 100%;
  padding-bottom: 100%;
  background: #f8f9fa;
  border-radius: 12rpx;
  border: 2rpx dashed #dee2e6;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;

  &:active {
    background: #e9ecef;
  }
}

.upload-icon {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -70%);
  font-size: 56rpx;
  color: #adb5bd;
}

.upload-text {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, 40%);
  font-size: 22rpx;
  color: #adb5bd;
}

// 设施网格
.facility-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16rpx;
}

.facility-item {
  background: #f8f9fa;
  border-radius: 12rpx;
  padding: 24rpx 16rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 2rpx solid #e9ecef;
  transition: all 0.2s;

  &:active {
    transform: scale(0.95);
  }

  &.selected {
    background: #e7f5ff;
    border-color: #4263eb;

    .facility-name {
      color: #4263eb;
      font-weight: 600;
    }
  }
}

.facility-name {
  font-size: 26rpx;
  color: #495057;
}

// 底部按钮
.bottom-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: #fff;
  padding: 20rpx 24rpx;
  padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
  box-shadow: 0 -4rpx 12rpx rgba(0, 0, 0, 0.04);
}

.submit-button {
  width: 100%;
  height: 88rpx;
  background: linear-gradient(135deg, #4c6ef5 0%, #4263eb 100%);
  color: #fff;
  border-radius: 12rpx;
  font-size: 30rpx;
  font-weight: 600;
  border: none;
  box-shadow: 0 8rpx 20rpx rgba(66, 99, 235, 0.25);
  letter-spacing: 2rpx;

  &:active:not([disabled]) {
    background: linear-gradient(135deg, #3b5bdb 0%, #364fc7 100%);
    transform: translateY(2rpx);
    box-shadow: 0 4rpx 12rpx rgba(66, 99, 235, 0.3);
  }

  &[disabled] {
    background: #e9ecef;
    color: #adb5bd;
    box-shadow: none;
  }
}
</style>
