ensure.js 11.4 KB
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'
};

const router = global.router;
const app = getApp();
const yas = new Yas(app);

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
    };

    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);

        return value;
    });

    let selectWay,
        selectTime;

    if (info.deliveryWayList.length) {
        info.deliveryWayList.map((value, index) => {
            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, index) => {
            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: ''
    },
    onLoad(options) {
        this.orderData = options;
        this.yasInfo = {
            skns: [],
            skus: [],
            pids: []
        };
        this.loadEnsurePayment({buyNumber: this.orderData.buyNumber, productSku: this.orderData.productSku});

        yas.pageOpenReport();
    },
    loadEnsurePayment(options, reload) {
        if (options.productSku) {
            this.orderType = ORDER_TYPE.BUYNOW;

            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);
        }

        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 data = res.data || {};

                this.setData({
                    promotionList: data.promotion_formula_list,
                    paymentAmount: data.last_order_amount

                });
            }
        });
    },
    showToast(title) {
        wx.showToast({
            title: title,
            icon: 'none',
            duration: 2000
        });
    },
    chooseAddress() {
        router.go('address', {
            type: 'select',
            id: this.data.choosedAddress.address_id
        });
    },
    chooseAddressCallback(address) {
        this.setData({choosedAddress: address});
    },
    enterAddress() {
        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);
            });
        }

        this.buynowCompute({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');
        }


        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 {
            // 普通购物车下单
        }
    },
    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;

        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(e => {
            this.orderSubmiting = false;
        });
    }
});