ReceptionRecordEdit.uvue 16.6 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
<template>
  <view class="reception-record-edit-root" :style="pageStyleVars">
    <view class="reception-safe-top-spacer" :style="receptionSafeTopSpacerStyle"></view>
    <un-navbar title="接待记录编辑" @leftClick="handleClose" :titleStyle="navbarTitleStyle" />
    <view class="reception-navbar-spacer"></view>

    <view class="reception-record-edit-wrap">
      <view class="reception-record-edit-body">
        <un-form :model="formData" labelWidth="80" labelAlign="left" borderBottom>
          <un-form-item prop="customerName" :customStyle="formItemCustomStyle">
            <template #label>
              <text class="form-label">车主姓名</text>
            </template>
            <un-input
              v-model="formData.customerName"
              border="none"
              inputAlign="right"
              placeholder="请输入车主姓名"
              :fontSize="inputFontSize"
              :placeholderStyle="placeholderStyle"
              :maxlength="50"
            ></un-input>
          </un-form-item>

          <un-form-item prop="customerPhone" :customStyle="formItemCustomStyle">
            <template #label>
              <text class="form-label">车主电话</text>
            </template>
            <un-input
              v-model="formData.customerPhone"
              border="none"
              type="tel"
              inputAlign="right"
              placeholder="请输入车主电话"
              :fontSize="inputFontSize"
              :placeholderStyle="placeholderStyle"
              :maxlength="11"
            ></un-input>
          </un-form-item>

          <un-form-item prop="customerType" :customStyle="formItemCustomStyle">
            <template #label>
              <text class="form-label">客户类型</text>
            </template>
            <view class="radio-cell">
              <un-radio-group v-model="formData.customerType" placement="row">
                <un-radio name="VIP" label="VIP"></un-radio>
                <un-radio name="潜客" label="潜客"></un-radio>
                <un-radio name="普通" label="普通"></un-radio>
              </un-radio-group>
            </view>
          </un-form-item>

          <un-form-item prop="carType" :customStyle="formItemCustomStyle">
            <template #label>
              <text class="form-label">品牌车型</text>
            </template>
            <un-input
              v-model="formData.carType"
              border="none"
              inputAlign="right"
              placeholder="请输入品牌车型"
              :fontSize="inputFontSize"
              :placeholderStyle="placeholderStyle"
              :maxlength="50"
            ></un-input>
          </un-form-item>

          <un-form-item prop="result" :customStyle="formItemCustomStyle">
            <template #label>
              <text class="form-label">接待结果</text>
            </template>
            <view class="radio-cell">
              <un-radio-group v-model="formData.result" placement="row">
                <un-radio name="成交" label="成交"></un-radio>
                <un-radio name="战败" label="战败"></un-radio>
              </un-radio-group>
            </view>
          </un-form-item>
        </un-form>
      </view>

      <view class="reception-record-edit-footer">
        <view class="btn cancel-btn" @click="handleClose">
          <text class="btn-text btn-text-cancel">取消</text>
        </view>
        <view
          class="btn submit-btn"
          :class="{ 'submit-btn--disabled': submitLoading }"
          @click="handleSubmit"
        >
          <text class="btn-text btn-text-submit">{{ submitLoading ? '提交中…' : '保存提交' }}</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="uts">
import { ref, computed, onMounted } from 'vue'
import { useScreenVars } from '@/services/adapter/hooks/index.uts'
import pageVars from '../styles/index.vars.uts'
import DBRecord from '@/services/recorder/DBRecord.uts'
import RecordSave from '@/services/recorder/RecordSave.uts'
import { FileStatus } from '@/services/recorder/common/constants.uts'
import { deepClone, toObj, getStringProp } from '@/utils/common.uts'
import { storage } from '@/utils/storage.uts'
import { getCustomerPhone } from '../lists/reception-list-helpers.uts'

/**
 * 编辑页路由 record 与本地库 RecordData / 列表项对齐,常见字段示例:
 * id, machineCode, startTime, endTime, recordStatus, endReasonType,
 * customerName, customerPhone, customerType, carType, result,
 * urlList[{ filePath, status, file?, filePathOnClient? }], 以及可选 merchantId、userId 等。
 * 表单仅维护客户与结果字段;提交时 deepClone 快照并覆盖表单列,其余字段原样保留。
 */
type EditFormModel = {
  id: string
  customerName: string
  customerPhone: string
  customerType: string
  carType: string
  result: string
}

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

const pageStyleVars = useScreenVars(pageVars as UTSJSONObject)

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

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

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

const formItemCustomStyle = {
  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

/** 顶部安全区占位(px):与 FormAdd/FormDetail 一致 */
const receptionPageInsetTopPx = ref(0)
const receptionSafeTopSpacerStyle = computed((): UTSJSONObject => {
  return { height: `${receptionPageInsetTopPx.value}px`, width: '100%' } as UTSJSONObject
})

function syncReceptionSafeTopSpacer(): void {
  const info = uni.getWindowInfo()
  let topInset = 0
  const insets = info.safeAreaInsets
  if (insets?.top != null && insets.top > 0) {
    topInset = Math.round(insets.top)
  } else if (info.safeArea?.top != null && info.safeArea.top > 0) {
    topInset = Math.round(info.safeArea.top)
  } else if (info.statusBarHeight != null && info.statusBarHeight > 0) {
    topInset = Math.round(info.statusBarHeight)
  }
  receptionPageInsetTopPx.value = topInset
}

function getEmptyForm(): EditFormModel {
  return {
    id: '',
    customerName: '',
    customerPhone: '',
    customerType: '',
    carType: '',
    result: '',
  }
}

const formData = ref<EditFormModel>(getEmptyForm())

/** 与 DB 一致的完整接待对象,用于组 save 参数并走 RecordSave 清理逻辑 */
const fullRecordSnapshot = ref<UTSJSONObject | null>(null)
const submitLoading = ref(false)

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

function resolveRecordId(r: UTSJSONObject): string {
  const id = fieldStr(r, 'id')
  if (id != '') {
    return id
  }
  return fieldStr(r, 'batchId')
}

function isUrlListItemReadyForSubmit(entry: UTSJSONObject): boolean {
  const stVal = entry['status']
  const st = typeof stVal == 'number' ? stVal as number : parseInt(`${stVal}`, 10)
  if (!isNaN(st) && (st == FileStatus.Uploaded || st == FileStatus.Completed)) {
    return true
  }
  const serverUrl = entry['file']
  if (serverUrl != null && typeof serverUrl == 'string' && serverUrl != '') {
    return true
  }
  return false
}

/** 与 RecordSave._saveOrUpdate 一致:无文件记录,或 urlList 内文件均已上传(含已填 OSS 地址) */
function isLocalRecordReadyForServerSubmit(rec: UTSJSONObject): boolean {
  const statusVal = rec['status']
  const statusNum = typeof statusVal == 'number' ? statusVal as number : parseInt(`${statusVal}`, 10)
  if (!isNaN(statusNum) && statusNum == FileStatus.NoFile) {
    return true
  }
  const rawList = rec['urlList']
  if (rawList == null || !Array.isArray(rawList)) {
    return false
  }
  const fileList = rawList as UTSJSONObject[]
  if (fileList.length == 0) {
    return false
  }
  for (let i = 0; i < fileList.length; i++) {
    if (!isUrlListItemReadyForSubmit(fileList[i])) {
      return false
    }
  }
  return true
}

function parseIntLoose(v: any | null, defaultVal: number): number {
  if (v == null) {
    return defaultVal
  }
  if (typeof v == 'number') {
    const n = v as number
    return isNaN(n) ? defaultVal : n
  }
  const parsed = parseInt(`${v}`, 10)
  return isNaN(parsed) ? defaultVal : parsed
}

/** 与接口 save 对齐:优先 reviewFlag,否则沿用 recordStatus */
function resolveReviewFlagNum(snap: UTSJSONObject): number {
  if (snap['reviewFlag'] != null) {
    return parseIntLoose(snap['reviewFlag'], 0)
  }
  return parseIntLoose(snap['recordStatus'], 0)
}

/**
 * 合并登录态中的门店/人员/设备信息(仅补空,不覆盖已有库字段)。
 * materialId 与 DefaultRecorderStrategy 一致默认 "101"。
 */
function mergeLoginContextIfEmpty(out: UTSJSONObject): void {
  const userObj = storage.getParse('userInfo')
  const typeItem = storage.getParse('typeItem')
  const setIfEmpty = (key: string, val: string): void => {
    if (val == '') {
      return
    }
    const cur = out[key]
    if (cur == null || `${cur}` == '') {
      out[key] = val
    }
  }
  setIfEmpty('userId', getStringProp(userObj, 'userId'))
  setIfEmpty('userName', getStringProp(userObj, 'userName'))
  setIfEmpty('merchantId', getStringProp(userObj, 'shopMerchantId'))
  setIfEmpty('typeCode', getStringProp(typeItem, 'typeCode'))
  setIfEmpty('materialId', '101')
  const mc = fieldStr(out, 'machineCode')
  if (mc == '') {
    const di = uni.getDeviceInfo()
    out['machineCode'] = di.deviceId
  }
}

/** 将本地快照字段对齐 linkwe-gateway reception/save 入参,去掉易混淆的旧字段名 */
function normalizeSaveRecCustomerShape(out: UTSJSONObject, snap: UTSJSONObject): void {
  let idVal = fieldStr(snap, 'id')
  if (idVal == '') {
    idVal = fieldStr(snap, 'batchId')
  }
  if (idVal != '') {
    out['id'] = idVal
  }

  const start = fieldStr(out, 'startTime')
  if (start == '') {
    const alt = fieldStr(out, 'receptionStartTime')
    if (alt != '') {
      out['startTime'] = alt
    }
  }
  const end = fieldStr(out, 'endTime')
  if (end == '') {
    const altEnd = fieldStr(out, 'receptionEndTime')
    if (altEnd != '') {
      out['endTime'] = altEnd
    }
  }

  const phone = fieldStr(out, 'customerPhone')
  if (phone == '') {
    const pn = fieldStr(out, 'phoneNumber')
    if (pn != '') {
      out['customerPhone'] = pn
    }
  }

  const flagNum = resolveReviewFlagNum(snap)
  out['recordStatus'] = flagNum
  out['endReasonType'] = flagNum

  out['status'] = 999

  out['batchId'] = null
  out['phoneNumber'] = null
  out['receptionStartTime'] = null
  out['receptionEndTime'] = null
  out['reviewFlag'] = null
  out['orderFinishFlag'] = null
  out['submitted'] = null
}

function buildMergedSubmitPayload(snap: UTSJSONObject, fd: EditFormModel): UTSJSONObject {
  const out = deepClone<UTSJSONObject>(snap)
  if (out == null) {
    return {} as UTSJSONObject
  }
  out['customerName'] = fd.customerName
  out['customerPhone'] = fd.customerPhone
  out['customerType'] = fd.customerType
  out['carType'] = fd.carType
  out['result'] = fd.result
  mergeLoginContextIfEmpty(out)
  normalizeSaveRecCustomerShape(out, snap)
  return out
}

function applyInitialRecord(r: UTSJSONObject): void {
  const next = getEmptyForm()
  next.id = fieldStr(r, 'id')
  if (next.id == '') {
    next.id = fieldStr(r, 'batchId')
  }
  next.customerName = fieldStr(r, 'customerName')
  next.customerPhone = getCustomerPhone(r)
  next.customerType = fieldStr(r, 'customerType')
  next.carType = fieldStr(r, 'carType')
  next.result = fieldStr(r, 'result')
  formData.value = next
}

function setSnapshotFromRecord(rec: UTSJSONObject): void {
  const cloned = deepClone<UTSJSONObject>(toObj(rec))
  if (cloned != null) {
    fullRecordSnapshot.value = cloned
  }
}

async function loadFullRecordFromDb(recordId: string, fallbackObj: UTSJSONObject): Promise<void> {
  try {
    const row = await DBRecord.getInstance().getRecordById(recordId)
    if (row == null) {
      uni.showToast({ title: '未找到本地接待记录', icon: 'none' })
      setSnapshotFromRecord(fallbackObj)
      applyInitialRecord(fallbackObj)
      return
    }
    const jo = toObj(row as UTSJSONObject)
    const cloned = deepClone<UTSJSONObject>(jo)
    if (cloned == null) {
      setSnapshotFromRecord(fallbackObj)
      applyInitialRecord(fallbackObj)
      return
    }
    fullRecordSnapshot.value = cloned
    applyInitialRecord(cloned)
  } catch (_e) {
    setSnapshotFromRecord(fallbackObj)
    applyInitialRecord(fallbackObj)
  }
}

function validateForm(): string | null {
  const fd = formData.value
  if (fd.customerName == '') return '请输入车主姓名'
  if (fd.customerPhone == '') return '请输入车主电话'
  if (!phoneRex.test(fd.customerPhone)) return '请输入正确的手机号码'
  if (fd.customerType == '') return '请选择客户类型'
  if (fd.carType == '') return '请输入品牌车型'
  if (fd.result == '') return '请选择接待结果'
  return null
}

function handleClose(): void {
  if (submitLoading.value) {
    return
  }
  uni.navigateBack()
}

async function handleSubmit(): Promise<void> {
  if (submitLoading.value) {
    return
  }
  const msg = validateForm()
  if (msg != null) {
    uni.showToast({ title: msg, icon: 'none' })
    return
  }

  const snap = fullRecordSnapshot.value
  if (snap == null) {
    uni.showToast({ title: '记录未就绪,请返回重试', icon: 'none' })
    return
  }
  // if (!isLocalRecordReadyForServerSubmit(snap)) {
  //   uni.showToast({ title: '录音仍在上传中,请在「待上传」完成后再提交', icon: 'none' })
  //   return
  // }

  submitLoading.value = true
  // try {
    const merged = buildMergedSubmitPayload(snap, formData.value)
    console.log('merged', merged)
    await RecordSave.submitLocalReceptionToServer(merged)
    console.log('RecordSave.submitLocalReceptionToServer success')
    uni.$emit('refresh-reception-list')
    uni.showToast({ title: '保存成功', icon: 'success' })
    uni.navigateBack()
  submitLoading.value = false
}

/**
 * 打开方式:
 * url: /pages/receptionCenter/forms/ReceptionRecordEdit?record=${encodeURIComponent(JSON.stringify(item))}
 */
onLoad((options: UTSJSONObject | null) => {
  if (options == 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 obj = parsed as UTSJSONObject
        const rid = resolveRecordId(obj)
        if (rid != '') {
          setSnapshotFromRecord(obj)
          applyInitialRecord(obj)
          void loadFullRecordFromDb(rid, obj)
        } else {
          setSnapshotFromRecord(obj)
          applyInitialRecord(obj)
        }
      }
    } catch (e) {
      console.error('Failed to parse record query', e)
    }
  }
})

onMounted(() => {
  syncReceptionSafeTopSpacer()
})
</script>

<style lang="scss" scoped>
.reception-record-edit-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;
}

.reception-navbar-spacer {
  height: 44px;
  flex-shrink: 0;
}

.reception-record-edit-wrap {
  display: flex;
  flex-direction: column;
  flex: 1;
  padding: 8px 24px 0;
  padding-bottom: 24px;
  box-sizing: border-box;
}

.reception-record-edit-body {
  display: flex;
  flex-direction: column;
  width: 100%;
}

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

.radio-cell {
  flex: 1;
  display: flex;
  flex-direction: row;
  justify-content: flex-end;
}

.reception-record-edit-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;
}

.submit-btn--disabled {
  opacity: 0.55;
}

.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;
}
</style>