FormDetail.uvue 28 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 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059
<template>
  <view class="form-detail-root" :style="pageStyleVars">
    <!-- 与 FormAdd 一致:安全区 + 固定导航占位,避免首屏内容被导航栏遮挡 -->
    <view class="reception-safe-top-spacer" :style="receptionSafeTopSpacerStyle"></view>
    <un-navbar title="接待详情" @leftClick="handleClose" :titleStyle="formDetailNavbarTitleStyle" />
    <view class="reception-navbar-spacer"></view>
    <view class="form-detail-wrap">
      <!-- 使用 flex: 1 自动撑满剩余空间,避免底部留白 -->
      <list-view
        class="form-detail-scroll"
        direction="vertical"
        :bounces="false"
        :show-scrollbar="false"
      >
        <list-item class="form-detail-li form-detail-li--head" :type="0">
          <view class="form-detail-body">
            <view class="form-section">
              <view class="form-section-header">
                <text class="form-section-title">接待信息</text>
              </view>
              <view class="form-section-body">
                <view v-for="item in ownerInfoRows" :key="item.key" class="form-row">
                  <text class="form-label">{{ item.label }}</text>
                  <text class="form-value">{{ item.value }}</text>
                </view>
              </view>
            </view>
          </view>
        </list-item>
        <list-item class="form-detail-li form-detail-li-goods" :type="1">
          <view class="goods-section-wrap">
            <view class="form-detail-goods-head">
              <text class="form-detail-goods-title">商品套餐</text>
            </view>
            <CustomEmpty
              v-if="goodsRowPairs.length == 0"
              type="base"
              title="暂无商品套餐"
            />
            <view
              v-else
              v-for="(row, goodsRowIndex) in goodsRowPairs"
              :key="goodsRowKey(row)"
              class="goods-row-wrap"
              :class="goodsRowIndex == goodsRowPairs.length - 1 ? 'goods-row-wrap-last' : ''"
            >
              <view class="goods-row-2">
                <view v-for="item in row" :key="item.id" class="goods-card goods-card--half">
                  <view class="goods-image-wrap">
                    <image class="goods-image" :src="item.image" mode="aspectFill"></image>
                  </view>
                  <view class="goods-info">
                    <text class="goods-name">{{ item.name }}</text>
                    <text class="goods-meta">业务场景:{{ item.scene }}</text>
                    <text class="goods-meta">客户标签:{{ item.customerTag }}</text>
                  </view>
                </view>
              </view>
            </view>
          </view>
        </list-item>
      </list-view>
    </view>
  </view>
</template>

<script setup lang="uts">
import { ref, computed, onMounted, onUnmounted, nextTick, watch, type Ref } from 'vue'
import { findVisitsInfo } from '@/api/receiption.uts'
import { getMaterialResponsePage } from '@/api/customer-api.uts'
import { storage } from '@/utils/storage.uts'
import CustomEmpty from '@/components/CustomEmpty/index.uvue'
import { useScreenVars } from '@/services/adapter/hooks/index.uts'
import pageVars from '../styles/index.vars.uts'

// 使用 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 GOODS_PLACEHOLDER_IMAGE = 'https://dummyimage.com/320x200/f3f6ff/94a3b8.png&text=%E6%9A%82%E6%97%A0%E5%9B%BE'

type GoodsCardItem = {
  id: string
  image: string
  name: string
  scene: string
  customerTag: string
}

const formDetailNavbarTitleStyle = computed((): UTSJSONObject => {
  return {
    fontSize: 'var(--reception-form-detail-navbar-title-font-size, 17px)',
  } as UTSJSONObject
})

/** 顶部安全区占位(px):与系统状态栏/刘海对齐,随窗口信息刷新 */
const receptionPageInsetTopPx = ref(0)

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

function calcReceptionSafeTopInsetPx(info: GetWindowInfoResult): number {
  // 自定义导航:预留顶部安全区,避免与状态栏/刘海重叠(优先 safeAreaInsets.top)
  let topInset = 0
  const insets = info.safeAreaInsets
  if (insets != null) {
    const t = insets.top
    if (t != null && t > 0) {
      topInset = Math.round(t)
    }
  }
  if (topInset <= 0) {
    const safe = info.safeArea
    if (safe != null) {
      const st = safe.top
      if (st != null && st > 0) {
        topInset = Math.round(st)
      }
    }
  }
  if (topInset <= 0) {
    const sb = info.statusBarHeight
    if (sb != null && sb > 0) {
      topInset = Math.round(sb)
    }
  }
  return topInset
}

const props = withDefaults(
  defineProps<{
    show?: boolean
    /** 列表行或初始详情;有 id 时会请求 findVisitsInfo 再填充展示 */
    detail?: UTSJSONObject | null
  }>(),
  { show: false, detail: null }
)

/** 页面模式:通过 uni.navigateTo 打开时为 true(同 FormAdd 用 query record 传参) */
const pageMode = ref(false)

const openFlag = computed((): boolean => {
  if (pageMode.value) {
    return true
  }
  // ✅ UTS 避免 Boolean === true 比较
  const val = props.show;
  return val != null && val;
})

function syncReceptionSafeTopSpacer(): void {
  const info = uni.getWindowInfo()
  receptionPageInsetTopPx.value = calcReceptionSafeTopInsetPx(info)
}

let formDetailLayoutPollId: number | null = null
onMounted(() => {
  syncReceptionSafeTopSpacer()
  formDetailLayoutPollId = setInterval(syncReceptionSafeTopSpacer, 400)
})

onUnmounted(() => {
  if (formDetailLayoutPollId != null) {
    clearInterval(formDetailLayoutPollId as number)
    formDetailLayoutPollId = null
  }
})

/** 弹窗打开后:先等于 props.detail,接口成功则替换为详情 data */
const resolvedDetail = ref<UTSJSONObject | null>(null)

/** getMaterialResponsePage 成功后的卡片数据;关闭弹窗时清空 */
const materialGoodsCards = ref<GoodsCardItem[]>([])
/** 仅在接口成功返回业务 data 后为 true,失败或未请求时回退 parseGoodsListFromDetail */
const materialGoodsFromApi = ref(false)


function fieldStr(data: UTSJSONObject, key: string): string {
  const v = data[key]
  if (v == null) {
    return ''
  }
  return `${v}`
}

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

/** 与 FormAdd 一致:arrivalDate / arrivalTime 多种形态 → YYYY-MM-DD */
function arrivalRecordToDateString(v: any | null): string {
  if (v == null) {
    return ''
  }
  if (typeof v == 'number') {
    const ts = v as number
    if (ts <= 0) {
      return ''
    }
    const d = new Date(ts)
    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}`
  }
  const s = `${v}`.trim()
  if (s == '') {
    return ''
  }
  let allDigits = true
  let j = 0
  while (j < s.length) {
    const c = s.charCodeAt(j) ?? -1
    if (c < 48 || c > 57) {
      allDigits = false
      break
    }
    j++
  }
  if (allDigits && s.length >= 10) {
    const n = parseFloat(s)
    if (!isNaN(n) && n > 0) {
      const d = new Date(n)
      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}`
    }
  }
  const head = s.length >= 10 ? s.substring(0, 10) : ''
  if (head.length == 10) {
    const parts = head.split('-')
    if (parts.length == 3) {
      return head
    }
  }
  return ''
}

/** 按 id 拉取详情并写入 resolvedDetail;失败时保持列表行数据并 toast(对齐 FormAdd.loadEditDetailIfNeeded) */
async function loadDetailFromApiIfNeeded(row: UTSJSONObject): Promise<void> {
  const idStr = fieldStr(row, 'id')
  if (idStr == '') {
    return
  }
  const params = {} as UTSJSONObject
  const idNum = parseIntSafe(idStr)
  if (idNum != null) {
    params['id'] = idNum
  } else {
    params['id'] = idStr
  }
  uni.showLoading({ title: '加载中', mask: true })
  try {
    const res = await findVisitsInfo(params)
    const body = res as UTSJSONObject
    const code = body['code']
    const dataVal = body['data'] as UTSJSONObject | null
    if (code != null && `${code}` == '0' && dataVal != null) {
      resolvedDetail.value = dataVal
    } else {
      const msg = body['message'] as string
      if (msg != null && msg != '') {
        uni.showToast({ title: msg, icon: 'none' })
      }
    }
  } catch (_e) {
    uni.showToast({ title: '加载详情失败', icon: 'none' })
  } finally {
    uni.hideLoading()
  }
}

watch(
  (): boolean => openFlag.value,
  (open: boolean): void => {
    if (!open) {
      resolvedDetail.value = null
      materialGoodsCards.value = []
      materialGoodsFromApi.value = false
      return
    }
    syncReceptionSafeTopSpacer()
    nextTick(() => {
      syncReceptionSafeTopSpacer()
    })
    // pageMode 下 resolvedDetail 由 onLoad 设定;这里仅处理“组件弹层”场景
    if (pageMode.value) {
      return
    }
    const r = props.detail
    if (r == null) {
      resolvedDetail.value = null
      return
    }
    resolvedDetail.value = r
    void loadDetailFromApiIfNeeded(r)
  },
  { immediate: true }
)

const emit = defineEmits<{
  'close': []
}>()

// 格式化手机号:13001365398 -> 130 0136 5398
function formatPhone(phone: string): string {
  if (phone == null || phone == '') { return '' }
  const s = phone.replace(/\s/g, '')
  if (s.length >= 11) {
    return s.substring(0, 3) + ' ' + s.substring(3, 7) + ' ' + s.substring(7, 11)
  }
  return phone
}

function formatVisitDate(d: UTSJSONObject | null): string {
  if (d == null) { return '' }
  let s = arrivalRecordToDateString(d['arrivalDate'])
  if (s != '') {
    return s
  }
  s = arrivalRecordToDateString(d['arrivalTime'])
  return s
}

// 空值显示为 "-"
function orPlaceholder(val: string): string {
  return (val != null && val != '') ? val : '-'
}

function joinReceptionSceneNamesFromMaterial(raw: any | null): string {
  if (raw == null || !(raw instanceof Array)) {
    return '-'
  }
  const arr = raw as any[]
  const parts: string[] = []
  let i = 0
  while (i < arr.length) {
    const n = fieldStr(arr[i] as UTSJSONObject, 'receptionSceneName')
    if (n != '') {
      parts.push(n)
    }
    i++
  }
  if (parts.length == 0) {
    return '-'
  }
  return parts.join('、')
}

function joinCustomerLabelNamesFromMaterial(raw: any | null): string {
  if (raw == null || !(raw instanceof Array)) {
    return '-'
  }
  const arr = raw as any[]
  const parts: string[] = []
  let i = 0
  while (i < arr.length) {
    const n = fieldStr(arr[i] as UTSJSONObject, 'labelName')
    if (n != '') {
      parts.push(n)
    }
    i++
  }
  if (parts.length == 0) {
    return '-'
  }
  return parts.join('、')
}

/** 素材分页单条 → 商品卡(与模板字段对齐) */
function materialInfoToGoodsCard(row: UTSJSONObject, idx: number): GoodsCardItem {
  const idStr = fieldStr(row, 'id')
  const id = idStr != '' ? idStr : `mat-${idx}`
  let img = fieldStr(row, 'cover')
  if (img == '') {
    const detailsRaw = row['detailInfos']
    if (detailsRaw != null && detailsRaw instanceof Array) {
      const details = detailsRaw as any[]
      if (details.length > 0) {
        img = fieldStr(details[0] as UTSJSONObject, 'image')
      }
    }
  }
  if (img == '') {
    img = GOODS_PLACEHOLDER_IMAGE
  }
  const title = fieldStr(row, 'title')
  const name = orPlaceholder(title != '' ? title : fieldStr(row, 'name'))
  return {
    id,
    image: img,
    name,
    scene: joinReceptionSceneNamesFromMaterial(row['receptionSceneInfoList']),
    customerTag: joinCustomerLabelNamesFromMaterial(row['customerLabelInfoList'])
  }
}

/** 对齐旧版 getMaterialResponsePage:userInfo + 当前档案 receptionScene / customerTag */
async function loadMaterialResponsePageForDetail(d: UTSJSONObject | null): Promise<void> {
  if (d == null) {
    materialGoodsCards.value = []
    materialGoodsFromApi.value = false
    return
  }
  const rawUser = storage.get('userInfo') as UTSJSONObject | null
  if (rawUser == null) {
    materialGoodsCards.value = []
    materialGoodsFromApi.value = false
    return
  }
  const merchantRaw = rawUser['shopMerchantId']
  if (merchantRaw == null || `${merchantRaw}` == '') {
    materialGoodsCards.value = []
    materialGoodsFromApi.value = false
    return
  }
  const sceneTypeRaw = rawUser['sceneType']
  const sceneVal = sceneTypeRaw != null ? sceneTypeRaw : 1

  const receptionSceneStr = fieldStr(d, 'receptionScene')
  const rsNum = parseIntSafe(receptionSceneStr)
  const receptionSceneInfoList: UTSJSONObject[] = []
  if (rsNum != null) {
    const one = {} as UTSJSONObject
    one['receptionSceneId'] = rsNum
    receptionSceneInfoList.push(one)
  }

  const customerLabelList: UTSJSONObject[] = []
  const tagStr = fieldStr(d, 'customerTag')
  if (tagStr != '') {
    const tagParts = tagStr.split(',')
    let ti = 0
    while (ti < tagParts.length) {
      const e = tagParts[ti].trim()
      if (e != '') {
        const lo = {} as UTSJSONObject
        lo['labelId'] = e
        customerLabelList.push(lo)
      }
      ti++
    }
  }

  const params = {} as UTSJSONObject
  params['currentPage'] = 1
  params['pageSize'] = 50
  if (rsNum != null) {
    params['receptionScene'] = rsNum
  }
  params['status'] = 1
  params['receptionSceneInfoList'] = receptionSceneInfoList
  params['customerLabelList'] = customerLabelList
  params['merchantId'] = merchantRaw
  params['showChannel'] = 2
  params['scene'] = sceneVal

  try {
    const res = await getMaterialResponsePage(params)
    const body = res as UTSJSONObject
    const listRaw = body['list']
    if (listRaw != null && listRaw instanceof Array) {
      const arr = listRaw as any[]
      const cards: GoodsCardItem[] = []
      let mi = 0
      while (mi < arr.length) {
        cards.push(materialInfoToGoodsCard(arr[mi] as UTSJSONObject, mi))
        mi++
      }
      materialGoodsCards.value = cards
    } else {
      materialGoodsCards.value = []
    }
    materialGoodsFromApi.value = true
  } catch (_e) {
    materialGoodsCards.value = []
    materialGoodsFromApi.value = false
  }
}

/** 详情(含列表行或 findVisitsInfo 结果)变化时拉取素材分页,填充商品套餐区 */
watch(
  (): UTSJSONObject | null => {
    if (openFlag.value != true) {
      return null
    }
    return resolvedDetail.value
  },
  (d: UTSJSONObject | null): void => {
    if (openFlag.value != true) {
      return
    }
    void loadMaterialResponsePageForDetail(d)
  }
)

const displayCustomerName = computed((): string => {
  const d = resolvedDetail.value
  if (d == null) { return '-' }
  // 新结构:customerName;旧结构兼容:ownerName / name
  const v = fieldStr(d, 'customerName')
  if (v != '') { return v }
  const v2 = fieldStr(d, 'ownerName')
  if (v2 != '') { return v2 }
  return orPlaceholder(fieldStr(d, 'name'))
})

const displayCustomerPhone = computed((): string => {
  const d = resolvedDetail.value
  if (d == null) { return '-' }
  // 新结构:customerPhone;旧结构兼容:ownerPhone / phone
  const raw = fieldStr(d, 'customerPhone')
  if (raw != '') { return formatPhone(raw) }
  const raw2 = fieldStr(d, 'ownerPhone')
  if (raw2 != '') { return formatPhone(raw2) }
  const raw3 = fieldStr(d, 'phone')
  return orPlaceholder(formatPhone(raw3))
})

const displayCarType = computed((): string => {
  const d = resolvedDetail.value
  if (d == null) { return '-' }
  // 新结构:carType;旧结构兼容:brandModel
  const v = fieldStr(d, 'carType')
  if (v != '') { return v }
  return orPlaceholder(fieldStr(d, 'brandModel'))
})

const displayCustomerType = computed((): string => {
  const d = resolvedDetail.value
  if (d == null) { return '-' }
  return orPlaceholder(fieldStr(d, 'customerType'))
})

const displayResult = computed((): string => {
  const d = resolvedDetail.value
  if (d == null) { return '-' }
  return orPlaceholder(fieldStr(d, 'result'))
})

const displayStoreName = computed((): string => {
  const d = resolvedDetail.value
  if (d == null) { return '-' }
  return orPlaceholder(fieldStr(d, 'storeName'))
})

const displaySpName = computed((): string => {
  const d = resolvedDetail.value
  if (d == null) { return '-' }
  return orPlaceholder(fieldStr(d, 'spName'))
})

const displayReceptionUserName = computed((): string => {
  const d = resolvedDetail.value
  if (d == null) { return '-' }
  return orPlaceholder(fieldStr(d, 'userName'))
})

const displayReceptionDate = computed((): string => {
  const d = resolvedDetail.value
  if (d == null) { return '-' }
  // 新结构:receptionDate(YYYY-MM-DD);兜底用旧版 formatVisitDate
  const v = fieldStr(d, 'receptionDate')
  if (v != '') { return v }
  const v2 = formatVisitDate(d)
  return orPlaceholder(v2)
})

const displayStartTime = computed((): string => {
  const d = resolvedDetail.value
  if (d == null) { return '-' }
  return orPlaceholder(fieldStr(d, 'startTime'))
})

const displayEndTime = computed((): string => {
  const d = resolvedDetail.value
  if (d == null) { return '-' }
  return orPlaceholder(fieldStr(d, 'endTime'))
})

const displayDurationStr = computed((): string => {
  const d = resolvedDetail.value
  if (d == null) { return '-' }
  const v = fieldStr(d, 'durationStr')
  if (v != '') { return v }
  return orPlaceholder(fieldStr(d, 'duration'))
})

const displayRecordUrl = computed((): string => {
  const d = resolvedDetail.value
  if (d == null) { return '-' }
  return orPlaceholder(fieldStr(d, 'recordUrl'))
})

const displayRemark = computed((): string => {
  const d = resolvedDetail.value
  if (d == null) { return '-' }
  return orPlaceholder(fieldStr(d, 'remark'))
})

const displayPhoneNumber = computed((): string => {
  const d = resolvedDetail.value
  if (d == null) { return '-' }
  // 新结构:phoneNumber(可能是门店/服务商联系电话)
  const raw = fieldStr(d, 'phoneNumber')
  return raw != '' ? formatPhone(raw) : '-'
})

type FormRowItem = {
  key: string
  label: string
  value: string
}

function pickGoodsImage(obj: UTSJSONObject): string {
  let s = fieldStr(obj, 'goodsImage')
  if (s != '') { return s }
  s = fieldStr(obj, 'image')
  if (s != '') { return s }
  s = fieldStr(obj, 'imgUrl')
  if (s != '') { return s }
  s = fieldStr(obj, 'coverUrl')
  return s != '' ? s : GOODS_PLACEHOLDER_IMAGE
}

function pickGoodsName(obj: UTSJSONObject): string {
  let s = fieldStr(obj, 'goodsName')
  if (s != '') { return s }
  s = fieldStr(obj, 'name')
  if (s != '') { return s }
  return fieldStr(obj, 'title')
}

function pickGoodsScene(obj: UTSJSONObject): string {
  let s = fieldStr(obj, 'receptionScenario')
  if (s != '') { return s }
  s = fieldStr(obj, 'sceneName')
  if (s != '') { return s }
  s = fieldStr(obj, 'businessScene')
  return s != '' ? s : '-'
}

function pickGoodsTag(obj: UTSJSONObject): string {
  let s = fieldStr(obj, 'customerTagName')
  if (s != '') { return s }
  s = fieldStr(obj, 'customerTag')
  return s != '' ? s : '-'
}

function goodsArrayToCards(raw: any): GoodsCardItem[] {
  const out: GoodsCardItem[] = []
  if (raw == null) {
    return out
  }
  const arr = raw as any[]
  let idx = 0
  while (idx < arr.length) {
    const el = arr[idx] as UTSJSONObject
    const idStr = fieldStr(el, 'id')
    const id = idStr != '' ? idStr : `goods-${idx}`
    out.push({
      id,
      image: pickGoodsImage(el),
      name: orPlaceholder(pickGoodsName(el)),
      scene: pickGoodsScene(el),
      customerTag: pickGoodsTag(el)
    })
    idx += 1
  }
  return out
}

/** 从详情对象解析商品列表(兼容多种后端字段名) */
function parseGoodsListFromDetail(d: UTSJSONObject | null): GoodsCardItem[] {
  if (d == null) {
    return []
  }
  const keys = ['goodsList', 'visitGoodsList', 'tapeGoodsList', 'productList', 'comboList']
  let i = 0
  while (i < keys.length) {
    const raw = d[keys[i]]
    if (raw != null) {
      const cards = goodsArrayToCards(raw)
      if (cards.length > 0) {
        return cards
      }
    }
    i += 1
  }
  return []
}

const ownerInfoRows = computed((): FormRowItem[] => {
  return [
    { key: 'customerName', label: '客户姓名', value: displayCustomerName.value },
    { key: 'customerPhone', label: '客户电话', value: displayCustomerPhone.value },
    { key: 'carType', label: '车型', value: displayCarType.value },
    { key: 'customerType', label: '客户类型', value: displayCustomerType.value },
    { key: 'result', label: '接待结果', value: displayResult.value },
    { key: 'storeName', label: '门店', value: displayStoreName.value },
    { key: 'spName', label: '服务商', value: displaySpName.value },
    { key: 'userName', label: '接待人', value: displayReceptionUserName.value },
    { key: 'receptionDate', label: '接待日期', value: displayReceptionDate.value },
    { key: 'startTime', label: '开始时间', value: displayStartTime.value },
    { key: 'endTime', label: '结束时间', value: displayEndTime.value },
    { key: 'durationStr', label: '接待时长', value: displayDurationStr.value },
    { key: 'phoneNumber', label: '联系号码', value: displayPhoneNumber.value },
    { key: 'recordUrl', label: '录音地址', value: displayRecordUrl.value },
    { key: 'remark', label: '备注', value: displayRemark.value }
  ]
})

const goodsList = computed((): GoodsCardItem[] => {
  if (materialGoodsFromApi.value) {
    return materialGoodsCards.value
  }
  return parseGoodsListFromDetail(resolvedDetail.value)
})

/** 每行两个卡片:按两项一组拆行;模板中在单个 list-item 内按行渲染 */
function chunkGoodsRows(list: GoodsCardItem[]): GoodsCardItem[][] {
  const rows: GoodsCardItem[][] = []
  let i = 0
  while (i < list.length) {
    const row: GoodsCardItem[] = []
    row.push(list[i])
    i += 1
    if (i < list.length) {
      row.push(list[i])
      i += 1
    }
    rows.push(row)
  }
  return rows
}

const goodsRowPairs = computed((): GoodsCardItem[][] => {
  return chunkGoodsRows(goodsList.value)
})

function goodsRowKey(row: GoodsCardItem[]): string {
  if (row.length == 0) {
    return 'goods-row-empty'
  }
  if (row.length == 1) {
    return row[0].id
  }
  return row[0].id + '-' + row[1].id
}

function handleClose(): void {
  if (pageMode.value) {
    uni.navigateBack()
  } else {
    emit('close')
  }
}

/**
 * 页面打开:与 FormAdd 同样通过 query record 传递 JSON 字符串
 * url: /pages/receptionCenter/forms/FormDetail?record=${encodeURIComponent(JSON.stringify(item))}
 */
onLoad((options: UTSJSONObject | null) => {
  // 只要走到 onLoad 就视为页面模式(组件弹层不会触发 onLoad)
  pageMode.value = true
  syncReceptionSafeTopSpacer()

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

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

.form-detail-root {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  overflow: hidden;
  box-sizing: border-box;
  background-color: #ffffff;
}

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

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

.form-detail-wrap {
  display: flex;
  flex-direction: column;
  align-items: stretch;
  width: 100%;
  flex: 1;
  min-height: 0;
  padding: 8px 0 0;
  padding-bottom: 24px;
  overflow: visible;
  box-sizing: border-box;
}

.form-detail-scroll {
  width: 100%;
  flex: 1;
  box-sizing: border-box;
  padding-bottom: 24px;
}

/* list-item 默认在部分端上不会拉满父宽,需显式铺满弹层内容区 */
.form-detail-li {
  width: 100%;
  margin: 0;
  box-sizing: border-box;
  /* 由子节点撑开高度,避免部分端上列表项被默认成固定行高 */
  height: auto;
  min-height: 0;
}

/* 首块(车主信息):仅随内容增高,不占据 list-view 剩余可视高度 */
.form-detail-li--head {
  flex-grow: 0;
  flex-shrink: 0;
  align-self: flex-start;
}

.form-detail-li-goods {
  padding-left: 0;
  padding-right: 0;
  padding-top: 0;
  padding-bottom: 0;
  margin: 0;
  /* 高度随商品卡内容变化,勿写死 px */
  height: auto;
  min-height: 0;
  align-self: flex-start;
  flex-grow: 0;
  flex-shrink: 0;
}

/* 商品区块内边距与行间距 */
.goods-section-wrap {
  display: flex;
  flex-direction: column;
  width: 100%;
  box-sizing: border-box;
  padding-left: 24px;
  padding-right: 24px;
}

.goods-row-wrap {
  width: 100%;
  margin-bottom: 12px;
  box-sizing: border-box;
}

.goods-row-wrap-last {
  margin-bottom: 0;
}

.form-detail-body {
  display: flex;
  flex-direction: column;
  width: 100%;
  box-sizing: border-box;
  padding-left: 24px;
  padding-right: 24px;
  /* 高度随车主信息行数、标题区实际占用变化;不参与父级 flex 分配剩余高度 */
  flex-grow: 0;
  flex-shrink: 0;
  height: auto;
  min-height: 0;
  /* 勿用大 padding-bottom;底部留白交给 .form-detail-scroll */
  padding-bottom: 0;
}

.form-section {
  display: flex;
  flex-direction: column;
  width: 100%;
  align-self: stretch;
}

.form-section-header {
  display: flex;
  flex-direction: row;
  align-items: center;
  margin-bottom: 8px;
}

.form-section-title {
  font-size: var(--reception-form-detail-section-title-font-size, 16px);
  font-weight: 700;
  color: #1e293b;
}

.form-section-body {
  display: flex;
  flex-direction: column;
  width: 100%;
  align-self: stretch;
}

.form-row {
  display: flex;
  flex-direction: row;
  align-items: center;
  width: 100%;
  padding: 12px 0;
  border-bottom: 1px solid #e2e8f0;
}

.form-label {
  width: 100px;
  flex-shrink: 0;
  font-size: var(--reception-form-detail-label-font-size, 14px);
  color: #1e293b;
}

.form-value {
  flex: 1;
  min-width: 0;
  font-size: var(--reception-form-detail-value-font-size, 14px);
  color: #1e293b;
}

.form-value:empty {
  color: #94a3b8;
}

.form-detail-goods-head {
  width: 100%;
  margin-top: 16px;
  padding-top: 12px;
  margin-bottom: 8px;
}

.form-detail-goods-title {
  font-size: var(--reception-form-detail-goods-title-font-size, 16px);
  font-weight: 700;
  color: #1e293b;
}

/* 每行 list-item 内横向两张卡 */
.goods-row-2 {
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  justify-content: space-between;
  align-items: flex-start;
  width: 100%;
  box-sizing: border-box;
  margin-bottom: 0;
}

.goods-card {
  display: flex;
  flex-direction: column;
  align-items: stretch;
  min-width: 0;
  height: auto;
  margin: 0;
  box-sizing: border-box;
  border-radius: 12px;
  background: #ffffff;
  /* 减轻纵向阴影外扩,避免相邻行之间像有「缝」 */
  box-shadow: 0 1px 4px 0 #2a61eb14;
  overflow: hidden;
}

.goods-card--half {
  flex: 0 0 48%;
  width: 48%;
}

.goods-image-wrap {
  width: 100%;
  height: 120px;
  background: #f3f6ff;
  overflow: hidden;
}

.goods-image {
  width: 100%;
  height: 100%;
}

.goods-info {
  display: flex;
  flex-direction: column;
  flex-grow: 0;
  flex-shrink: 0;
  width: 100%;
  min-width: 0;
  padding: 8px 8px 10px;
}

.goods-name {
  width: 100%;
  font-size: var(--reception-form-detail-goods-name-font-size, 14px);
  font-weight: 700;
  color: #1e293b;
  margin-bottom: 4px;
}

.goods-meta {
  width: 100%;
  font-size: var(--reception-form-detail-goods-meta-font-size, 12px);
  color: #475569;
  line-height: var(--reception-form-detail-goods-meta-line-height, 16px);
  margin-bottom: 2px;
}

.goods-meta:last-child {
  margin-bottom: 0;
}
</style>