const getReq = require('../../config.js').getReq
import Bundle from '../../utils/Bundle'
import recordSource from '../../utils/recordSource'
import bonusUp from '../../utils/bonusUp';
let app = getApp()
Page({
  data: {
    loadAnimation: true,
    free_info: [],
    summary: [],
    cart_list: [],
    n_cart_list: [],
    all_checked: false,
    allPrice: 0,
    allGoodsPrice: 0,
    hasmore: false,
    curpage: 0,
    special_datas: {},
    prop_special: [],
    summery: [],
    canShow: false,
    fromSource: '',
    firstLoad: true,
    tipsFlag: false,
    tipsDatas: null
  },
  onLoad: function () {

  },
  onShow: function () {
    this.setData({
      loadAnimation: true,
      free_info: [],
      summary: [],
      cart_list: [],
      n_cart_list: [],
      all_checked: false,
      allPrice: 0,
      allGoodsPrice: 0,
      hasmore: false,
      curpage: 0,
      special_datas: {},
      prop_special: [],
      summery: [],
      tipsFlag: false,
      tipsDatas: null
    });
    this.req_datas();
    this.getFavorite()
    // if (app.globalData.userInfo) {
    //   setTimeout(() => {
    //     bonusUp((tipsFlag, tipsDatas) => {
    //       this.setData({
    //         tipsFlag,
    //         tipsDatas
    //       })
    //     })
    //   }, 0);
    // }
  },
  getFavorite() {
    let self = this
    getReq(app,{
      act: 'member_bonus',
      op: 'match_goodsex',
      curpage: 1
    }, function (res) {
      if (res.code == 200) {
        let special_datas = res.datas
        let prop_special = res.datas.special_list
        let summery = res.datas.summary
        self.setData({
          special_datas,
          prop_special,
          summery
        })
      }
    })
  },
  getCartList(cart_list, summary, bundling) {
    let summaryMap = new Map()
    let bundlingMap = new Map()
    summary.map(item => {
      summaryMap.set(item['goods_id'], item)
    })
    if (bundling.length) {
      bundling.map(item => {
        bundlingMap.set(item['bl_id'], item)
      })
    }
    let n_cart_list = new Bundle(cart_list, summaryMap, bundlingMap).createOrders()
    return n_cart_list
  },

  req_datas() {
    let self = this;
    let fromSource = this.data.fromSource

    if (this.data.firstLoad) {
      fromSource = recordSource(app, `act=cart&op=list&minest_cartid=${self.data.curpage}&client_type=mini`);
      this.setData({
        fromSource: app.globalData.fromSource
      })
    }
    else {
      app.setFromSource(this.data.fromSource)
    }
    getReq(app,{
      act: 'cart',
      op: 'list',
      minest_cartid: self.data.curpage,
      from: fromSource
    }, function (res) {
      if (res.code == 200) {
        let hasmore = res.datas.mobile_page.hasmore;
        let free_info = res.datas.free_info;
        let summary_datas = res.datas.summary;
        let cart_list = res.datas.cart_list;

        let bundling = res.datas.bundling
        let summary = [];
        if (cart_list.length <= 0) {
          self.setData({
            free_info: free_info || self.data.free_info,
            loadAnimation: false,
            canShow: true
          });
          return;
        }
        for (let item of cart_list) {
          item.checked = false;
        }
        for (let i = 0; i < cart_list.length; i++) {
          for (let j = 0; j < summary_datas.length; j++) {
            if (cart_list[i].goods_id == summary_datas[j].goods_id) {
              summary.push(summary_datas[j]);
              break;
            }
          }
        }
        if (hasmore) {
          let lastCartListId = cart_list[cart_list.length - 1].cart_id;
          self.setData({
            hasmore: true,
            curpage: lastCartListId
          })
        }
        else {
          self.setData({
            canShow: true,
            hasmore: false
          })
        }
        cart_list = self.getCartList(cart_list, summary_datas, bundling);
        let localSummary = self.data.summary;
        let localCartList = self.data.cart_list;
        self.setData({
          free_info: free_info || self.data.free_info,
          summary: localSummary.concat(summary),
          cart_list: localCartList.concat(cart_list),
          loadAnimation: false,
          firstLoad: false
        });

      }
    })
  },
  goods_checked(e) {
    let cartid = e.currentTarget.dataset.cartid;
    let cart_list = this.data.cart_list;
    let all_checked_state = 0;
    for (let item of cart_list) {
        if (item.cart_id == cartid) {
        item.checked = !item.checked;
      }
    }
    for (let item of cart_list) {
      if (item.checked) {
        all_checked_state = all_checked_state + 1;
      }
    }

    if (all_checked_state == cart_list.length) {
      all_checked_state = true;
    }
    else {
      all_checked_state = false;
    }
    this.setData({
      cart_list,
      all_checked: all_checked_state
    });
    this.total();
  },
  all_checked() {
    let cart_list = this.data.cart_list;
    let all_checked_state = this.data.all_checked;
    for (let item of cart_list) {
      item.checked = !all_checked_state;
    }
    this.setData({
      cart_list,
      all_checked: !all_checked_state
    });
    this.total();
  },
  req_goods_num(cart_id, quantity, callback) {
    let self = this;
    getReq(app,{
      act: 'cart',
      op: 'edit',
      cart_id,
      quantity
    }, function (res) {
      if (res.code == 200) {
        let goods_num = res.datas.goods_num;
        let cart_list = self.data.cart_list;
        for (let item of cart_list) {
          if (item.cart_id == cart_id) {
            item.goods_num = goods_num;
          }
        }
        self.setData({
          cart_list
        });
        callback;
        for (let i = 0; i < self.data.cart_list.length; i++) {
          if (self.data.cart_list[i].checked) {
            self.total();
            break;
          }
        }
      }
      else {
        wx.showToast({
          title: res.message,
          icon: "none"
        })
      }
    })
  },
  goods_num_handle(e) {
    let self = this;
    let cart_id = e.target.dataset.cartid;
    let num = e.target.dataset.num;
    let compute_function = e.target.dataset.function;
    let goods_id = e.target.dataset.goodsid;
    let quantity = 1;
    if (compute_function == 'add') {
      quantity = num + quantity;
      this.req_goods_num(cart_id, quantity);
    }
    else {
      quantity = num - quantity;
      if (quantity <= 0) {
        this.cancal_cart(e, goods_id, cart_id);
      }
      else {
        self.req_goods_num(cart_id, quantity);
      }
    }
  },
  del_cart(cart_id, goods_id) {
    let summary = this.data.summary;
    let cart_list = this.data.cart_list;
    for (let i = 0; i < summary.length; i++) {
      if (summary[i].goods_id == goods_id) {
        summary.splice(i, 1);
      }
    }
    for (let i = 0; i < cart_list.length; i++) {
      if (cart_list[i].goods_id == goods_id) {
        cart_list.splice(i, 1);
      }
    }
    this.setData({
      summary,
      cart_list
    })
  },
  cancal_cart(e, goodsid, cartid) {
    let self = this;
    let goods_id = e.target.dataset.goodsid || goodsid;
    let cart_id = e.target.dataset.cartid || cartid;
    wx.showModal({
      title: "提示",
      content: "确定要删除吗？",
      success: function (res) {
        if (res.confirm) {
          self.req_goods_num(cart_id, 0, self.del_cart(cart_id, goods_id));
        } else if (res.cancel) {
          return;
        }
      }
    })
  },
  total() {
    let self = this;
    let cart_item = [];
    for (let item of this.data.cart_list) {
      if (item.checked) {
        cart_item.push(item.cart_id);
      }
    }
    if (cart_item.length <= 0) {
      self.setData({
        allPrice: 0,
        allGoodsPrice: 0
      })
    }
    let carts = cart_item.join(",");
    getReq(app,{
      act: 'member_buy',
      op: 'calc_cash',
      ifcart: 1,
      cart_id: carts
    }, function (res) {
      if (res.code == 200) {
        let { payinfo } = res.datas
        let allPrice = parseFloat(payinfo['pay_car_pred'])
        let allGoodsPrice = parseFloat(payinfo['pay_car_nopred'])
        self.setData({
          allPrice,
          allGoodsPrice
        })
      }
    })
  },
  onReachBottom() {
    let self = this;
    let hasmore = this.data.hasmore;
    if (hasmore) {
      let req_curpage = this.data.curpage;
      getReq(app,{
        act: 'cart',
        op: 'list',
        minest_cartid: req_curpage
      }, function (res) {
        self.req_datas();
      })
    }
  },
  settlement() {
    const cart_id_list = [];
    for (let cart_item of this.data.cart_list) {
      if (cart_item.checked) {
        cart_id_list.push(cart_item.cart_id);
      }
    }
    if (cart_id_list.length <= 0) {
      wx.showToast({
        title: "请最少选择一件商品",
        icon: "none"
      });
      return;
    }
    let cart_list = cart_id_list.join(',');
    app.navigateto(`/pages/confirmOrder/confirmOrder?iscart=1&cart_id=${cart_list}`)
  },
  skip_index() {
    app.switchtab("/pages/index/index")
  },
  toDetails(e) {
    let goods_id = e.currentTarget.dataset.goodsid
    app.navigateto(`/pages/details/details?goods_id=${goods_id}&title=商品详情`)
  },
  closeTips() {
    this.setData({
      tipsFlag: false,
      tipsDatas: null
    })
  }
})
