index.vue 13.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 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457
<!--
 * @Date: 2025-08-27 17:44:53
 * @LastEditors: hookehuyr hookehuyr@gmail.com
 * @LastEditTime: 2025-09-02 11:23:27
 * @FilePath: /lls_program/src/pages/EditFamily/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="请输入家庭名称(最多10个字)"
              @blur="validateFamilyName"
              maxlength="10"
            />
            <view v-if="familyNameError" class="text-red-500 text-sm mt-2">{{ familyNameError }}</view>
          </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="请输入您家庭的特色、成员特点等家庭标签(最多100个字)"
              :rows="2"
              @blur="validateFamilyIntro"
              maxlength="100"
            />
            <view v-if="familyIntroError" class="text-red-500 text-sm mt-2">{{ familyIntroError }}</view>
          </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
                    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;"
                    :cursorSpacing="100"
                  />
                </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 Cover -->
        <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 class="mb-4">
              <view class="relative">
                <image
                  :src="familyAvatar || defaultFamilyCover"
                  class="w-full h-48 rounded-lg object-cover"
                  mode="aspectFill"
                  @tap="previewAvatar"
                />
                <view
                  v-if="familyAvatar"
                  @click="deleteAvatar"
                  class="absolute -top-2 -right-2 w-6 h-6 bg-red-500 rounded-full flex items-center justify-center"
                >
                  <view class="text-white text-sm">×</view>
                </view>
                <view
                  @click="chooseImage"
                  class="absolute bottom-2 right-2 px-3 py-1 bg-black bg-opacity-50 text-white text-sm rounded-full flex items-center"
                >
                  <Photograph size="14" class="mr-1" />
                  {{ familyAvatar ? '更换' : '上传' }}
                </view>
              </view>
            </view>
            <!-- 上传提示 -->
            <view class="text-center text-gray-400 text-sm">
              支持图片格式(jpg、png)最大5MB
            </view>
          </view>
        </view>
      </view>
      <!-- Submit Button -->
      <view
        @click="handleSaveFamily"
        class="w-full py-3 bg-blue-500 text-white text-lg font-medium rounded-lg flex items-center justify-center"
      >
        保存
      </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, onMounted } 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';
import defaultFamilyCoverSvg from '@/assets/images/default-family-cover.png';

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

// 字数验证错误信息
const familyNameError = ref('');
const familyIntroError = 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 defaultFamilyCover = ref(defaultFamilyCoverSvg);

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

onMounted(() => {
  Taro.setNavigationBarTitle({ title: '编辑家庭' });
  // Mock data for current family information
  familyName.value = '幸福一家';
  familyIntro.value = '我们是相亲相爱的一家人';
  districtValue.value = [310104]; // 模拟勾选项已选择徐汇区
  // 需要提交的数据集
  selectedDistrict.value = 310104; // 模拟已选择徐汇区
  selectedDistrictText.value = districtColumns.value.find(item => item.value === selectedDistrict.value).text;
  familyMotto.value = ['家', '和', '万', '事'];
  familyAvatar.value = 'https://img.yzcdn.cn/vant/cat.jpeg';
});

/**
 * @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 handleInputChange = (index, value) => {
  // 只保留第一个有效字符(汉字、数字、大小写字母)
  const validChar = value.match(/[\u4e00-\u9fa5a-zA-Z0-9]/)?.[0] || '';
  familyMotto.value[index] = validChar;
};

/**
 * 处理失焦事件
 */
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') => {
  Taro.showToast({
    title: message,
    icon: type,
    duration: 2000
  });
};

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

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

/**
 * 上传图片到服务器
 */
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('服务器错误,稍后重试!', 'none');
          }
        },
      });
    },
    fail: function (res) {
      Taro.hideLoading({
        success: () => {
          showToast('上传失败,稍后重试!', 'none');
        }
      });
    }
  });
};

/**
 * 预览头像
 */
const previewAvatar = () => {
  const imageToPreview = familyAvatar.value || defaultFamilyCover.value;
  previewImages.value = [{ src: imageToPreview }];
  previewIndex.value = 0;
  previewVisible.value = true;
};

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

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

/**
 * 验证家庭名称字数
 */
const validateFamilyName = () => {
  familyNameError.value = '';
  if (familyName.value.length > 10) {
    familyNameError.value = '家庭名称不能超过10个字';
  }
};

/**
 * 验证家庭介绍字数
 */
const validateFamilyIntro = () => {
  familyIntroError.value = '';
  if (familyIntro.value.length > 100) {
    familyIntroError.value = '家庭介绍不能超过100个字';
  }
};

/**
 * 表单验证
 */
const validateForm = () => {
  // 先验证字数
  validateFamilyName();
  validateFamilyIntro();

  if (!familyName.value.trim()) {
    showToast('请输入家庭名称', 'none');
    return false;
  }

  if (familyName.value.length > 10) {
    Taro.showModal({
      title: '提示',
      content: '家庭名称不能超过10个字,请重新输入',
      showCancel: false
    });
    return false;
  }

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

  if (familyIntro.value.length > 100) {
    Taro.showModal({
      title: '提示',
      content: '家庭介绍不能超过100个字,请重新输入',
      showCancel: false
    });
    return false;
  }

  if (!selectedDistrict.value) {
    showToast('请选择区域战队', 'none');
    return false;
  }

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

  return true;
};

/**
 * 保存家庭信息
 */
const handleSaveFamily = () => {
  if (!validateForm()) {
    return;
  }

  // 在实际应用中,这里会调用API保存家庭信息
  showToast('家庭信息保存成功', 'success');

  setTimeout(() => {
    Taro.navigateBack();
  }, 1500);
};
</script>