createDeafeatOrder.js 16.3 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
import { ImgUrl } from '~/config'
import { getSelectOrderGoodsList,quotationGoodsList, defeatOrderCreate } from '../../api'
import commonApi from '~/api/api'
import NP from 'number-precision'
import { checkStudyTask, checkOrderLockGate } from '~/store/ModalToQueueControl'
import {
  coalesceYmd,
  isDateOnOrBeforeToday
} from '../../services/calendarDateBounds.helpers.js'
Page({
  /**
   * 页面的初始数据
   */
  data: {
    IMG_URL: ImgUrl,
    scanIcon:
      'https://img02.glsx.com.cn/weapp/resource/dj-car-boutique-work-wechat/ocr_icon.png',
    name: 'createdOrder',
    dateObj: {
      beforeDay: '',
      today: '',
      nextDay: '',
      maxDate: '',
      todayShow: ''
    },
    customer: {
      customerName: '',
      customerPhone: '',
      salesType: 0
    },
    reasonList: [
      {
        select: false,
        name: '回去考虑一下'
      },
      {
        select: false,
        name: '完全不需要'
      },
      {
        select: false,
        name: '问家里意见'
      },
      {
        select: false,
        name: '没钱'
      },
      {
        select: false,
        name: '开一两年就不用了'
      },
      {
        select: false,
        name: '车开不了那么久换车'
      }
    ],
    deafeatReason: '',
    orderObj: {},
    customerInfoBox: false,
    saleTypesList: [
      {
        type: 0,
        name: '门店引流-售前'
      },
      {
        type: 1,
        name: '门店引流-售后'
      },
      {
        type: 2,
        name: '自然到店'
      }
    ],
    showSceneSelect: false,
    sceneColumns: [],
    sceneDefaultIndex: 0
  },
  async prefillRecentScene() {
    const userInfo = this.data.userInfo || wx.$util.getUserInfo() || {}
    const currentCode = this.data.orderObj?.baseSceneCode || ''
    if (currentCode) return
    try {
      const res = await commonApi.getRecentUserScene({
        sceneType: String(userInfo.sceneType ?? ''),
        phone: userInfo.phone
      })
      const recent = res?.code == 0 ? res?.data : null
      const baseSceneCode = recent?.baseSceneCode || ''
      if (!baseSceneCode) return
      this.setData({
        'orderObj.baseSceneCode': baseSceneCode,
        'orderObj.sceneType': recent?.sceneType
      })
    } catch (e) {}
  },
  /**设置日期 */
  setTimeList(dateNum) {
    const todayYmd = new Date().format('yyyy-MM-dd')
    const maxDate = coalesceYmd(todayYmd, todayYmd)
    let today = dateNum || todayYmd
    /**
     * 根据日期字符串获取星期几
     * @param dateString 日期字符串(如:2020-05-02)
     * @returns {String}
     */
    var dateArray = today.split('-')
    let date = new Date(dateArray[0], parseInt(dateArray[1] - 1), dateArray[2])
    let todayShow = ' 周' + '日一二三四五六'.charAt(date.getDay())
    todayShow =
      dateArray[0] +
      '年' +
      dateArray[1] +
      '月' +
      dateArray[2] +
      '日 ' +
      todayShow

    this.setData({
      dateObj: {
        today,
        maxDate,
        todayShow
      }
    })
  },
  // 获取选中天数
  rangeSelect(e) {
    let { date } = e.detail
    const today = coalesceYmd(
      this.data.dateObj?.maxDate,
      new Date().format('yyyy-MM-dd')
    )
    if (!isDateOnOrBeforeToday(date, today)) {
      return this.showToast('战败日期不能晚于今天')
    }
    this.setTimeList(date)
  },

  onLoad: async function (res) {
    this.setTimeList()
    this.handlerUserInfo()
    await this.prefillRecentScene()
    this.getUserSceneList()
    this.getGoodsProduct()
  },

  onRoute(options) {
    this.setData({
      'customer.customerName': options.customerName,
      'customer.customerPhone': options.customerPhone
    })
  },

  onShow: function () {
    this.setTimeList()
  },
  toSelectReason(e) {
    let { deafeatReason } = this.data
    const { item, index } = e.currentTarget.dataset
    let str = deafeatReason
    str = deafeatReason + item.name
    if (str.length > 30) {
      str = deafeatReason
    }
    this.setData({
      deafeatReason: str
    })
  },
  intReason(e) {
    this.setData({
      deafeatReason: e.detail.value
    })
  },
  showPopup(e) {
    let { showName } = e.currentTarget.dataset
    if (showName === 'showSceneSelect') {
      this.getUserSceneList()
    }
    this.setData({
      [showName]: true
    })
  },
  getUserSceneList() {
    const userInfo = this.data.userInfo || wx.$util.getUserInfo() || {}
    commonApi
      .getUserScene({
        sceneType: String(userInfo.sceneType ?? ''),
        phone: userInfo.phone
      })
      .then(res => {
        const list = res?.code == 0 && res?.data?.length ? res.data : []
        const sceneColumns = list.map(item => ({
          ...item,
          name: item.name || item.staffName
        }))
        const code = this.data.orderObj?.baseSceneCode || ''
        const idx = code
          ? sceneColumns.findIndex(s => s.baseSceneCode == code)
          : 0
        const currentScene = code && idx >= 0 ? sceneColumns[idx] : null
        this.setData({
          sceneColumns,
          sceneDefaultIndex: idx >= 0 ? idx : 0,
          ...(currentScene
            ? {
                'orderObj.baseSceneName': currentScene.name || '',
                'orderObj.sceneType': currentScene.sceneType
              }
            : {})
        })
      })
      .catch(() => {
        this.setData({
          sceneColumns: []
        })
      })
  },
  onCloseSceneSelect() {
    this.setData({
      showSceneSelect: false
    })
  },
  onConfirmSceneSelect(e) {
    const scene = e.detail.value || {}
    const userInfo = this.data.userInfo || wx.$util.getUserInfo() || {}
    const prevCode = this.data.orderObj?.baseSceneCode || ''
    const nextCode = scene.baseSceneCode || ''
    const switched = prevCode !== nextCode
    this.setData(
      {
        showSceneSelect: false,
        'orderObj.baseSceneCode': nextCode,
        'orderObj.baseSceneName': scene.name || scene.staffName || '',
        'orderObj.sceneType': scene.sceneType
      },
      () => {
        if (switched) {
          this.getGoodsProduct()
        }
      }
    )
    scene.baseSceneCode &&
      commonApi
        .saveUserScene({
          baseSceneCode: scene.baseSceneCode,
          sceneType: userInfo.sceneType,
          phone: userInfo.phone
        })
        .catch(() => {})
  },
  handlerUserInfo() {
    let userInfo = wx.$util.getUserInfo()
    let { orderObj } = this.data
    orderObj.sellerMerchantName = userInfo.merchantName
    orderObj.sellerMerchantId = userInfo.merchantId
    orderObj.sellerName = userInfo.name
    orderObj.sellerUserId = userInfo.uuid
    this.setData({
      orderObj,
      userInfo
    })
  },
  showCustomPop(e) {
    this.setData({
      customerInfoBox: true
    })
  },
  chooseCustomerInfo(e) {
    console.log(e)
    let { detail } = e
    let customer = {
      customerName: detail.customer.customerName,
      customerSex: detail.customer.customerSex,
      customerPhone: detail.customer.customerPhone,
      carBrandId: detail.customer.carBrandId,
      carBrand: detail.customer.carBrand,
      carChildsBrandId: detail.customer.carChildsBrandId,
      carChildsBrandName: detail.customer.carChildsBrandName,
      carSeriesId: detail.customer.carSeriesId,
      carSeriesName: detail.customer.carSeriesName,
      standNo: detail.customer.standNo,
      plateNumber: detail.customer.plateNumber
    }
    this.setData({
      customer
    })
    this.setData({ customerInfoBox: false })
  },
  onCustomerInfoCancel() {
    this.setData({ customerInfoBox: false })
  },
  input(e) {
    let { value } = e.detail
    let { name } = e.currentTarget.dataset
    this.setData({
      [name]: value
    })
  },
  // 提交完停留当前页面清空数据
  async toContinueSumbit() {
    const params = await this.handlerParams()
    this.toPostData(params, 1)
  },
  // 提交完跳转订单列表页面
  async toSumbit() {
    const params = await this.handlerParams()
    this.toPostData(params, 0)
  },
  // 获取商品列表数据(与车损报价一致:按 sceneType=0 + baseSceneCode 拉可选商品)
  getGoodsProduct() {
    const { default4SStoreInfo } = wx.$util.getUserInfo() || {}
    const baseSceneCode = this.data.orderObj?.baseSceneCode || ''
    if (!default4SStoreInfo?.merchantId || !baseSceneCode) {
      this.setDefailtInfo([])
      return
    }
    wx.showLoading({ title: '加载中...' })
	quotationGoodsList({
		merchantId: default4SStoreInfo.merchantId,
		suitCarPrice: '',
		baseSceneCode
	  })
      .then(result => {
        wx.hideLoading()
        let { code, data, message } = result
        if (code != 0) {
          wx.$util.showToast(message || '商品加载失败')
          this.setDefailtInfo([])
          return
        }
        if (!data?.length) {
          this.setDefailtInfo([])
          return
        }

        data = data.map(ele => {
          if (ele.goods) {
            let item = ele.goods
            ele.goods = {
              ...item,
              goodsId: item.merchantGoodsId,
              // goodsNameAlias: item.upgradeGoodsAlias,
              goodsNameAlias: item.goodsAlias || item.goodsNameAlias,
              appreciation: item?.appreciation,
              goodsName: item?.upgradeGoodsName,
              quotationGoodsServiceItemsRelationDTOList:
                item?.upgradeGoodsServiceItemsList,
              titlePictureUrl: item.goodsInfo?.thumbUrl
            }
          }
          if (ele.packageGoods) {
            let item = ele.packageGoods
            item.goodsList = item.goodsList.map(ele => {
              // console.log(ele, '2222');
              let obj = {
                packageId: item.packageCode,
                packageName: item.packageName,
                packageNameAlias: item.packageAlias || item.packageNameAlias,
                goodsId: ele.merchantGoodsId || ele.upgradeGoodsId,
                goodsName: ele.upgradeGoodsName || ele.goodsName,
                goodsNameAlias: ele.goodsAlias || ele.goodsNameAlias,
                // shopMinPrice: item.shopMinPrice,
                goodsPrice: this.multipliedByHundred(ele.price),
                sellPrice: ele.sellPrice
              }
              return obj
              // ele.push(obj);
            })
            ele.packageGoods.sellPrice = item.goodsList.reduce((pre, item) => {
              pre = NP.plus(pre, item.sellPrice)
              return pre
            }, 0)
          }
          return ele
        })
        console.log(data, 'data')
        this.setDefailtInfo(data)
      })
      .catch(err => {
        wx.hideLoading()
        console.log(err)
        this.setDefailtInfo([])
      })
  },
  // 乘以100保留两位小数点
  multipliedByHundred: str => {
    let floatVal = parseFloat(str)
    if (isNaN(floatVal)) {
      return 0
    }
    floatVal = Math.round(str * 10000) / 100
    let strVal = floatVal.toString()
    let searchVal = strVal.indexOf('.')
    if (searchVal < 0) {
      searchVal = strVal.length
      strVal += '.'
    }
    while (strVal.length <= searchVal + 2) {
      strVal += '0'
    }
    return parseFloat(strVal)
  },
  // 处理默认隐藏信息
  setDefailtInfo(data) {
    let vdQuotationGoodsList = []
    if (Array.isArray(data) && data.length && data[0]) {
      let item = data[0]

      if (item.goods) {
        item = item.goods
        const obj = {
          goodsId: item.merchantGoodsId,
          goodsName: item.goodsName,
          goodsNameAlias: item.goodsAlias || item.goodsNameAlias,
          // shopMinPrice: item.shopMinPrice,
          goodsPrice: this.multipliedByHundred(item.sellPrice)
        }
        // pre.push(obj);
        item = obj
        vdQuotationGoodsList.push(item)
      }
      if (item.packageGoods) {
        let packageGoods = item.packageGoods

        item = item.packageGoods
        item = item.goodsList.map(ele => {
          console.log(ele, '2222')
          let obj = {
            packageId: packageGoods.packageCode,
            packageName: packageGoods.packageName,
            packageNameAlias:
              packageGoods.packageAlias || pachageGoods.packageNameAlias,
            goodsId: ele.goodsId,
            goodsName: ele.goodsName,
            goodsNameAlias: ele.goodsNameAlias,
            // shopMinPrice: item.shopMinPrice,
            goodsPrice: this.multipliedByHundred(ele.sellPrice)
          }
          // pre.push(obj);
          // item = obj
          return obj
        })
        // item.
        vdQuotationGoodsList = item
      }
      // let item = {
      //   goodsId: firstItem.goodsId,
      //   goodsName: firstItem.goodsName,
      //   goodsNameAlias: firstItem.goodsNameAlias,
      //   goodsPrice: NP.times(100, firstItem.sellPrice),
      // }
      console.log(item, 'firstItem')
    }
    let { default4SStoreInfo } = wx.$util.getUserInfo()
    const msg = {
      total: 1,
      mode: 1,
      check: true,
      insurancePrice: 0,
      merchantId4s: default4SStoreInfo.merchantId,
      merchantName4s: default4SStoreInfo.merchantName,
      minEquityPrice: 0,
      payType: 1,
      paymentDocList: [],
      quotedPriceUpdate: 0,
      referrer: '', //推荐人,
      referrerId: '', //
      transactionNo: '',
      vdQuotationGoodsList,
      owner: {
        ageRange: '',
        carBrand: '',
        carBrandId: '',
        carChildsBrandId: '',
        carChildsBrandName: '',
        carColor: '',
        carSeriesId: '',
        carSeriesName: '',
        carVin: '',
        certificateNo: '',
        city: '',
        companion: '',
        confirmStatus: false,
        owner: '', //客户姓名
        ownerGender: '',
        phone: '', //客户手机号
        price: '',
        salesType: 0,
        saveStatus: false,
        seat: 5
      },
      defeatOrder: true
    }
    this.defaultMsg = msg
  },
  // 同步选择信息
  async handlerParams() {
    return new Promise((resolve, reject) => {
      let params = this.defaultMsg,
        { customer, orderObj, deafeatReason, dateObj } = this.data
      if (!orderObj.employeeName) return this.showToast(`请选择推荐人员`)
      if (!orderObj.baseSceneCode) return this.showToast(`请选择场景名称`)
      if (!customer.customerName) return this.showToast(`请输入车主姓名`)
      if (!customer.customerPhone) return this.showToast(`请输入车主手机号`)
      const phoneRex = /^[1]([3-9])[0-9]{9}$/
      if (!phoneRex.test(customer.customerPhone)) {
        this.showToast(`请输入正确的手机号`)
        return
      }
      if (!deafeatReason) return this.showToast(`请输入战败原因`)
      const today = coalesceYmd(
        dateObj.maxDate,
        new Date().format('yyyy-MM-dd')
      )
      if (!isDateOnOrBeforeToday(dateObj.today, today)) {
        return this.showToast('战败日期不能晚于今天')
      }
      params.owner.owner = customer.customerName
      params.owner.phone = customer.customerPhone
      params.owner.salesType = customer.salesType
      params.referrer = orderObj.employeeName
      params.referrerId = orderObj.userId
      params.baseSceneCode = orderObj.baseSceneCode
      params.remark = deafeatReason
      params.defeatOrderTime = dateObj.today + ' 00:00:00'
      resolve(params)
    })
  },
  // 提交结束后重置数据
  resetData() {
    const customer = {
      customerName: '',
      customerPhone: '',
      salesType: 0
    }
    this.setData(
      {
        deafeatReason: '',
        customer,
        dateObj: {}
      },
      () => {
        this.setTimeList()
      }
    )
  },
  // 接口请求
  async toPostData(params, type) {
    console.log(params)
    // 校验学习中心开单限制
    let staffStudyTask = await checkStudyTask()
    if (staffStudyTask) return false
    // 校验异常订单
    let lockCheck = await checkOrderLockGate()
    if (lockCheck) return false

    // 添加收款方 0:嘀加收款
    params.payee = 0
    wx.showLoading({ title: '提交中...' })
    defeatOrderCreate(params).then(res => {
      wx.hideLoading()
      console.log(res)
      if (res && res.code == 0) {
        if (type == 1) {
          wx.$util.showToast('提交成功')
          this.resetData()
        } else {
          wx.$router.reLaunch('packageEquity.equityPage', {
            tabIndex: 1
          })
        }
      } else {
        wx.$util.showToast(res.message)
      }
    })
  },
  onCloseSaleType() {
    this.setData({ salesTypeShow: false })
  },
  onChangeSaleType(e) {
    console.log(e)
    const { type } = e.detail.value
    this.setData({
      'customer.salesType': type,
      salesTypeShow: false
    })
  }
})