index.vue 12.9 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425
<!--
 * @Date: 2025-08-27 17:44:53
 * @LastEditors: hookehuyr hookehuyr@gmail.com
 * @LastEditTime: 2025-08-29 13:58:07
 * @FilePath: /lls_program/src/pages/CreateFamily/index.vue
 * @Description: 文件描述
-->
<template>
  <view class="min-h-screen flex flex-col bg-[#F9FAFB]">
    <!-- <AppHeader title="创建家庭" /> -->
    <view class="flex-1 px-4 py-6 overflow-auto">
      <view class="mb-6">
        <view class="text-gray-600 mb-6">
          请填写家庭信息,创建您的专属家庭空间
        </view>
        <!-- Family Name -->
        <view class="mb-6">
          <view class="bg-white rounded-lg border border-gray-200 p-4">
            <view class="block text-lg font-medium mb-2">家庭名称</view>
            <input
              type="text"
              v-model="familyName"
              class="w-full text-gray-600 focus:outline-none"
              placeholder="请输入家庭名称"
            />
          </view>
        </view>
        <!-- Family Introduction -->
        <view class="mb-6">
          <view class="bg-white rounded-lg border border-gray-200 p-4">
            <view class="block text-lg font-medium mb-2">家庭介绍</view>
            <textarea
              v-model="familyIntro"
              class="w-full text-gray-600 focus:outline-none resize-none"
              placeholder="请输入您家庭的特色、成员特点等家庭标签"
              :rows="2"
            />
          </view>
        </view>
        <!-- District Selection -->
        <view class="mb-6">
          <view class="bg-white rounded-lg border border-gray-200 p-4">
            <view class="block text-lg font-medium mb-4">快来挑选加入哪个区域战队</view>
            <view class="bg-white rounded-xl p-4 border border-gray-200" @click="showDistrictPicker = true">
              <view class="flex justify-between items-center">
                <text :class="{'text-gray-400': !selectedDistrictText, 'text-gray-900': selectedDistrictText}" class="text-base">
                  {{ selectedDistrictText || '请选择区域' }}
                </text>
                <Right size="16" color="#888" />
              </view>
            </view>
          </view>
        </view>
        <!-- Family Motto -->
        <view class="mb-6">
          <view class="bg-white rounded-lg border border-gray-200 p-4">
            <view class="flex justify-between items-center mb-4">
              <view class="block text-lg font-medium">家训口令</view>
              <!-- <view
                @click="generateRandomMotto"
                class="px-3 py-1 bg-blue-100 text-blue-600 rounded-full text-sm"
              >
                随机生成
              </view> -->
            </view>
            <view class="flex gap-2 mb-4">
              <view v-for="(char, index) in familyMotto" :key="index" class="flex-1">
                <view class="w-full aspect-square flex items-center justify-center bg-gray-100 rounded-lg">
                  <input
                    :ref="(el) => (inputRefs[index] = el)"
                    type="text"
                    v-model="familyMotto[index]"
                    :placeholder="familyMottoPlaceholder[index]"
                    @input="(e) => handleInputChange(index, e.target.value)"
                    @focus="focusedIndex = index"
                    @blur="handleBlur(index)"
                    class="w-full h-full bg-transparent text-center"
                    style="font-size: 38rpx;"
                  />
                </view>
              </view>
              <!-- <view class="flex-1 flex items-center justify-center">
                <view class="w-full aspect-square flex items-center justify-center bg-gray-100 rounded-lg text-blue-500">
                  <Edit size="20" />
                </view>
              </view> -->
            </view>
            <view class="flex items-center text-sm text-gray-600">
              <Tips size="16" class="text-yellow-500 mr-2" />
              <view>设置有意义的家训口令,便于家人记忆和加入</view>
            </view>
          </view>
        </view>
        <!-- Family Avatar -->
        <view class="mb-10">
          <view class="bg-white rounded-lg border border-gray-200 p-4">
            <view class="block text-lg font-medium mb-2">
              家庭头像(选填)
            </view>
            <!-- 已上传头像显示 -->
            <view v-if="familyAvatar" class="mb-4">
              <view class="relative inline-block">
                <image
                  :src="familyAvatar"
                  class="w-24 h-24 rounded-lg object-cover"
                  mode="aspectFill"
                  @tap="previewAvatar"
                />
                <view
                  @click="deleteAvatar"
                  class="absolute -top-2 -right-2 w-4 h-4 bg-red-500 rounded-full flex items-center justify-center"
                >
                  <view class="text-white text-xs">×</view>
                </view>
              </view>
            </view>
            <!-- 上传区域 -->
            <view
              v-if="!familyAvatar"
              class="border border-dashed border-gray-200 rounded-lg p-6 flex flex-col items-center justify-center"
              @click="chooseImage"
            >
              <view class="text-gray-400 mb-2">
                <Photograph size="24" />
              </view>
              <view class="text-center text-gray-400">点击上传图片</view>
              <view class="text-center text-gray-400 text-xs mt-1">
                支持图片格式(jpg、png)最大10MB
              </view>
            </view>
          </view>
        </view>
      </view>
      <!-- Submit Button -->
      <view
        @tap="isFormValid ? handleCreateFamily : null"
        :class="[
          'w-full py-3 text-white text-lg font-medium rounded-lg flex items-center justify-center',
          isFormValid ? 'bg-blue-500' : 'bg-gray-300'
        ]"
      >
        创建家庭
      </view>
    </view>



    <!-- 图片预览 -->
    <nut-image-preview
      v-model:show="previewVisible"
      :images="previewImages"
      :init-no="previewIndex"
      @close="closePreview"
    />

    <!-- 区域选择器 -->
    <nut-popup v-model:visible="showDistrictPicker" position="bottom">
      <nut-picker
        v-model="districtValue"
        :columns="districtColumns"
        @confirm="onDistrictConfirm"
        @cancel="showDistrictPicker = false"
        title="选择区域战队"
      ></nut-picker>
    </nut-popup>
  </view>
</template>

<script setup>
import { ref, nextTick, computed } from 'vue';
import Taro from '@tarojs/taro';
import { Edit, Tips, Photograph, Right } from '@nutui/icons-vue-taro';
// import AppHeader from '../../components/AppHeader.vue';
import BASE_URL from '@/utils/config';

const familyName = ref('');
const familyIntro = ref('');
const selectedDistrict = ref(null);
const selectedDistrictText = ref('');
const familyMotto = ref(['', '', '', '']);
const familyMottoPlaceholder = ref(['孝', '敬', '和', '睦']);

// 区域选择器相关
const showDistrictPicker = ref(false);
const districtValue = ref([]);
const districtColumns = ref([
  { text: '黄浦区', value: 310101 },
  { text: '徐汇区', value: 310104 },
  { text: '长宁区', value: 310105 },
  { text: '静安区', value: 310106 },
  { text: '普陀区', value: 310107 },
  { text: '虹口区', value: 310109 },
  { text: '杨浦区', value: 310110 },
  { text: '闵行区', value: 310112 },
  { text: '宝山区', value: 310113 },
  { text: '嘉定区', value: 310114 },
  { text: '浦东新区', value: 310115 },
  { text: '金山区', value: 310116 },
  { text: '松江区', value: 310117 },
  { text: '青浦区', value: 310118 },
  { text: '奉贤区', value: 310120 },
  { text: '崇明区', value: 310151 }
]);
const familyAvatar = ref('');
const focusedIndex = ref(-1);
const inputRefs = ref([]);

const isFormValid = computed(() => {
  return (
    familyName.value.trim() !== '' &&
    familyIntro.value.trim() !== '' &&
    selectedDistrict.value !== null &&
    familyMotto.value.every(char => char.trim() !== '')
  );
});

/**
 * @description 确认选择区域
 * @param {object} param0 - 包含 selectedValue 和 selectedOptions 的对象
 */
const onDistrictConfirm = ({ selectedValue, selectedOptions }) => {
  selectedDistrict.value = selectedValue[0];
  selectedDistrictText.value = selectedOptions.map((option) => option.text).join('');
  showDistrictPicker.value = false;
};

// 图片预览相关
const previewVisible = ref(false);
const previewImages = ref([]);
const previewIndex = ref(0);

// const generateRandomMotto = () => {
//   // 在实际应用中,这里会生成随机家训
//   // 目前仅作为演示使用预设值
//   familyMotto.value = ['爱', '和', '勤', '俭'];
// };

/**
 * 处理输入变化
 */
const handleInputChange = (index, value) => {
  // 只保留第一个有效字符(汉字、数字、大小写字母)
  const validChar = value.match(/[\u4e00-\u9fa5a-zA-Z0-9]/)?.[0] || '';
  familyMotto.value[index] = validChar;

  // 如果输入了有效字符且不是最后一个输入框,自动聚焦下一个
  if (validChar && index < 3) {
    focusedIndex.value = index + 1;
    // 使用 nextTick 确保 DOM 更新后再聚焦
    nextTick(() => {
      if (inputRefs.value[index + 1]) {
        inputRefs.value[index + 1].focus();
      }
    });
  }
};

/**
 * 处理失焦事件
 */
const handleBlur = (index) => {
  focusedIndex.value = -1;
  // 确保只保留有效字符(汉字、数字、大小写字母)
  const value = familyMotto.value[index];
  const validChar = value.match(/[\u4e00-\u9fa5a-zA-Z0-9]/)?.[0] || '';
  familyMotto.value[index] = validChar;
};

/**
 * 显示提示信息
 */
const showToast = (message, type = 'success') => {
  const icon = type === 'error' ? 'error' : 'success';
  Taro.showToast({
    title: message,
    icon: icon,
    duration: 2000
  });
};

/**
 * 选择图片
 */
const chooseImage = () => {
  Taro.chooseImage({
    count: 1,
    sizeType: ['compressed'],
    sourceType: ['album', 'camera'],
    success: function (res) {
      const tempFilePath = res.tempFilePaths[0];

      // 检查文件大小(10MB = 10 * 1024 * 1024 bytes)
      Taro.getFileInfo({
        filePath: tempFilePath,
        success: function (fileInfo) {
          if (fileInfo.size > 10 * 1024 * 1024) {
            showToast('图片大小不能超过10MB', 'error');
            return;
          }
          uploadImage(tempFilePath);
        },
        fail: function () {
          // 如果获取文件信息失败,直接上传
          uploadImage(tempFilePath);
        }
      });
    },
    fail: function () {
      showToast('选择图片失败', 'error');
    }
  });
};

/**
 * 上传图片到服务器
 */
const uploadImage = (filePath) => {
  // 显示上传中提示
  Taro.showLoading({
    title: '上传中',
    mask: true
  });

  wx.uploadFile({
    url: BASE_URL + '/admin/?m=srv&a=upload',
    filePath,
    name: 'file',
    header: {
      'content-type': 'multipart/form-data',
    },
    success: function (res) {
      let upload_data = JSON.parse(res.data);
      Taro.hideLoading({
        success: () => {
          if (res.statusCode === 200) {
            familyAvatar.value = upload_data.data.src;
            showToast('上传成功', 'success');
          } else {
            showToast('服务器错误,稍后重试!', 'error');
          }
        },
      });
    },
    fail: function (res) {
      Taro.hideLoading({
        success: () => {
          showToast('上传失败,稍后重试!', 'error');
        }
      });
    }
  });
};

/**
 * 预览头像
 */
const previewAvatar = () => {
  if (!familyAvatar.value) {
    showToast('暂无图片可预览', 'error');
    return;
  }
  previewImages.value = [{ src: familyAvatar.value }];
  previewIndex.value = 0;
  previewVisible.value = true;
};

/**
 * 删除头像
 */
const deleteAvatar = () => {
  familyAvatar.value = '';
  showToast('头像已删除', 'success');
};

/**
 * 关闭预览
 */
const closePreview = () => {
  previewVisible.value = false;
};

/**
 * 表单验证
 */
const validateForm = () => {
  if (!familyName.value.trim()) {
    showToast('请输入家庭名称', 'error');
    return false;
  }

  if (!familyIntro.value.trim()) {
    showToast('请输入家庭介绍', 'error');
    return false;
  }

  if (!familySize.value) {
    showToast('请选择家庭规模', 'error');
    return false;
  }

  // 检查家训口令是否完整填写
  const mottoComplete = familyMotto.value.every(char => char.trim() !== '');
  if (!mottoComplete) {
    showToast('请完整填写家训口令', 'error');
    return false;
  }

  return true;
};

/**
 * 创建家庭
 */
const handleCreateFamily = () => {
  // 在实际应用中,这里会调用API创建家庭
  // 目前仅作为演示跳转到仪表盘页面
  showToast('家庭创建成功', 'success');

  setTimeout(() => {
    Taro.navigateTo({
      url: '/pages/Dashboard/index'
    });
  }, 1500);
};
</script>