ensure.js 16.8 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
import ensureModel from '../../../models/cart/ensure';
import addressModel from '../../../models/home/address';
import commonModel from '../../../models/common';
import wechatAddressUtil from '../../../utils/wechat-address';
import { wechatPay } from '../../../utils/wechat-pay';
import Yas from '../../../common/yas';

const SKU_TYPE = 'O';
const PAYMENT = { // 支付类型
  ID: 15,
  TYPE: 1,
};
const ORDER_TYPE = { // 结算订单类型
  BUYNOW: 'buynow',
  ORDINARY: 'ordinary'
};

const app = getApp();
let yas;

function _queryFromServiceAsync(fn) {
  if (fn) {
    let args = [...arguments];

    args.shift();

    args[0] = args[0] || {};
    Object.assign(args[0], {
      appType: app.getAppType()
    });

    return fn(...args);
  } else {
    return Promise.reject();
  }
}

function formatPaymentData(data, yasInfo) {
  data = data || {};

  let info = {
    choosedAddress: data.delivery_address || '',
    goodsList: data.goods_list || [],
    deliveryWayList: data.delivery_way || [],
    deliveryTimeList: data.delivery_time || [],
    promotionList: data.shopping_cart_data.promotion_formula_list,
    paymentAmount: data.shopping_cart_data.last_order_amount,
    isJit: false,
    package_title_detail: ''
  };
  let supplierId = 0;

  yasInfo = yasInfo || {};

  info.goodsList.map(value => {
    if (value.goods_type === 'gift' || value.goods_type === 'price_gift') {
      value.sales_price = value.last_price;
    }

    yasInfo.skns && yasInfo.skns.push(value.product_skn);
    yasInfo.skus && yasInfo.skus.push(value.product_sku);
    yasInfo.pids && yasInfo.pids.push(value.product_id);

    if (!info.isJit && value.is_jit === 'Y') {
      supplierId = value.supplier_id;
      info.isJit = true;
    }

    return value;
  });

  (data.shopping_cart_data && data.shopping_cart_data.package_list || []).some(item => {
    info.package_title_detail = item.title || '';
    return item === supplierId;
  });

  let selectWay,
    selectTime;

  if (info.deliveryWayList.length) {
    info.deliveryWayList.map(value => {
      if (value.default === 'Y') {
        value.checked = true;
        selectWay = value;
      }
    });

    if (!selectWay) {
      selectWay = info.deliveryWayList[0];
      info.deliveryWayList[0].checked = true;
    }

    info.deliveryWayId = selectWay.delivery_way_id;
    info.deliveryWayText = `${selectWay.delivery_way_name}:运费¥${selectWay.delivery_way_cost}`;
  }

  if (info.deliveryTimeList.length) {
    info.deliveryTimeList.map(value => {
      if (value.default === 'Y') {
        value.checked = true;
        selectTime = value;
      }
    });

    if (!selectTime) {
      selectTime = info.deliveryTimeList[0];
      info.deliveryTimeList[0].checked = true;
    }

    info.deliveryTimeId = selectTime.delivery_time_id;
    info.deliveryTimeText = selectTime.delivery_time_string || '';
  }

  return info;
}

// 普通结算-数据格式化
function formatShoppingPaymentData(data, yasInfo) {
  data = data || {};

  let info = {
    choosedAddress: data.delivery_address || '',
    goodsList: data.goods_list || [],
    deliveryWayList: data.delivery_way || [],
    deliveryTimeList: data.delivery_time || [],
    promotionList: data.shopping_cart_data.promotion_formula_list,
    paymentAmount: data.shopping_cart_data.last_order_amount,
    isJit: false,
    package_title_detail: ''
  };
  let supplierId = 0;

  yasInfo = yasInfo || {};

  info.goodsList.map(value => {
    if (value.goods_type === 'gift' || value.goods_type === 'price_gift') {
      value.sales_price = value.last_price;
    }

    yasInfo.skns && yasInfo.skns.push(value.product_skn);
    yasInfo.skus && yasInfo.skus.push(value.product_sku);
    yasInfo.pids && yasInfo.pids.push(value.product_id);

    if (!info.isJit && value.is_jit === 'Y') {
      supplierId = value.supplier_id;
      info.isJit = true;
    }

    return value;
  });

  (data.shopping_cart_data && data.shopping_cart_data.package_list || []).some(item => {
    info.package_title_detail = item.title || '';
    return item === supplierId;
  });

  let selectWay,
    selectTime;

  if (info.deliveryWayList.length) {
    info.deliveryWayList.map(value => {
      if (value.default === 'Y') {
        value.checked = true;
        selectWay = value;
      }
    });

    if (!selectWay) {
      selectWay = info.deliveryWayList[0];
      info.deliveryWayList[0].checked = true;
    }

    info.deliveryWayId = selectWay.delivery_way_id;
    info.deliveryWayText = `${selectWay.delivery_way_name}:运费¥${selectWay.delivery_way_cost}`;
  }

  if (info.deliveryTimeList.length) {
    info.deliveryTimeList.map(value => {
      if (value.default === 'Y') {
        value.checked = true;
        selectTime = value;
      }
    });

    if (!selectTime) {
      selectTime = info.deliveryTimeList[0];
      info.deliveryTimeList[0].checked = true;
    }

    info.deliveryTimeId = selectTime.delivery_time_id;
    info.deliveryTimeText = selectTime.delivery_time_string || '';
  }

  return info;
}

Page({
  data: {
    choosedAddress: {},
    goodsList: [],
    deliveryWayText: '',
    deliveryWayEditStatus: false,
    deliveryWayList: [],

    deliveryTimeText: '',
    deliveryTimeEditStatus: false,
    deliveryTimeList: [],

    invoiceNeedStatus: false,

    promotionList: [],
    paymentAmount: '',

    isJit: false,
    package_title_detail: ''
  },
  onLoad(options) {
    this.orderData = options;
    this.yasInfo = {
      skns: [],
      skus: [],
      pids: []
    };

    // 立即购买
    if (this.orderData.productSku) {
      this.loadEnsurePayment({buyNumber: this.orderData.buyNumber, productSku: this.orderData.productSku});
    } else {
      this.loadShoppingPayment(options);
    }

    yas = new Yas(app);
    yas.pageOpenReport();
  },
  _showModal(message) {
    return wx.showModal({
      content: message || '网络异常,请稍后重试',
      showCancel: false,
      confirmText: '好的',
    });
  },

  // 普通购买
  loadShoppingPayment(options) {
    this.orderType = ORDER_TYPE.ORDINARY;

    return _queryFromServiceAsync(ensureModel.shoppingPayment, {
      cart_type: options.cartType || 'ordinary',
      yoho_coin_mode: 0
    }).then(res => {
      if (res.code !== 200) {
        return this._showModal(res.message);
      }

      let data = formatShoppingPaymentData(res.data, this.yasInfo);

      this.setData(data);
    }).catch(() => {
      this._showModal();
    });
  },
  shoppingCompute(data) {
    if (typeof data === 'object') {
      Object.assign(this.orderData, data);
    }

    return _queryFromServiceAsync(ensureModel.shoppingCompute, {
      cart_type: 'ordinary',
      payment_type: 1, // 支付方式,1 在线支付 2 货到付款
      delivery_way: this.orderData.deliveryWayId, // 快递方式,1 普通 2 加急
      use_yoho_coin: 0, // 使用的yoho币金额,单位元1:00
      use_red_envelopes: 0, // 使用的红包,单位元
      coupon_code: '', // 优惠券code,多个用","分割
      promotion_code: '', // 优惠码code
      gift_card_code: '', // 礼品卡code
    }).then(res => {
      if (res.code === 200) {
        let comp = res.data || {};

        this.setData({
          promotionList: comp.promotion_formula_list,
          paymentAmount: comp.last_order_amount
        });
      }
    });
  },
  loadEnsurePayment(options) {
    if (options.productSku) {
      this.orderType = ORDER_TYPE.BUYNOW;

      _queryFromServiceAsync(ensureModel.buynowPayment, {
        sku_type: SKU_TYPE,
        product_sku: options.productSku,
        buy_number: options.buyNumber || 1,
        yoho_coin_mode: 0,
        is_support_apple_pay: 'N',
      }).then(res => {
        if (res.code !== 200) {
          wx.showModal({
            content: res.message || '网络异常,请稍后重试',
            showCancel: false,
            confirmText: '好的',
          });
          return;
        }

        let data = formatPaymentData(res.data, this.yasInfo);

        Object.assign(this.orderData, {
          productSku: options.productSku,
          buyNumber: options.buyNumber || 1,
          deliveryWayId: data.deliveryWayId,
          deliveryTimeId: data.deliveryTimeId
        });

        this.setData(data);
      }).catch(() => {
        wx.showModal({
          content: '网络异常,请稍后重试',
          showCancel: false,
          confirmText: '好的',
        });
      });
    }
  },
  buynowCompute(data) {
    if (typeof data === 'object') {
      Object.assign(this.orderData, data);
    }

    _queryFromServiceAsync(ensureModel.buynowCompute, {
      cart_type: 'ordinary',
      sku_type: SKU_TYPE,
      product_sku: this.orderData.productSku,
      buy_number: this.orderData.buyNumber,
      delivery_way: this.orderData.deliveryWayId,
      payment_type: 1, // 支付方式,1 在线支付 2 货到付款
    }).then(res => {
      if (res.code === 200) {
        let comp = res.data || {};

        this.setData({
          promotionList: comp.promotion_formula_list,
          paymentAmount: comp.last_order_amount
        });
      }
    });
  },
  showToast(title) {
    wx.showToast({
      title: title,
      icon: 'none',
      duration: 2000
    });
  },
  chooseAddress() {
    global.router.go('address', {
      type: 'select',
      id: this.data.choosedAddress.address_id
    });
  },
  chooseAddressCallback(address) {
    this.setData({choosedAddress: address});
  },
  enterAddress() {
    global.router.go('address', {type: 'add'});
  },
  chooseWechatAddress() {
    wechatAddressUtil.choose(res => {
      addressModel.saveWechatAddressData(res).then(result => {
        if (result.code === 200) {
          this.chooseAddressCallback(result.data);
        } else {
          wx.showToast({
            title: result.message,
            icon: 'none',
            duration: 1500
          });
        }
      });
    });
  },
  toggleDeliveryWayList() {
    this.setData({deliveryWayEditStatus: !this.data.deliveryWayEditStatus});
  },
  changeDeliveryWay(e) {
    let id = e.currentTarget.dataset.id;
    let name = e.currentTarget.dataset.name;
    let list = this.data.deliveryWayList;

    if (list.length) {
      list.map(item => {
        item.checked = (+item.delivery_way_id === +id);
      });
    }

    if (this.orderData.productSku) {
      this.buynowCompute({deliveryWayId: id});
    } else {
      this.shoppingCompute({deliveryWayId: id});
    }

    this.setData({
      deliveryWayText: name,
      deliveryWayEditStatus: false,
      deliveryWayList: list
    });
  },
  toggleDeliveryTimeList() {
    this.setData({deliveryTimeEditStatus: !this.data.deliveryTimeEditStatus});
  },
  changeDeliveryTime(e) {
    let id = e.currentTarget.dataset.id;
    let name = e.currentTarget.dataset.name;
    let list = this.data.deliveryTimeList;

    if (list.length) {
      list.map(item => {
        item.checked = (+item.delivery_time_id === +id);
      });
    }

    this.orderData.deliveryTimeId = id;
    this.setData({
      deliveryTimeText: name,
      deliveryTimeEditStatus: false,
      deliveryTimeList: list
    });
  },
  toggleInvoiceWrap(e) {
    let data = {invoiceNeedStatus: e.detail.value};

    if (!this.data.invoiceInfo) {
      let address = this.data.choosedAddress || {};

      data.invoiceInfo = {
        invoiceType: 2,
        invoiceCompany: false,
        invoiceTitle: '',
        invoiceTitleShow: '个人',
        invoiceContent: 12,
        taxNumber: '',
        receiver: address.mobile || ''
      };
    }

    this.setData(data);
  },
  changeInvoiceInfo() {
    let skey = `invoice${Date.parse(new Date())}`;

    try {
      wx.setStorageSync(skey, this.data.invoiceInfo);
    } catch (e) {
      console.log('invoice info setStorageSync error');
    }

    global.router.go('cartInvoice', {skey: skey});
  },
  changeInvoiceCallback(invoice) {
    if (!invoice.invoiceCompany && !invoice.invoiceTitle) {
      invoice.invoiceTitleShow = '个人';
    } else {
      invoice.invoiceTitleShow = invoice.invoiceTitle;
    }

    this.setData({invoiceInfo: invoice});
  },
  submitOrder(e) {
    this.formId = e.detail.formId;

    if (this.orderType === ORDER_TYPE.BUYNOW) {
      this.buynowOrderSubmit();
    } else {
      // 普通购物车下单
      this.shoppingSubmit();
    }
  },
  buynowOrderSubmit() {
    if (this.orderSubmiting) {
      return;
    }

    let param = {
      sku_type: SKU_TYPE,
      product_sku: this.orderData.productSku,
      buy_number: this.orderData.buyNumber,
      payment_id: PAYMENT.ID,
      payment_type: PAYMENT.TYPE,
      qhy_union: JSON.stringify({client_id: app.getUnionType()})
    };

    if (this.orderData.deliveryWayId) {
      param.delivery_way = this.orderData.deliveryWayId;
    }

    if (this.orderData.deliveryTimeId) {
      param.delivery_time = this.orderData.deliveryTimeId;
    }

    if (this.data.choosedAddress && this.data.choosedAddress.address_id) {
      param.address_id = this.data.choosedAddress.address_id;
    } else {
      return this.showToast('请选择收件地址');
    }

    if (this.data.invoiceNeedStatus) {
      let invoiceInfo = this.data.invoiceInfo;

      Object.assign(param, {
        invoices_title: invoiceInfo.invoiceTitleShow,
        invoices_type: invoiceInfo.invoiceType,
        invoice_content: invoiceInfo.invoiceContent,
        buyerTaxNumber: invoiceInfo.taxNumber,
        invoice_payable_type: invoiceInfo.invoiceCompany ? 2 : 1,
        receiverMobile: invoiceInfo.receiver
      });
    }

    if (+param.invoices_type === 2 && !param.receiverMobile) {
      return this.showToast('请填写电子发票接收手机号');
    }

    this.orderSubmiting = true;

    _queryFromServiceAsync(ensureModel.buynowSubmit, param).then(res => {
      this.orderSubmiting = false;

      if (res.code === 200) {
        let data = res.data;

        // yas上报
        yas.report('YB_SC_ORD', {
          ORD_NUM: data.order_code + '',
          PRD_SKN: this.yasInfo.skns.join(','),
          RPD_SKU: this.yasInfo.skus.join(','),
          PRD_ID: this.yasInfo.pids.join(','),
          ORDER_TYPE: 102 // 101购物车下单,102立即购买下单
        });

        // 上报formID
        commonModel.addWechatFormId({
          order_code: data.order_code,
          openId: app.getOpenID(),
          miniapp_type: app.getMiniappType(),
          formId: this.formId
        });

        data.needJump = true;
        wechatPay(data);
      } else {
        wx.showModal({
          content: res.message,
          showCancel: false,
          confirmText: '好的',
        });
      }
    }).catch(() => {
      this.orderSubmiting = false;
    });
  },
  shoppingSubmit() {
    if (this.orderSubmiting) {
      return;
    }

    let param = {
      payment_id: PAYMENT.ID,
      payment_type: PAYMENT.TYPE,
      use_red_envelopes: 0, // 使用的红包,单位元
      use_yoho_coin: 0, // 使用的yoho币金额,单位元
      coupon_code: '', // 优惠券code,多个用","分割
      is_print_price: 'N', // string    否   "Y" "N" 是否打印
      is_continue_buy: 'N', // string 否   "N" "Y" 是否继续结算
      gift_card_code: '', // 礼品卡code
      qhy_union: JSON.stringify({client_id: app.getUnionType()})
    };

    if (this.orderData.deliveryWayId) {
      param.delivery_way = this.orderData.deliveryWayId;
    }

    if (this.orderData.deliveryTimeId) {
      param.delivery_time = this.orderData.deliveryTimeId;
    }

    if (this.data.choosedAddress && this.data.choosedAddress.address_id) {
      param.address_id = this.data.choosedAddress.address_id;
    } else {
      return this.showToast('请选择收件地址');
    }

    if (this.data.invoiceNeedStatus) {
      let invoiceInfo = this.data.invoiceInfo;

      Object.assign(param, {
        invoices_title: invoiceInfo.invoiceTitleShow,
        invoices_type: invoiceInfo.invoiceType,
        invoice_content: invoiceInfo.invoiceContent,
        buyerTaxNumber: invoiceInfo.taxNumber,
        invoice_payable_type: invoiceInfo.invoiceCompany ? 2 : 1,
        receiverMobile: invoiceInfo.receiver
      });
    }

    if (+param.invoices_type === 2 && !param.receiverMobile) {
      return this.showToast('请填写电子发票接收手机号');
    }

    this.orderSubmiting = true;

    return _queryFromServiceAsync(ensureModel.shoppingSubmit, param).then(res => {
      this.orderSubmiting = false;

      if (res.code !== 200) {
        return this._showModal(res.message);
      }

      let data = res.data;

      // yas上报
      yas.report('YB_SC_ORD', {
        ORD_NUM: data.order_code + '',
        PRD_SKN: this.yasInfo.skns.join(','),
        RPD_SKU: this.yasInfo.skus.join(','),
        PRD_ID: this.yasInfo.pids.join(','),
        ORDER_TYPE: 101 // 101购物车下单,102立即购买下单
      });

      // 上报formID
      commonModel.addWechatFormId({
        order_code: data.order_code,
        openId: app.getOpenID(),
        miniapp_type: app.getMiniappType(),
        formId: this.formId
      });

      data.needJump = true;
      wechatPay(data);
    }).catch(() => {
      this.orderSubmiting = false;
    });
  }
});