FormAdd.uvue 23.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 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821
<template>
  <view class="form-add-root" :style="pageStyleVars">
    <!-- 与接待中心 center.uvue 一致:安全区 + 固定导航占位,避免首屏表单被导航栏遮挡 -->
    <view class="reception-safe-top-spacer" :style="receptionSafeTopSpacerStyle"></view>
    <un-navbar title="客户档案" @leftClick="handleClose" :titleStyle="formAddNavbarTitleStyle" />
    <view class="reception-navbar-spacer"></view>
    <view class="form-add-wrap">
      <view class="form-add-body">
        <un-form :model="formData" labelWidth="80" labelAlign="left" borderBottom>
          <un-form-item prop="ownerName" :customStyle="formAddFormItemCustomStyle">
            <template #label>
              <text class="form-add-label">车主姓名</text>
            </template>
            <un-input
              v-model="formData['ownerName']"
              border="none"
              inputAlign="right"
              placeholder="请输入车主姓名"
              :fontSize="formAddInputFontSize"
              :placeholderStyle="formAddPlaceholderStyle"
              :maxlength="50"
            ></un-input>
          </un-form-item>

          <un-form-item prop="ownerPhone" :customStyle="formAddFormItemCustomStyle">
            <template #label>
              <text class="form-add-label">车主电话</text>
            </template>
            <un-input
              v-model="formData['ownerPhone']"
              border="none"
              type="tel"
              inputAlign="right"
              placeholder="请输入车主电话"
              :fontSize="formAddInputFontSize"
              :placeholderStyle="formAddPlaceholderStyle"
              :maxlength="11"
            ></un-input>
          </un-form-item>

          <un-form-item prop="brandModel" :customStyle="formAddFormItemCustomStyle">
            <template #label>
              <text class="form-add-label">品牌车型</text>
            </template>
            <view class="form-add-link-cell" @click="brandCascaderShow = true">
              <text
                :class="[
                  'form-add-link-cell__value',
                  formData.brandModel !== '' ? 'form-add-link-cell__value--has' : 'form-add-link-cell__value--empty',
                ]"
              >
                {{ formData.brandModel !== '' ? formData.brandModel : '请选择品牌车型' }}
              </text>
              <un-icon name="arrow-right" color="#a1a1a1"></un-icon>
            </view>
          </un-form-item>
          <un-form-item prop="receptionSceneName" :customStyle="formAddFormItemCustomStyle">
            <template #label>
              <text class="form-add-label">接待场景</text>
            </template>
            <view class="form-add-link-cell" @click="sceneSelectShow = true">
              <text
                :class="[
                  'form-add-link-cell__value',
                  formData.receptionSceneName !== ''
                    ? 'form-add-link-cell__value--has'
                    : 'form-add-link-cell__value--empty',
                ]"
              >
                {{ formData.receptionSceneName !== '' ? formData.receptionSceneName : '请选择接待场景' }}
              </text>
              <un-icon name="arrow-right" color="#a1a1a1"></un-icon>
            </view>
          </un-form-item>

          <un-form-item prop="arrivalDate" :customStyle="formAddFormItemCustomStyle">
            <template #label>
              <text class="form-add-label">到店日期</text>
            </template>
            <view class="form-add-link-cell" @click="onOpenDatePicker">
              <text
                :class="[
                  'form-add-link-cell__value',
                  formData.arrivalDate !== '' ? 'form-add-link-cell__value--has' : 'form-add-link-cell__value--empty',
                ]"
              >
                {{ formData.arrivalDate !== '' ? formData.arrivalDate : '请选择到店日期' }}
              </text>
              <un-icon name="arrow-right" color="#a1a1a1"></un-icon>
            </view>
          </un-form-item>

          <un-form-item prop="customerTagName" :customStyle="formAddFormItemCustomStyle">
            <template #label>
              <text class="form-add-label">客户标签</text>
            </template>
            <view
              class="form-add-link-cell"
              @click="customerTagsSelectShow = true"
              :style="{ position: 'relative', zIndex: 10 }"
            >
              <text
                :class="[
                  'form-add-link-cell__value',
                  formData.customerTagName !== ''
                    ? 'form-add-link-cell__value--has'
                    : 'form-add-link-cell__value--empty',
                ]"
              >
                {{ formData.customerTagName !== '' ? formData.customerTagName : '请选择客户标签' }}
              </text>
              <un-icon name="arrow-right" color="#a1a1a1"></un-icon>
            </view>
          </un-form-item>
        </un-form>
      </view>
      <view class="form-add-footer">
        <view class="btn cancel-btn" @click="handleClose">
          <text class="btn-text btn-text-cancel">取消</text>
        </view>
        <view class="btn submit-btn" @click="handleSubmit">
          <text class="btn-text btn-text-submit">提交</text>
        </view>
      </view>
    </view>
    <CarBrands
      ref="carBrandSelectRef"
      @select="onCarBrandsSelect"
      @close="onCarBrandClose"
    />
    <SenceSelect
      ref="sceneSelectRef"
      :echo-data="{ receptionScenario: formData.receptionSceneName } as UTSJSONObject"
      echo-key="receptionScenario"
      @confirm="onSceneConfirm"
      @close="onSceneClose"
    />
    <CustomerTags
      ref="customerTagsSelectRef"
      :echo-data="{ customerTags: formData.customerTagName } as UTSJSONObject"
      echo-key="customerTags"
      @confirm="onCustomerTagsConfirm"
      @close="onCustomerTagsClose"
    />
    <!-- 到店日期选择器 -->
    <un-datetime-picker
      :show="datePickerShow"
      v-model="arrivalDateValue"
      mode="date"
      title="选择到店日期"
      valueFormat="YYYY-MM-DD"
      @confirm="onDatePickerConfirm"
      @cancel="datePickerShow = false"
      @close="datePickerShow = false"
    />
  </view>
</template>

<script setup lang="uts">
import { ref, watch, nextTick, computed, onMounted, type Ref } from 'vue'
import { ComponentPublicInstance } from 'vue'
import CarBrands from '@/components/CarBrands.uvue'
import SenceSelect from './filters/SenceSelect.uvue'
import CustomerTags from './filters/CustomerTags.uvue'
import { saveVisitsInfo, updateVisitsInfo, findVisitsInfo } from '@/api/receiption.uts'
import { storage } from '@/utils/storage.uts'
import { useScreenVars } from '@/services/adapter/hooks/index.uts'
import pageVars from './styles/index.vars.uts'

const phoneRex = /^1[3-9]\d{9}$/

// 使用 index.vars.uts + common.scss 约定的 CSS 变量体系做自适应(方向/分辨率由 useScreenVars 内部决定)
const pageStyleVars = useScreenVars(pageVars as UTSJSONObject)
{/* const pageStyleVars = computed((): Any => {
  const sv = screenVarsHook.screenVars as Ref<UTSJSONObject>
  return sv.value as Any
}) */}

const formAddFormItemCustomStyle = {
  height: 'var(--reception-form-add-item-height)',
  paddingTop: 'var(--reception-form-add-item-padding-top)',
  paddingBottom: 'var(--reception-form-add-item-padding-bottom)',
} as UTSJSONObject

const formAddNavbarTitleStyle = computed((): UTSJSONObject => {
  return {
    fontSize: 'var(--reception-form-add-navbar-title-font-size)',
  } as UTSJSONObject
})

const formAddPlaceholderStyle = {
  fontSize: 'var(--reception-form-add-placeholder-font-size)',
} as UTSJSONObject

const formAddInputFontSize = computed((): number => {
  const v = (pageStyleVars.value as UTSJSONObject)['--reception-form-add-input-font-size'] as string | null
  if (v == null || v == '') {
    return 14
  }
  // 允许配置为 '18px' / '18'
  const n = parseInt(v.replace('px', ''), 10)
  return isNaN(n) ? 14 : n
})

const props = withDefaults(
  defineProps<{
    show?: boolean
    /** 编辑时传入列表行数据(含 id、车型与标签等接口字段),新增时为 null */
    initialRecord?: UTSJSONObject | null
  }>(),
  { show: true, initialRecord: null }
)

// 从页面参数接收编辑数据
const initialRecordFromQuery = ref<UTSJSONObject | null>(null)

const emit = defineEmits<{
  'close': []
  /** 保存或重复归类处理完成后通知父级刷新列表 */
  'saved': []
}>()

// 表单数据:与 default_customerForm / saveVisitsInfo 参数字段对齐(展示名 + 提交用 id)
type FormDataModel = {
  id: string
  ownerName: string
  ownerPhone: string
  brandModel: string
  receptionSceneName: string
  receptionScene: string
  arrivalDate: string
  customerTagName: string
  customerTag: string
  carModelId: string
  carBrand: string
  carBrandId: string
  oneCarBrand: string
  oneCarBrandId: string
}

function getEmptyForm(): FormDataModel {
  return {
    id: '',
    ownerName: '',
    ownerPhone: '',
    brandModel: '',
    receptionSceneName: '',
    receptionScene: '',
    arrivalDate: '',
    customerTagName: '',
    customerTag: '',
    carModelId: '',
    carBrand: '',
    carBrandId: '',
    oneCarBrand: '',
    oneCarBrandId: ''
  }
}

/** 通用工具函数 */
function fieldStr(data: UTSJSONObject | null, key: string): string {
  if (data == null || data[key] == null) return ''
  return `${data[key]}`
}

function parseIntSafe(s: string | null): number | null {
  if (s == null || s === '') return null
  const n = parseInt(s, 10)
  return isNaN(n) ? null : n
}

/** 日期格式化辅助函数 */
function formatDateByTimestamp(timestamp: number): string {
  const d = new Date(timestamp)
  const y = d.getFullYear()
  const m = (d.getMonth() + 1).toString().padStart(2, '0')
  const day = d.getDate().toString().padStart(2, '0')
  return `${y}-${m}-${day}`
}

/** 日期格式化:毫秒时间戳、数字串或 YYYY-MM-DD → 表单日期串 */
function arrivalRecordToDateString(v: any | null): string {
  if (v == null) return ''

  // 处理数字时间戳
  if (typeof v === 'number') {
    return v > 0 ? formatDateByTimestamp(v) : ''
  }

  const s = `${v}`.trim()
  if (s === '') return ''

  // 处理数字字符串(时间戳)
  if (/^\d+$/.test(s) && s.length >= 10) {
    const n = parseFloat(s)
    if (!isNaN(n) && n > 0) {
      return formatDateByTimestamp(n)
    }
  }

  // 处理 YYYY-MM-DD 格式
  if (s.length >= 10) {
    const head = s.substring(0, 10)
    const parts = head.split('-')
    if (parts.length == 3) return head
  }

  return ''
}

const formData = ref<FormDataModel>(getEmptyForm())
const brandCascaderShow = ref(false)
const sceneSelectShow = ref(false)
const customerTagsSelectShow = ref(false)
const arrivalDateValue = ref<string | number>('')

function applyInitialRecord(r: UTSJSONObject): void {
  const next = getEmptyForm()
  next.id = fieldStr(r, 'id')
  next.ownerName = fieldStr(r, 'ownerName')
  next.ownerPhone = fieldStr(r, 'ownerPhone')
  next.brandModel = fieldStr(r, 'brandModel')
  next.receptionSceneName = fieldStr(r, 'receptionSceneName')
  if (next.receptionSceneName == '') {
    next.receptionSceneName = fieldStr(r, 'receptionScenario')
  }
  next.receptionScene = fieldStr(r, 'receptionScene')
  const arrivalDateVal: any | null = (r as UTSJSONObject)['arrivalDate']
  next.arrivalDate = arrivalRecordToDateString(arrivalDateVal)
  if (next.arrivalDate === '') {
    const arrivalTimeVal: any | null = (r as UTSJSONObject)['arrivalTime']
    next.arrivalDate = arrivalRecordToDateString(arrivalTimeVal)
  }
  let tagName = fieldStr(r, 'customerTagName')
  if (tagName.indexOf(',') >= 0) {
    const tagParts = tagName.split(',')
    tagName = tagParts.join('|')
  }
  next.customerTagName = tagName
  next.customerTag = fieldStr(r, 'customerTag')
  next.carModelId = fieldStr(r, 'carModelId')
  next.carBrand = fieldStr(r, 'carBrand')
  next.carBrandId = fieldStr(r, 'carBrandId')
  next.oneCarBrand = fieldStr(r, 'oneCarBrand')
  next.oneCarBrandId = fieldStr(r, 'oneCarBrandId')
  formData.value = next
}

/** 重置表单 */
function resetForm(): void {
  formData.value = getEmptyForm()
  brandCascaderShow.value = false
  sceneSelectShow.value = false
  customerTagsSelectShow.value = false
  arrivalDateValue.value = ''
}

/** 编辑态:按 id 拉取详情并回显 */
async function loadEditDetailIfNeeded(): Promise<void> {
  const r = initialRecordFromQuery.value ?? props.initialRecord

  if (r == null) {
    resetForm()
    return
  }

  const idStr = fieldStr(r, 'id')
  if (idStr === '') {
    applyInitialRecord(r)
    return
  }

  const params = { id: parseIntSafe(idStr) ?? idStr } as UTSJSONObject

  uni.showLoading({ title: '加载中', mask: true })
  try {
    const res = await findVisitsInfo(params)
    console.log('findVisitsInfo', res)

    const body = res as UTSJSONObject
    const dataVal = body['data'] as UTSJSONObject | null

    if (fieldStr(body, 'code') === '0' && dataVal != null) {
      applyInitialRecord(dataVal)
    } else {
      const msg = fieldStr(body, 'message')
      if (msg !== '') uni.showToast({ title: msg, icon: 'none' })
      applyInitialRecord(r)
    }
  } catch (_e) {
    uni.showToast({ title: '加载详情失败', icon: 'none' })
    applyInitialRecord(r)
  } finally {
    uni.hideLoading()
  }
}

const submitLock = ref(false)

/** 顶部安全区占位(px):与 system 状态栏/刘海对齐 */
const receptionPageInsetTopPx = ref(0)

const receptionSafeTopSpacerStyle = computed(() => {
  return {
    height: `${receptionPageInsetTopPx.value}px`,
    width: '100%',
  } as UTSJSONObject
})

function syncReceptionSafeTopSpacer(): void {
  const info = uni.getWindowInfo()
  let topInset = 0

  // 优先使用 safeAreaInsets.top
  const insets = info.safeAreaInsets
  if (insets?.top != null && insets.top > 0) {
    topInset = Math.round(insets.top)
  }
  // 降级使用 safeArea.top
  else if (info.safeArea?.top != null && info.safeArea.top > 0) {
    topInset = Math.round(info.safeArea.top)
  }
  // 最后使用 statusBarHeight
  else if (info.statusBarHeight != null && info.statusBarHeight > 0) {
    topInset = Math.round(info.statusBarHeight)
  }

  receptionPageInsetTopPx.value = topInset
}

// 到店日期选择器
const datePickerShow = ref(false)

function onOpenDatePicker(): void {
  arrivalDateValue.value = formData.value.arrivalDate !== '' ? formData.value.arrivalDate : ''
  datePickerShow.value = true
  console.log('datePickerShow:', datePickerShow.value)
}

function onDatePickerConfirm(): void {
  formData.value.arrivalDate = arrivalDateValue.value !== '' ? `${arrivalDateValue.value}` : ''
  datePickerShow.value = false
}

/** 通用选择器控制函数 */
function toggleSelector(ref: ComponentPublicInstance | null, show: boolean): void {
  if (ref == null) return
  nextTick(() => {
    nextTick(() => {
      ref.$callMethod(show ? 'open' : 'close')
    })
  })
}

// 品牌车型选择器
const carBrandSelectRef = ref<ComponentPublicInstance | null>(null)

watch(brandCascaderShow, (show: boolean) => {
  toggleSelector(carBrandSelectRef.value, show)
})

// 接待场景选择器
const sceneSelectRef = ref<ComponentPublicInstance | null>(null)

watch(sceneSelectShow, (show: boolean) => {
  toggleSelector(sceneSelectRef.value, show)
})

// 客户标签选择器
const customerTagsSelectRef = ref<ComponentPublicInstance | null>(null)

watch(customerTagsSelectShow, (show: boolean) => {
  console.log('customerTagsSelectShow changed:', show)
  toggleSelector(customerTagsSelectRef.value, show)
})

function onSceneConfirm(payload: UTSJSONObject): void {
  sceneSelectShow.value = false
  formData.value.receptionSceneName = fieldStr(payload, 'receptionScenario')
  formData.value.receptionScene = fieldStr(payload, 'sceneId')
}

function onSceneClose(): void {
  sceneSelectShow.value = false
}

function onCustomerTagsConfirm(payload: UTSJSONObject): void {
  customerTagsSelectShow.value = false
  formData.value.customerTagName = fieldStr(payload, 'customerTags')
  formData.value.customerTag = fieldStr(payload, 'tagId')
}

function onCustomerTagsClose(): void {
  customerTagsSelectShow.value = false
}

function onCarBrandsSelect(payload: UTSJSONObject): void {
  brandCascaderShow.value = false

  // 提取字段值
  const modelStr = fieldStr(payload, 'name')
  const childName = fieldStr(payload, 'carChildsBrandName')
  const childId = fieldStr(payload, 'carChildsBrandId')
  const oneStr = fieldStr(payload, 'carBrand')
  const oneId = fieldStr(payload, 'carBrandId')
  const modelId = fieldStr(payload, 'id')

  // 只使用车型名称
  formData.value.brandModel = modelStr
  formData.value.carBrand = childName
  formData.value.carBrandId = childId
  formData.value.oneCarBrand = oneStr
  formData.value.oneCarBrandId = oneId
  formData.value.carModelId = modelId
}

function onCarBrandClose(): void {
  brandCascaderShow.value = false
}

// 旧位置的方法已前置,此处留空

watch(
  (): boolean => props.show,
  (open: boolean): void => {
    if (!open) {
      return
    }
    void loadEditDetailIfNeeded()
  },
  { immediate: true }
)

function handleClose(): void {
  resetForm()
  emit('close')
  uni.navigateBack()
}

function normalizeCustomerTagNameForApi(name: string): string {
  if (name == '') {
    return ''
  }
  const parts = name.split('|')
  return parts.join(',')
}

/** 表单验证 */
function validateForm(): string | null {
  const { ownerName, ownerPhone, brandModel, carModelId, receptionSceneName, arrivalDate, customerTagName } = formData.value

  if (ownerName === '') return '请输入车主姓名'
  if (ownerPhone === '') return '请输入车主电话'
  if (!phoneRex.test(ownerPhone)) return '请输入正确的手机号码'
  if (brandModel === '') return '请选择品牌车型'
  if (carModelId === '') return '请重新选择完整车型信息'
  if (receptionSceneName === '') return '请选择接待场景'
  if (arrivalDate === '') return '请选择到店日期'
  if (customerTagName === '') return '请选择客户标签'

  return null
}

/** 构建提交参数 */
function buildSubmitParams(): UTSJSONObject | null {
  const rawUser = storage.get('userInfo') as UTSJSONObject | null
  if (rawUser == null) {
    uni.showToast({ title: '未获取到登录门店信息', icon: 'none' })
    return null
  }

  const merchantId = fieldStr(rawUser, 'shopMerchantId')
  if (merchantId === '') {
    uni.showToast({ title: '未获取到门店 merchantId', icon: 'none' })
    return null
  }

  const sceneTypeNum = rawUser['sceneType'] as number | null
  const bussinessScene = (sceneTypeNum ?? 1) == 0 ? 1 : 2

  const fd = formData.value
  const params = {
    customerTag: fd.customerTag,
    merchantId,
    bussinessScene,
    ownerName: fd.ownerName,
    ownerPhone: fd.ownerPhone,
    brandModel: fd.brandModel,
    receptionSceneName: fd.receptionSceneName,
    arrivalDate: fd.arrivalDate,
    customerTagName: normalizeCustomerTagNameForApi(fd.customerTagName),
    carBrand: fd.carBrand,
    oneCarBrand: fd.oneCarBrand
  } as UTSJSONObject

  // 可选数字字段
  const rsNum = parseIntSafe(fd.receptionScene)
  if (rsNum != null) params['receptionScene'] = rsNum
  else if (fd.receptionScene !== '') params['receptionScene'] = fd.receptionScene

  const carModelIdNum = parseIntSafe(fd.carModelId)
  if (carModelIdNum != null) params['carModelId'] = carModelIdNum

  const carBrandIdNum = parseIntSafe(fd.carBrandId)
  if (carBrandIdNum != null) params['carBrandId'] = carBrandIdNum

  const oneCarBrandIdNum = parseIntSafe(fd.oneCarBrandId)
  if (oneCarBrandIdNum != null) params['oneCarBrandId'] = oneCarBrandIdNum

  // 编辑模式添加 id
  if (fd.id !== '') {
    const idNum = parseIntSafe(fd.id)
    params['id'] = idNum ?? fd.id
  }

  return params
}

async function handleSubmit(): Promise<void> {
  if (submitLock.value) return

  // 表单验证
  const errorMsg = validateForm()
  if (errorMsg != null) {
    uni.showToast({ title: errorMsg, icon: 'none' })
    return
  }

  // 构建参数
  const params = buildSubmitParams()
  if (params == null) return

  submitLock.value = true
  uni.showLoading({ title: '提交中', mask: true })
  console.log('saveVisitsInfo 保存更新 params', params)

  try {
    const isUpdate = formData.value.id !== ''
    const res = isUpdate ? await updateVisitsInfo(params) : await saveVisitsInfo(params)
    console.log('saveVisitsInfo 保存更新成功', res)

    const body = res as UTSJSONObject
    const code = fieldStr(body, 'code')
    console.log('saveVisitsInfo 保存更新成功code', code)

    // 失败直接提示后结束
    if (code != '0') {
      const msg = fieldStr(body, 'message')
      uni.showToast({ title: msg !== '' ? msg : '保存失败', icon: 'none' })
      return
    }

    // 成功:处理重复记录提示(后端可能用 data 标记归类结果)
    const flag = fieldStr(body, 'data')
    if (flag === '2') {
      await new Promise<void>((resolve) => {
        uni.showModal({
          content: '存在与该手机号相同的接待记录,系统将自动归类到已接待',
          showCancel: false,
          confirmText: '确认',
          confirmColor: '#347BFF',
          success: () => resolve()
        })
      })
    }

    // 提父级刷新并关闭
    uni.showToast({ title: '提交成功', icon: 'success' })
    handleClose();
    uni.$emit('refresh-reception-list')

  } catch (_e) {
    uni.showToast({ title: '网络异常,请重试', icon: 'none' })
  } finally {
    uni.hideLoading()
    submitLock.value = false
  }
}

onMounted(() => {
  syncReceptionSafeTopSpacer()
})

onLoad((options: UTSJSONObject) => {
  const recordStr = options['record']
  if (recordStr != null && typeof recordStr === 'string' && recordStr !== '') {
    try {
      const parsed = JSON.parse(recordStr)
      if (parsed != null && typeof parsed === 'object') {
        initialRecordFromQuery.value = parsed as UTSJSONObject
        applyInitialRecord(initialRecordFromQuery.value as UTSJSONObject)
      }
    } catch (e) {
      console.error('Failed to parse record query', e)
    }
  }
  void loadEditDetailIfNeeded()
})
</script>

<style lang="scss" scoped>
.form-add-root {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
  overflow: hidden;
  box-sizing: border-box;
  background-color: #ffffff;
}

.reception-safe-top-spacer {
  width: 100%;
  flex-shrink: 0;
}

/* un-navbar 固定定位时不占文档流高度,预留标题栏区域(与 center.uvue 一致) */
.reception-navbar-spacer {
  height: 44px;
  flex-shrink: 0;
}

.form-add-wrap {
  display: flex;
  flex-direction: column;
  flex: 1;
  padding: 8px 24px 0;
  padding-bottom: 24px;
  box-sizing: border-box;
  /* 内容区域自然撑开,不设置滚动 */
}

.form-add-body {
  display: flex;
  flex-direction: column;
  width: 100%;
}

.form-add-footer {
  display: flex;
  flex-direction: row;
  margin: 24px;
  padding-top: 16px;
  /* 禁止按钮被挤压 */
  flex-shrink: 0;
  background-color: #ffffff;
  /* 底部安全区适配 */
  padding-bottom: env(safe-area-inset-bottom);
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
}

.btn {
  flex: 1;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
  height: 44px;
  border-radius: 8px;
}

.cancel-btn {
  background-color: #f1f5f9;
  margin-right: 12px;
}

.submit-btn {
  background-color: #3b82f6;
}

.btn-text {
  font-size: var(--reception-form-add-btn-text-font-size, 16px);
  font-weight: 700;
}

.cancel-btn .btn-text {
  color: #64748b;
}

.submit-btn .btn-text {
  color: #ffffff;
}

.form-add-link-cell {
  flex: 1;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: flex-end;
  box-sizing: border-box;
}

.form-add-link-cell__value {
  flex: 1;
  font-size: var(--reception-form-add-cell-value-font-size, 14px);
  text-align: right;
  margin-right: 6px;
}

.form-add-link-cell__value--has {
  color: #1e293b;
}

.form-add-link-cell__value--empty {
  color: rgb(151, 150, 150);
}

.form-add-label {
  font-size: var(--reception-form-add-label-font-size, 14px);
}

.form-add-link-cell__arrow {
  margin-left: 6px;
  color: #cbd5e1;
  font-size: 14px;
  text-align: right;
}
</style>