cart.js 12.5 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
import wx from '../../utils/wx';
import formatImage from '../../utils/formatImage';
import detailModel from '../../models/product/detail';
import cartModel from '../../models/cart/cart';
import cartHandle from '../../models/cart/cart-handle';

import Picker from '../goodsDetail/picker/picker';

const app = getApp();
const router = global.router;

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

    args.shift();

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

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

Page({
  data: {
    isEditing: false,
    pickerData: {
      view: {
        isShow: false,
        isSoldOutSoon: false,
        goodsList: [],
        sizeList: [],
        image: '',
        goodPrice: '',
        price: '',
        buyNumber: 1,
        minusButtonEnable: false,
        plusButtonEnable: true,
        buyButtonEnable: true,
        buy_limit_number: 0,
        bundle_count: 0
      },
      sourceType: 'goodsDetail'
    }
  },
  onLoad() {
    Picker.init(this);
  },
  onShow() {
    this.getCartData();
  },
  onHide: function() {
    if (this.data.isEditing) {
      this.editCartStatus({clearEditing: true});
    }
  },
  showToast(title) {
    wx.showToast({
      title: title,
      icon: 'none',
      duration: 1000
    });
  },
  showModal(title, options) {
    return wx.showModal(Object.assign({
      title: '',
      content: title,
      cancelText: '取消',
      confirmText: '确认',
      confirmColor: '#d0021b'
    }, options));
  },
  goShopping() {
    router.go('home');
  },
  handleOrdinaryCartData(data) {
    let resData = cartHandle.formatOrdinaryCartData(data, true);

    this._allGoodsList = resData.allGoodsList;
    delete resData.allGoodsList;
    this.setData(resData);
    this._oldOrdinaryCartData = resData;

    return resData;
  },
  getCartData() {
    _queryFromServiceAsync(cartModel.getCartData).then(res => {
      if (res.code === 200 && res.data) {
        return this.handleOrdinaryCartData(res.data);
      } else {
        return Promise.reject();
      }
    }).catch(() => {
      this.setData({isEmptyCart: true});
    });
  },
  editCartStatus(e) {
    let data = {isEditing: !this.data.isEditing};

    if (e.clearEditing) {
      data.isEditing = false;
    }

    if (!data.isEditing && this.data.isSelectAll !== this._oldOrdinaryCartData.isSelectAll) {
      data.isSelectAll = this._oldOrdinaryCartData.isSelectAll;
    }

    this._removeGoodsList = {};
    this.setData(data);
  },
  editCart(list, selected) {
    list = cartHandle.changeGoodsListData(list, selected);

    if (!list.length) {
      return Promise.resolve({});
    }

    return _queryFromServiceAsync(cartModel.selectAndQueryCart, {
      product_sku_list: JSON.stringify(list)
    }).then(res => {
      if (res && res.code === 200 && res.data) {
        return this.handleOrdinaryCartData(res.data);
      } else {
        return Promise.reject({});
      }
    }).catch(() => {
      this.setData(this._oldOrdinaryCartData);
    });
  },
  removeCartGoodsAsync(list) {
    list = cartHandle.changeGoodsListData(list);

    if (!list.length) {
      return Promise.resolve({});
    }

    return _queryFromServiceAsync(cartModel.removeAndQueryCart, {
      product_sku_list: JSON.stringify(list)
    }).then(res => {
      if (res && res.code === 200) {
        return this.handleOrdinaryCartData(res.data);
      }
    });
  },
  touchStartAction(e) {
    let touchKey = `wrap${e.timeStamp}`;

    if (e.detail && e.detail.indexKey) {
      touchKey = e.detail.indexKey;
    }

    this.setData({touchKey});
  },
  showMorePromotion(e) {
    let pid = e.currentTarget.dataset.pid;
    let promotionMoreStatus = this.data.promotionMoreStatus || {};

    promotionMoreStatus[pid] = !promotionMoreStatus[pid];
    this.setData({promotionMoreStatus});
  },
  navToPromotionPage(e) {
    let pItem = e.currentTarget.dataset.promotion;
    let promotion_type = pItem.promotion_type;

    let gStatus = (+pItem.status === 10 || +pItem.status === 30);

    if (promotion_type === 'Gift' && gStatus) {
      router.go('cartGift', {
        promotion_id: pItem.promotion_id,
        is_gift: 1,
        status: pItem.status
      });
    } else if (promotion_type === 'Needpaygift' && gStatus) {
      router.go('cartGift', {
        promotion_id: pItem.promotion_id,
        status: pItem.status
      });
    } else {
      router.go('productSearch', {
        title: '优惠活动商品',
        promotionTitle: pItem.promotion_title,
        promotionId: pItem.promotion_id
      });
    }
  },
  navToGiftPage(e) {
    let promotion = e.currentTarget.dataset.promotion;

    if (promotion.showArrow) {
      router.go('cartGift', {
        promotion_id: promotion.promotion_ids,
        is_gift: promotion.isGift ? 1 : 0,
        status: 10
      });
    }
  },
  chooseGoodsItem(e) {
    let item = e.detail;

    this.editCart([item]);
  },
  chooseGoodsBundle(e) {
    let bundle = e.detail;

    this.editCart(bundle.goods_list, bundle.selected);
  },
  editGoodsNum(e) {
    let goods = e.detail;

    if (goods) {
      return _queryFromServiceAsync(cartModel.editCartGoodsNum, {
        product_sku: goods.product_sku
      }, goods.isAdd).then(res => {
        if (res && res.code === 200) {
          this.editCart([goods], 'Y');
        }
      });
    }
  },
  editBundleNum(e) {
    let bundle = e.detail;

    if (bundle) {
      return _queryFromServiceAsync(cartModel.editCartBundleNum, {
        activity_id: bundle.pool_id,
        batch_no: bundle.pool_batch_no
      }, bundle.isAdd).then(res => {
        if (res && res.code === 200) {
          this.editCart(bundle.goods_list, 'Y');
        }
      });
    }
  },
  editGoodsColorSize(e) {
    let goods = e.detail;
    let pickData = this.data.pickerData;

    this._cureditGoods = goods;

    pickData.view.should_hidden_number_view = (goods.bundle_activity_id && goods.batch_no);
    pickData.view.min_buy_number = goods.min_buy_number > 0 ? goods.min_buy_number : 1;

    detailModel.productInfo(goods.product_skn).then(res => {
      if (res && res.code === 200) {
        let ImgUrls = [];
        let color_length = 0;

        if (res.data.goods_list) {
          color_length = res.data.goods_list.length;
        }
        res.data.goods_list.map((item, index) => {
          let images = item.images_list;

          ImgUrls = [...ImgUrls, ...images];
          if (index === 0 && color_length === 1) {
            item.selected = true;
            this.data.colorSelected = true;
            this.data.selectedProductId = item.goods_id;
          }
        });

        let isSoldOutSoon = false;
        let tags = res.data.tags;

        if (tags) {
          isSoldOutSoon = tags.includes('is_soon_sold_out');
        }

        pickData.view.goodsList = res.data.goods_list;
        pickData.view.isSoldOutSoon = isSoldOutSoon;

        // 默认显示第一种颜色的尺码
        pickData.view.sizeList = res.data.goods_list.length ? res.data.goods_list[0].size_list : [];

        let plusButtonEnable = false;
        let minusButtonEnable = false;

        // 根据库存设置该尺码是否可以选择
        let size_length = 0;

        if (pickData.view.sizeList) {
          size_length = pickData.view.sizeList.length;
        }

        pickData.view.sizeList && pickData.view.sizeList.map((item, index) => {
          item.enable = item.storage_number > 0;
          if (index === 0 && size_length === 1 && this.data.colorSelected) {
            // 当颜色被选中 并且只有一个size 时 才会自动 做选中尺码操作
            pickData.view.buyButtonEnable = item.enable;
            if (item.enable) {
              item.selected = true;
              plusButtonEnable = item.storage_number > 1;
              this.setData({
                selectedSKU: item.product_sku,
                storageNumber: item.storage_number
              });
            }
          }
        });

        pickData.view.plusButtonEnable = plusButtonEnable;
        pickData.view.minusButtonEnable = minusButtonEnable;
        pickData.view.image = formatImage.image(ImgUrls.length > 0 ? ImgUrls[0].image_url : '', 168, 232);
        pickData.view.price = res.data.format_market_price;
        pickData.view.goodPrice = res.data.format_sales_price;


        this.setData({
          pickerData: pickData
        });
        Picker.pickerShow(this);
      }
    }).catch(err => {
      this.showToast(err.code + err.message + '');
    });
  },
  removeGoodsListInEdit(e) {
    let info = e.detail;

    if (info.goods_list) {
      let list = info.goods_list || [];

      list.map(item => {
        this._removeGoodsList[item.indexKey] = info.selected === 'Y' ? item : false;
      });
    } else {
      this._removeGoodsList[info.indexKey] = info.selected === 'Y' ? info : false;
    }
  },
  mutilRemoveGoods() {
    let removeList = [];

    this._removeGoodsList = this._removeGoodsList || [];

    for (let i in this._removeGoodsList) {
      if (this._removeGoodsList.hasOwnProperty(i) && this._removeGoodsList[i]) {
        removeList.push(this._removeGoodsList[i]);
      }
    }

    if (!removeList.length) {
      return this.showToast('请勾选您要删除的商品');
    }

    this.showModal('是否删除选中的全部商品?').then(res => {
      if (res.confirm) {
        this.removeCartGoodsAsync(removeList);
      }
    });
  },
  removeGoods(e) {
    this.showModal('是否删除选中商品?').then(res => {
      if (res.confirm) {
        this.removeCartGoodsAsync([e.detail]);
      }
    });
  },
  cleanInvalidGoods() {
    this.showModal('是否确认清空所有失效商品?').then(res => {
      if (!res.confirm) {
        return;
      }

      let invalidGoods = this.data.invalidGoodsList;
      let invalidList = [];

      if (invalidGoods && invalidGoods.length) {
        invalidGoods.map(list => {
          invalidList.push.apply(invalidList, list);
        });
      }

      return this.removeCartGoodsAsync(invalidList);
    });
  },
  selectAllGoods() {
    let isSelectAll = this.data.isSelectAll;

    if (this.data.isEditing) {
      isSelectAll = !isSelectAll;

      this.setData({
        isSelectAll: isSelectAll,
        isEditSelectAll: isSelectAll ? 'Y' : 'N'
      });
      return;
    }

    this.editCart(this._allGoodsList, isSelectAll ? 'N' : 'Y').then(res => {
      if (!isSelectAll && res && res.hasLowStorage) {
        this.showToast('您全选的商品中存在库存不足商品,已帮您自动取消勾选成功');
      }
    });
  },
  paymentAction: function() {
    // 如果没有选中商品则不能进入结算页
    if (this.data.shoppingCartData.selected_goods_count <= 0) {
      return this.showToast('您还没有选择宝贝哦');
    }

    if (this.data.matchGiftIds && this.data.matchGiftIds.length > 0) {
      return this.showModal('您还未选择赠品,是否去选择赠品?', {
        cancelText: '不要赠品',
        confirmText: '去选择',
        confirmColor: '#444444',
        cancelColor: '#444444',
      }).then(res => {
        if (res.confirm) {
          // TODO 去选择赠品
          // that.navToChooseGiftPage();
        } else if (res.cancel) {
          // 直接跳转 结算页面
          router.go('cartEnsure');
        }
      });
    }
    router.go('cartEnsure');
  },

  hidePicker(e) {
    if (e.target.id === 'picker-bg') {
      Picker.pickerHide(this);
    }
  },
  confirmChoose() {
    let sku = this.data.selectedSKU;

    if (!sku) {
      return this.showToast('请选择颜色或尺码');
    }

    let buyNumber = this.data.pickerData.view.buyNumber;
    let min_buy_number = this.data.pickerData.view.min_buy_number > 0 ? this.data.pickerData.view.min_buy_number : 1;

    if (buyNumber > 0 && buyNumber < min_buy_number && min_buy_number !== 1) {
      return this.showToast('最低' + min_buy_number + '件起');
    }

    let goods = this._cureditGoods;
    let goodsInfo = [{
      old_product_sku: goods.product_sku,
      new_product_sku: sku,
      buy_number: buyNumber,
      activity_id: goods.bundle_activity_id,
      batch_no: goods.batch_no,
      selected: 'Y',
    }];

    return _queryFromServiceAsync(cartModel.editCartGoods, {
      swap_data: JSON.stringify(goodsInfo)
    }).then(res => {
      if (res && res.code === 200) {
        this.editCart([{
          buy_number: buyNumber,
          goods_type: goods.goods_type,
          product_sku: sku,
          promotion_id: goods.promotion_id,
          selected: 'Y',
        }], 'Y');
        Picker.pickerHide(this);
        this.clearPickerData && this.clearPickerData();
      }
    });
  },
  ...Picker.pickerAction
});