createOrderCarQuotation.js 18.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 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
import { IMG_URL } from '../../../../utils/imageBase.js'
// packageEquity/pages/carEquity/serviceInfo/serviceInfo.js
import { getQuotationInfo, quotationAdd, updateQuotation, listByMerchantIdAndIds, getQuotationInfoById, quotationPicture, quotationRecording, priceCounter } from '../../../api'
import { quotedImgUrl } from '~/config'
import {
  DEFAULT_NEED_CHANGE_LIST,
  divideByHundred,
  divideByHundredObj,
  multipliedByHundred,
  multipliedByHundredObj
} from '../services/quotationMoney.helpers.js'
import {
  buildInsurancePayload,
  buildOwnerPayload,
  mapOwnerSalesTypeForApi,
  mapQuotationGoodsList,
  parseInsureListToForm
} from '../services/quotationPayload.helpers.js'
import { reconcileEquityCustomerDailyFields } from '../services/customerDailyFields.helpers.js'
import { submitStandardQuotation } from '../services/standardQuotationSubmit.workflow.js'
import {
  buildPricingPayload,
  requestQuotationPrice
} from '../services/quotationPricing.workflow.js'
import { buildSelectedCustomerState } from '../services/quotationCustomerSelection.helpers.js'
import constantList from '../components/constant/constantList'
// console.log(quotedImgUrl, 'quotedImgUrl')
Page({
  /**
   * 页面的初始数据
   */
  data: {
    IMG_URL,
    owner: {
      owner: '',
      phone: '',
      certificateNo: '',
      carVin: '',
      seat: '5',
      price: '',
      confirmStatus: false,
      saveStatus: false,
      salesType: 0,
      salesTypeLabel: constantList.salesTypeList[0].optionLabel,
      customerTags: '',
      actualDeliveryDate: ''
    },
    // owner: {
    //   owner: 'test2',
    //   phone: 15816539334,
    //   certificateNo: '230182198012251659',
    //   carVin: '12345678912345678',
    //   seat: 5,
    //   price: 7,
    //   confirmStatus: false,
    //   saveStatus: false
    // },
    quotationGoodsList: [], //权益商品列表
    orderInfo: {
      // 0-商业,1-交强,2-车船,3-增值车损,4-other 对应下面字段名字
      // owner
      business: {
        type: 0,
        three: '100万',
        driver: '1万',
        passenger: '1万'
      },
      mutualStrength: {
        type: 1,
        compensation: '20万'
      },
      vehiclesAndVessels: {
        type: 2,
        compensation: new Date().getFullYear() + '年'
      },
      valueAddedVehicleLoss: {
        type: 3
      },
      otherInsuranceList: [],
      mode: 0
    },
    // 页面存放表单对象的对象名
    dataAttrName: 'owner',
    step: 'first',
    // step: 'second',
    needChangeList: ['price', 'base', 'threePremium', 'carInsidePremium', 'passengerPremium', 'payPrice'],
    // vin二次确认弹窗
    showVinDialog: false,
    secFormData: {},
    tempVin: ''
  },
  secondChange() {
    let { showVinDialog } = this.data
    this.setData({
      showVinDialog: !showVinDialog
    })
  },
  handleSecClose() {
    let { tempVin } = this.data
    this.setData({
      secFormData: {
        carVin: ''
      },
    })
    if (tempVin) {
      console.log(tempVin, 'tempVin----')
      this.setData({
        'owner.carVin': tempVin,
        tempVin: ''
      })
    }
    this.secondChange()
  },
  handleSecConfirm(e) {
    let { detail } = e
    this.setData({
      ['owner.carVin']: detail.carVin,
      tempVin: detail.carVin
    })
  },
  reWrite(type, data) {
    console.log(type, data)
    let { owner } = this.data
    if (type == 'vehicleCertificate') {
      this.setData({
        tempVin: this.data.owner.carVin
      })
      let { vinNo: carVin, seatingCapacity: seat, engineNo: engineNumber, carColor } = data
      owner = Object.assign(owner, {
        carVin,
        seat,
        engineNumber,
        carColor
      })
      owner.carVin = ''
      if (carVin) {
        this.setData({
          secFormData: {
            carVin: carVin
          }
        })
        this.secondChange(carVin)
      }
    }
    if (type == 'idCard') {
      // debugger
      let { name, sex: ownerGender, address: addr, cardNo: certificateNo } = data
      owner = Object.assign(owner, {
        owner: name,
        ownerGender,
        addr,
        certificateNo
      })
      console.log(owner, 'owner')
    }

    this.setData({
      owner
    })
  },
  /**
   * 合并 FirstStep 上报的车主字段。
   *
   * @param {{detail: {patch: object}}} event 组件事件
   * @returns {void}
   */
  handleOwnerChange(event) {
    this.setData({ owner: { ...this.data.owner, ...(event.detail?.patch || {}) } })
  },
  /**
   * 合并 FirstStep/SecondStep 上报的订单字段。
   *
   * @param {{detail: {patch: object}}} event 组件事件
   * @returns {void}
   */
  handleOrderChange(event) {
    this.setData({
      orderInfo: { ...this.data.orderInfo, ...(event.detail?.patch || {}) }
    })
  },
  /**
   * 应用场景切换,并只在场景真正变化时清空报价商品。
   *
   * @param {{detail: {previousCode: string, scene: object}}} event 场景事件
   * @returns {void}
   */
  handleSceneChange(event) {
    const { previousCode, scene = {} } = event.detail || {}
    const patch = {
      baseSceneCode: scene.baseSceneCode || '',
      baseSceneName: scene.baseSceneName || scene.name || '',
      sceneType: scene.sceneType
    }
    this.setData({
      orderInfo: { ...this.data.orderInfo, ...patch },
      owner: reconcileEquityCustomerDailyFields(this.data.owner, patch)
    })
    if (previousCode !== patch.baseSceneCode) {
      this.handleResetGoodsRequested({ detail: { reason: 'scene-change' } })
    }
  },
  /**
   * 把客户档案映射为标准权益报价数据。
   *
   * @param {{detail: {customer: object}}} event 客户选择事件
   * @returns {void}
   */
  handleCustomerSelected(event) {
    const result = buildSelectedCustomerState({
      currentOwner: this.data.owner,
      orderInfo: this.data.orderInfo,
      customer: event.detail?.customer
    })
    this.setData({
      owner: result.owner,
      orderInfo: { ...this.data.orderInfo, ...result.orderPatch }
    })
  },
  /**
   * 清空依赖车辆/场景的报价选择并重新读取商品池。
   *
   * @param {{detail?: {reason?: string}}} _event 重置原因
   * @returns {void}
   */
  handleResetGoodsRequested(_event) {
    this.setData({
      ['orderInfo.quotedPriceUpdate']: '',
      ['orderInfo.goodsId']: '',
      ['orderInfo.goodsName']: '',
      ['orderInfo.valueAddedVehicleLoss']: {
        appreciation: '',
        goodsName: '',
        type: 3
      }
    })
    this.getQuotationInfo()
  },
  handleFirstConfirm(e) {
    // let { formData } = e.detail
    this.setData({
      // ['orderInfo.owner']: formData,
      step: 'second'
    })
  },
  /**
   * 处理标准权益商品计价请求,组件只负责上报所选商品 ID。
   *
   * @param {{detail: {goodsId: string|number}}} event 组件事件
   * @returns {Promise<void>} 计价完成后更新父页面状态
   */
  async handleQuoteRequested(event) {
    const goodsItem = this.data.quotationGoodsList.find(
      item => item.id == event.detail.goodsId
    )
    if (!goodsItem) return wx.$util.showToast('未找到报价商品')

    const payload = buildPricingPayload({
      owner: this.getOwnerInfo(),
      quotation: this.getInsurance(),
      goods: goodsItem
    })
    wx.$util.showLoading()
    try {
      const result = await requestQuotationPrice(payload, { priceCounter })
      if (result.status !== 'success') {
        return wx.$util.showToast(result.message || '获取报价失败')
      }

      const { data } = result
      const goodsName = goodsItem.upgradeGoodsName || goodsItem.goodsName
      this.setData({
        ['orderInfo.quotedPriceUpdate']: divideByHundred(data.quotedPriceUpdate),
        ['orderInfo.goodsId']: goodsItem.id,
        ['orderInfo.goodsName']: goodsItem.goodsName,
        ['orderInfo.valueAddedVehicleLoss']: {
          appreciation: goodsItem.id,
          goodsName,
          type: 3
        },
        ['orderInfo.quotationGoodsInfo']: {
          titlePictureUrl: goodsItem.goodsInfo?.thumbUrl,
          goodsName,
          quotationGoodsServiceItemsRelationDTOList:
            goodsItem.upgradeGoodsServiceItemsList
        }
      })
    } catch (error) {
      console.warn('标准权益计价失败', error)
      wx.$util.showToast(error?.message || '获取报价失败')
    } finally {
      wx.hideLoading()
    }
  },
  /**
   * 查询告知书生成结果,让接口异常由调用方统一恢复页面状态。
   *
   * @param {string|number} id 报价单 ID
   * @returns {Promise<object>} 原始查询响应
   */
  getQuotationGenerate(id) {
    return getQuotationInfoById({ id })
  },
  updateEquityPrice(type) {
    // quotationPicture
    let { orderInfo } = this.data
    const { id } = orderInfo
    wx.$util.showLoading('加载中...')

    const quotedPriceUpdate = this.multipliedByHundred(orderInfo?.modifyEquityQuotation?.quotedPriceUpdate)

    quotationPicture({
      id,
      quotedPriceUpdate,
      createQuotedUrl: quotedImgUrl + id
    })
      .then(result => {
        // debugger
        wx.hideLoading()
        console.log(result)
        let { code, data, message } = result
        if (code == 0) {
          type == 'saveEdit' ? wx.$router.reLaunch('packageEquity.equityPage', { tabIndex: 1 }) : this.navigatorNext(orderInfo.id)
        }
      })
      .catch(err => { })
  },
  /**
   * 提交标准权益报价并生成告知书;页面统一管理 loading 与防重锁。
   *
   * @returns {Promise<*>} 导航、提示或中止结果
   */
  async handleSecondConfirm() {
    // owner, orderInfo,
    // 修改权益报价逻辑
    let { modifyEquityQuotation, confirmStatus } = this.data
    if (confirmStatus) return false
    if (modifyEquityQuotation) {
      return this.updateEquityPrice()
    }
    // orderInfo.check = false
    // orderInfo.owner = owner
    // this.setData({ orderInfo })
    wx.showLoading('报价中...')
    this.setData({
      confirmStatus: true
    })
    try {
      const outcome = await this.handleSecondConfirmCheck(true)
      const result = outcome.response || {}
      if (outcome.status !== 'success') {
        return wx.$util.showToast(result.message || '报价失败')
      }
      const { data: id, message } = result || {}
      if (!id) {
        return wx.$util.showToast(message || '报价失败')
      }

      const status = await this.getQuotationGenerate(id)
      console.log('id', id)
      return status?.code == 0
        ? this.navigatorNext(id)
        : wx.$util.showToast(status?.message || '报价失败')
    } catch (error) {
      console.warn('标准权益报价提交失败', error)
      return wx.$util.showToast(error?.message || '报价失败')
    } finally {
      wx.hideLoading()
      this.setData({
        confirmStatus: false
      })
    }
  },
  getInsurance() {
    const { orderInfo, needChangeList } = this.data
    const { default4SStoreInfo } = wx.$util.getUserInfo()
    return buildInsurancePayload(orderInfo, default4SStoreInfo, needChangeList)
  },
  getOwnerInfo() {
    const { owner, orderInfo } = this.data
    return buildOwnerPayload(
      owner,
      this.data.needChangeList,
      orderInfo
    )
  },
  /**
   * 构建并提交标准权益报价 payload,不处理 UI 副作用。
   *
   * @param {boolean} check 是否执行完整提交校验
   * @returns {Promise<object>} 接口原始响应
   */
  async handleSecondConfirmCheck(check) {
    // 获取保险信息
    let orderInfo = this.getInsurance()
    let owner = this.getOwnerInfo()
    owner.salesType = mapOwnerSalesTypeForApi(owner.salesType)
    orderInfo.owner = owner
    orderInfo.check = check
    console.log('orderInfo', orderInfo)
    return submitStandardQuotation(
      { payload: orderInfo, isEdit: Boolean(orderInfo.id) },
      { quotationAdd, updateQuotation }
    )
  },
  navigatorNext(id) {
    // packageEquity/pages/TabBar/equityPage
    wx.$router.redirectTo('schemeConfirmation', {
      id
    })
  },
  getOrderInfo() {
    let { id, orderInfo } = this.data
    // 先写死调试
    getQuotationInfoById({
      id
    })
      .then(result => {
        console.log('result', result)
        let { code, data: tableInfo } = result
        if (code == 0) {
          tableInfo.owner.price = divideByHundred(tableInfo.owner.price)
          tableInfo.quotedPriceUpdate = divideByHundred(tableInfo.quotedPriceUpdate)
          const insuranceTypeObj = parseInsureListToForm(
            tableInfo.insureList,
            this.data.needChangeList
          )
          const salesTypeNum = Number(tableInfo.owner.salesType)
          tableInfo.owner.salesType = [0, 1, 2].includes(salesTypeNum)
            ? salesTypeNum
            : 0
          const salesTypeOption = constantList.salesTypeList.find(
            item => item.optionId === tableInfo.owner.salesType
          )
          tableInfo.owner.salesTypeLabel =
            salesTypeOption?.optionLabel ||
            constantList.salesTypeList[0].optionLabel
          tableInfo.owner = reconcileEquityCustomerDailyFields(
            tableInfo.owner,
            tableInfo
          )
          this.setData({
            orderInfo: Object.assign(orderInfo, tableInfo, insuranceTypeObj),
            owner: tableInfo.owner
          })
          // 不是编辑权益价格取消勾选商品
          if (!orderInfo.modifyEquityQuotation) {
            this.setData({
              ['orderInfo.quotedPriceUpdate']: '',
              ['orderInfo.goodsId']: '',
              ['orderInfo.goodsName']: '',
              ['orderInfo.valueAddedVehicleLoss']: {
                appreciation: '',
                goodsName: '',
                type: 3
              }
            })
          }
        }
      })
      .catch(err => { })
  },
  // 缩小100
  divideByHundredObj(obj) {
    return divideByHundredObj(obj, this.data.needChangeList)
  },
  multipliedByHundredObj(obj) {
    return multipliedByHundredObj(obj, this.data.needChangeList)
  },
  // 不需要检验 存草稿
  /**
   * 保存标准权益报价草稿,并在全部完成路径恢复保存锁。
   *
   * @returns {Promise<*>} 导航、提示或中止结果
   */
  async handleEditSave() {
    let { owner, orderInfo, modifyEquityQuotation, saveStatus } = this.data
    if (modifyEquityQuotation) {
      return this.updateEquityPrice('saveEdit')
    }
    if (saveStatus) return false
    wx.showLoading('保存中...')
    this.setData({
      saveStatus: true
    })
    orderInfo.check = false
    orderInfo.owner = owner
    this.setData({
      orderInfo
    })
    try {
      const outcome = await this.handleSecondConfirmCheck(false)
      const { data, message } = outcome.response || {}
      if (outcome.status === 'success' && data) {
        return wx.$router.redirectTo('packageEquity.equityPage', { tabIndex: 1 })
      }
      return wx.$util.showToast(message || '存草稿失败')
    } catch (error) {
      console.warn('标准权益报价草稿保存失败', error)
      return wx.$util.showToast(error?.message || '存草稿失败')
    } finally {
      wx.hideLoading()
      this.setData({
        saveStatus: false
      })
    }
  },
  getQuotationInfo() {
    let { default4SStoreInfo } = wx.$util.getUserInfo()
    console.log(default4SStoreInfo, 'default4SStoreInfo')
    let { orderInfo } = this.data
    listByMerchantIdAndIds({
      merchantId: default4SStoreInfo.merchantId
    })
      .then(result => {
        console.log(result)
        const data = mapQuotationGoodsList(result.data, {
          outTradeNo: orderInfo.outTradeNo,
          totalFee: orderInfo.totalFee
        })
        if (!data.length)
          return wx.showModal({
            title: '温馨提示',
            content: '商品已下架或计算规则未配置,请联系客服处理。',
            showCancel: false,
            confirmText: '确定',
            confirmColor: '#347BFF'
          })
        this.setData({
          quotationGoodsList: data
        })
        // let { id: appreciation, goodsInfo, upgradeGoodsName: goodsName, upgradeGoodsServiceItemsList } = data[0]
        // this.setData({
        //   ['orderInfo.valueAddedVehicleLoss']: {
        //     appreciation,
        //     goodsName,
        //     type: 3
        //   },
        //   ['orderInfo.quotationGoodsInfo']: {
        //     titlePictureUrl: goodsInfo.thumbUrl,
        //     goodsName,
        //     quotationGoodsServiceItemsRelationDTOList: upgradeGoodsServiceItemsList
        //   }
        // })
      })
      .catch(err => { })
  },
  divideByHundred: str => divideByHundred(str),
  multipliedByHundred: str => multipliedByHundred(str),
  back() {
    console.log('back')
    // wx.$router.reLaunch('pages.sceneIndex')
    let { step } = this.data
  
    console.log('step', step)
    if (step == 'first') {
      wx.$router.reLaunch('packageEquity.equityPage')
    } else {
      this.setData({
        step: 'first'
      })
    }
  },
  navbarReady(e) {
    let navBarHeight = e.detail.height
    this.setData({
      navBarHeight
    })
  },
  onRoute(options) {
    console.log(options, 'options')
    // 判断是编辑还是新增
    // options.id = 14
    // options.modifyEquityQuotation = true
    let { outTradeNo, totalFee } = options
    // outTradeNo
    if (outTradeNo) {
      this.setData({
        // outTradeNo
        totalFee: totalFee,
        ['orderInfo.outTradeNo']: outTradeNo
      })
    }
    if (options.id) {
      // 修改权益报价
      let { modifyEquityQuotation } = options
      if (modifyEquityQuotation) {
        let minEquityPrice = this.divideByHundred(modifyEquityQuotation.minEquityPrice)
        let quotedPriceUpdate = this.divideByHundred(modifyEquityQuotation.quotedPriceUpdate)
        this.setData({
          ['orderInfo.modifyEquityQuotation']: {
            minEquityPrice,
            quotedPriceUpdate
          },
          modifyEquityQuotation: true,
          step: 'second'
        })
      }
      this.setData({
        id: options.id
      })
      this.getOrderInfo()
    }
    this.getQuotationInfo()
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) { },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    // let that = this
    // setTimeout(() => {
    //   this.node = that.selectComponent('#SecondStep')
    //   console.log(this.node, 'node')
    //   this.node.handlePopupShow()
    //   // node()
    // }, 1000)
    // this.getOrderInfo()
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() { },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() { },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() { },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() { },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() { },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() { }
})