var app = getApp();
var $ = require('../../../js/util.js');
var QQMapWX = require('../../../js/qqmap-wx-jssdk.min.js');
var qqmapsdk;
Page({
  data: {
    cart_list:[],//购物车数据
    cart_other_list: [],//购物车其他门店数据
    promot_lists_json:{},//活动规则参数
    price_type_arr:{2:'会员价',3:'促销价'},
    select_all:true,//全选按钮
    checkobj: {},//当前选中的购物车
    activeobj: {},//存取活动优惠
    total_price:0,//结算金额
    total_count: 0,//结算数量
    //换购弹窗
    hg_show:false,
    hg_list: {},//换购商品列表
    hg_checked:{},//选中的换购商品
    hg_cur_key:{},//当前弹窗的参数
    gift_list:{},
    //换购end
    location_n: '',
    longitude:0,
    latitude:0,
    is_show:false,
    show_q: false,
    first:1,
    is_getUserProfile:false,
    info:[]
  },
  onLoad: function (options) {
    app.globalData.is_key_first=2;
    if (wx.getUserProfile){
      this.setData({
        is_getUserProfile:true
      })
    }
  
  },
  onShow: function () {
    //初始化数据
    var self = this;
    app.getUserInfo(function (ret) {
      console.log(ret);
      if (ret) {
        self.setData({
          info: ret,
        });
      }
      if (self.data.info && self.data.info.mobile){
         self.getIndex();
      }
    });
  },
  tolocation: function () {
    app.HCnavigateTo('../../location/location');
  },
  getIndex: function () {
    var self = this;
    var action = 'c=Cart&a=index';
    var first = self.data.first;
    if(first==1){
    app.showLoading('加载中...');
    }
    var data = '&xpoint=' + self.data.longitude + '&ypoint=' + self.data.latitude + '&send=' + app.globalData.send + "&no_auto_hide_toast=true";
    var HCshopid = app.globalData.HCshopid;
    app.ajaxRequest(action, 'GET', data, function (ret) {
      first++;
      if (HCshopid == 0 && app.globalData.HCshopid > 0) {
        self.getIndex(); return;
      }
      //console.log(ret);
      app.hideLoading();//手动隐藏弹窗
      if (ret.status==1){
        var cart_list = new Object;
        var shop_info = new Object;
        var send_desc = '';
        if(ret.list){//单门店
          for (var i in ret.list){
            cart_list = ret.list[i].promot_list;
            shop_info = ret.list[i].shop_info;
            send_desc = ret.list[i].send_desc;
          }
        }
        //处理cart_list，方便调用满赠，加价购
        for (var i in cart_list){
          var newarr = new Array;
          for (var j in cart_list[i].goods_list) {
            newarr.push(cart_list[i].goods_list[j].id);
          }
          cart_list[i].promot_info['cart_key'] = newarr.join("_");
        }
        //end
        cart_list = $.isEmptyObject(cart_list) ? '' : cart_list;
        var other_list=new Object;
        other_list = ret.other_list;
        other_list = $.isEmptyObject(other_list) ? '' : other_list;
        self.setData({
          is_show:true,
          cart_list: cart_list,
          shop_info: shop_info,
          send_desc: send_desc,
          cart_other_list: other_list,
          promot_lists_json: ret.promot_lists_json,
          first:first
        })
        self.select_all_check();
      }else{
        self.setData({
          is_show: true,
          cart_list: [],
          total_price: 0,//结算金额
          total_count: 0,//结算数量
        })
      }
    }, true);
  },
  FNcheckboxAll: function (event){
    var value = event.detail.value;
    if ($.inArray('on',value)){
      this.select_all_check();
      var select_all = true; 
    }else{
      var select_all = false; 
      this.select_all_check_no();
    }
    this.setData({
      select_all: select_all
    })
  },
  FNcheckbox:function(event){
    var self = this;
    var value = event.detail.value;
    var checkobj = self.data.checkobj;
    var len = 0;
    for (var i in checkobj){
      if (!$.inArray(i, value)){
        checkobj[i]['status'] = false; len++;
      }else{
        checkobj[i]['status'] = true;
      }
    }
    var select_all = self.data.select_all;
    var checkobj_num = self.data.checkobj_num;
    if (len == checkobj_num){
      select_all = false;
    } else if (len == 0){
      select_all = true;
    }
    self.setData({
      checkobj: checkobj,
      select_all: select_all
    })
    self.count_total();
  },
  select_all_check:function(){//checkbox全部选中的方法
    var cart_list = this.data.cart_list;
    var checkobj = new Object;
    var newarr = new Array;
    for (var i in cart_list) {
      for (var j in cart_list[i].goods_list) {
        if (cart_list[i].goods_list[j].is_valid!=1)continue;
        var id = cart_list[i].goods_list[j].id;
        var param = new Object;
        param.id = id;
        param.status = true;
        param.act_id = i;
        param.price = parseFloat(cart_list[i].goods_list[j].shop_price);
        param.num = parseInt(cart_list[i].goods_list[j].goods_num);
        checkobj[id] = param;
        newarr.push(id);
      }
    }
    this.setData({
      checkobj: checkobj,
      checkobj_num: newarr.length
    })
    this.count_total();
  },
  select_all_check_no: function () {//checkbox全部不选中的方法
    var checkobj = this.data.checkobj;
    for (var i in checkobj){
      checkobj[i]['status'] = false;
    }
    this.setData({
      checkobj: checkobj
    })
    this.count_total();
  },
  del_cart:function(event){
    this.done_del_cart(event.currentTarget.dataset.id);
  },
  clear_out_cart:function(){
    this.done_del_cart('del_out_all');
  },
  done_del_cart: function (id) {
    if(!id)return;
    var self = this;
    app.HCerror('提示', '确认删除？', true, function (ret) {
      if (ret.confirm) {
        var data = new Object;
        var action = 'c=Cart&a=del_cart';
        app.showLoading('加载中...');
        data.id = id;
        app.ajaxRequest(action, 'POST', data, function (ret) {
          if (ret.status == 1) {
            app.HCtoast('删除成功');
            var cart_list = self.data.cart_list;
            for (var i in cart_list) {
              for (var j in cart_list[i].goods_list) {
                if (cart_list[i].goods_list[j].id == data.id) {
                  cart_list[i].goods_list.splice(j, 1);
                }
              }
              if ($.isEmptyObject(cart_list[i].goods_list)){
                delete cart_list[i];//活动下没有商品后，隐藏该活动
              }
            }
            cart_list = $.isEmptyObject(cart_list) ? '' : cart_list;
            self.setData({
              cart_list: cart_list,
              is_show:true
            })
            if (id =='del_out_all'){
              self.setData({
                cart_other_list: []
              })
            }
            self.select_all_check_no();
          } else {
            app.HCerror('提示', '删除失败', false);
          }
        }, true);
      }
    })
  },
  change_cart_con: function (event) {
    var self = this;
    var dataset = event.currentTarget.dataset;
    var checkobj = self.data.checkobj;
    var thisid = dataset.id;
    var is_add=1;
    if (checkobj[thisid]){
      if (dataset.type == '+') {
         is_add = 1;        
        checkobj[thisid].num = parseInt(checkobj[thisid].num) + 1;
      } else if (dataset.type == '-') {
        if (parseInt(checkobj[thisid].num) > 1) {
          is_add = 0; 
          checkobj[thisid].num = parseInt(checkobj[thisid].num) - 1;
        }else{
          self.done_del_cart(thisid);return;
        }
      } else if (dataset.type == '=') {
        var value = event.detail.value;
        if (isNaN(value)) {
          checkobj[thisid].num = 1;
        } else {
          checkobj[thisid].num = value;
        }
      }
      var action = 'c=Cart&a=add_cart';
      var data=new Object;
      data.cart_id = dataset.id;
      data.goods_id=dataset.goodsid;
      data.num = checkobj[thisid].num;
      data.is_add=is_add;
      data.is_cart=1;
      app.showLoading('加载中...');
      app.ajaxRequest(action, 'POST', data, function (ret) {
          if(ret.status!=1){
            checkobj[thisid].num = checkobj[thisid].num - 1;
            app.HCerror('提示', ret.msg, false)
            
          }else{
            // 3-13 zjn
            self.setData({
              checkobj: checkobj
            });
            self.count_total();
          }
      },true)

    }
  },
  count_total:function(){
    var self = this;
    var checkobj = self.data.checkobj;
    var activeobj = new Object;
    var promot_lists_json = JSON.parse(self.data.promot_lists_json);
    var total_price = 0;//计算出购物车总价
    var total_price_arr = new Object;//临时存储各个活动商品的总价
    for (var i in checkobj){
      if (checkobj[i].status){//计算选中商品的价格属性
        if (checkobj[i].act_id > 0) {//计算活动价
          if (total_price_arr[checkobj[i].act_id])continue;//避免重复计算活动总价
          var this_act = new Object;
          if (!$.isEmptyObject(promot_lists_json)){
            this_act = promot_lists_json[checkobj[i].act_id];
          }
          if (!$.isEmptyObject(this_act)){
            var act_name = this_act['act_name'];
            var min_amount = parseFloat(this_act['min_amount']);//金额下限
            var max_amount = parseFloat(this_act['max_amount']);//金额上限
            var act_type = this_act['act_type'];//类型:1满减2满折3满赠4加价购
            var act_type_ext = parseFloat(this_act['act_type_ext']);//优惠值
            var is_addup = this_act['is_addup'];//当活动为满减时 是否叠加
            var act_price = 0;//当前活动下商品总价
            for (var j in checkobj) {
              if (checkobj[j].act_id == checkobj[i].act_id && checkobj[j].status){
                act_price = act_price + (checkobj[j].num * parseFloat(checkobj[j].price));
              }
            }
            var orig_prices = act_price;//商品原价
            var demo_prices = act_price//商品原价
            //满足活动最低价
            if (act_price >= min_amount) {
              if (act_type == 1) {
                if (is_addup == 1) {
                  if (max_amount && act_price >= max_amount) { demo_prices = max_amount; }
                  if (min_amount > 0) act_price = act_price - (Math.floor(demo_prices / min_amount) * act_type_ext);
                } else {
                  act_price = act_price - act_type_ext;
                }
              } else if (act_type == 2) {
                act_price = act_price * (act_type_ext / 100);
              } else if (act_type == 3){
                  activeobj[checkobj[i].act_id] = new Object;
                  activeobj[checkobj[i].act_id].act_type = 3;
              } else if (act_type == 4) {
                  activeobj[checkobj[i].act_id] = new Object;
                  activeobj[checkobj[i].act_id].act_type = 4;
                  //叠加加价购的价格
                  // total_price = total_price + parseFloat(act_type_ext);
                  if (this.data.cart_list[checkobj[i].act_id].gift_list){
                    total_price = total_price + parseFloat(act_type_ext);
                  }
                  
              } else if (act_type == 0){
                //限时促销按普通商品走
                
                total_price = total_price + (checkobj[i].num * parseFloat(checkobj[i].price));
              }
              if (orig_prices != act_price){
                activeobj[checkobj[i].act_id] = new Object;
                // activeobj[checkobj[i].act_id].act_desc = '已优惠：￥' + $.formatmoney(parseFloat(orig_prices) - parseFloat(act_price));
              }
              total_price_arr[checkobj[i].act_id] = act_price;//存入这个活动下总价
            } else {
              if (act_type == 3 || act_type == 4){
                activeobj[checkobj[i].act_id] = new Object;
                activeobj[checkobj[i].act_id].act_desc = '还差￥' + $.formatmoney(parseFloat(min_amount) - parseFloat(act_price)) + ',去凑单>';
              }
              if (act_type == 2 || act_type == 1) {
                activeobj[checkobj[i].act_id] = new Object;
                activeobj[checkobj[i].act_id].act_desc = '还差￥' + $.formatmoney(parseFloat(min_amount) - parseFloat(act_price)) + ',去凑单>';
              }
              //按普通商品价格计算
              total_price = total_price + (checkobj[i].num * parseFloat(checkobj[i].price));
            }
          }else{
            //处理有活动id，但是没有活动规则
            total_price = total_price + (checkobj[i].num * parseFloat(checkobj[i].price));
          }
        } else {//计算普通商品价格
          total_price = total_price + (checkobj[i].num * parseFloat(checkobj[i].price));
        }
      }
    }
    for (var i in total_price_arr){//普通商品价格加上活动商品价格
      total_price = total_price + total_price_arr[i];
    }
    total_price = $.formatmoney(total_price);
    
    var total_count = 0;
    for (var i in checkobj){
      if (checkobj[i].status){
        total_count+=checkobj[i].num;
      } 
    }

    self.setData({
      total_price: total_price,
      checkobj: checkobj,
      activeobj:activeobj,
      total_count: total_count
    });
  },
  hide_hg:function(){
    this.setData({
      hg_show: false
    });
  },
  hg_goods:function(event){

    var data = new Object;
    var self = this;
    var action = 'c=Cart&a=change_pro_goods';
    app.showLoading('加载中...');
    data.pro_id = event.currentTarget.dataset.id;
    data.cart_ids = event.currentTarget.dataset.key;
    var hg_cur_key = self.data.hg_cur_key;
    hg_cur_key = data;
    var hg_checked = new Object;
    var cart_list = self.data.cart_list;
    //使弹窗带上默认值
    for (var i in cart_list) {
      if (i == data.pro_id){
        if (cart_list[i].gift_list && cart_list[i].gift_list.id>0){
          hg_checked[cart_list[i].gift_list.id] = cart_list[i].gift_list;
        }
        break;
      }
    }
    //end
    app.ajaxRequest(action, 'POST', data, function (ret) {
     // console.log(ret);
      if(ret.status==1){
        var hg_list = new Object;
        if (ret.data.goods_info) { hg_list = ret.data.goods_info; }
        self.setData({
          hg_show: true,
          hg_list: hg_list,
          hg_cur_key: hg_cur_key,
          hg_checked: hg_checked
        });
      }else{
        if (!ret.msg) ret.msg = '参数错误';
        app.HCerror('提示',ret.msg,false)
      }
    }, true);
  },
  check_goods:function(event){
    var self = this;
   // var hg_checked = self.data.hg_checked;
    var hg_list = self.data.hg_list;
    var id = event.currentTarget.dataset.id;
    var hg_checked = self.data.hg_checked;
    var checkcode = false;
    if (!$.isEmptyObject(hg_checked)){
      if (!hg_checked[id]){
        checkcode = true;
      }else{
        checkcode = false;
      }
      var hg_checked = new Object;
    }else{
      checkcode = true;
    }
    if (checkcode){
      for (var i in hg_list) {
        if (hg_list[i].goods_id == id) {
          hg_checked[id] = hg_list[i];
        }
      }
    }
    this.setData({
      hg_checked: hg_checked
    });
  },
  sub_hg_goods:function(){
    var self = this;
    var action = 'c=Cart&a=add_pro_goods';
    var hg_checked = self.data.hg_checked;
    var cart_list = self.data.cart_list;
    var hg_checked_arr = new Array;
    for (var i in hg_checked){
      hg_checked_arr = hg_checked[i];
    }
    var data = new Object;
    data = self.data.hg_cur_key;
    if ($.isEmptyObject(hg_checked)) {
      data.id = '';
      data.goods_attr = '';
    }else{
      data.id = hg_checked_arr.goods_id;
      data.goods_attr = hg_checked_arr.goods_attr;
    }
    app.showLoading('加载中...');
    app.ajaxRequest(action, 'POST', data, function (ret) {
      if (ret.status == 1) {
        //重新渲染当前页面的赠品或者加价购的商品
        for (var i in cart_list){
          if (i == data.pro_id){
            cart_list[i].gift_list = hg_checked_arr;
            break;
          }
        }
      }
      self.hide_hg();
      self.setData({
        cart_list: cart_list
      });
    }, true);
  },
  go_buy:function(){
    app.HCswitchTab('../../takeout/index/index');
  },
  gotoPromat: function (event) {
    app.HCnavigateTo('../../activity/cont/cont?id=' + event.currentTarget.dataset.id + '&cart_id=' + event.currentTarget.dataset.key);
  },
  GotoCont: function (event) {
    app.HCnavigateTo('../../takeout/cont/cont?id=' + event.currentTarget.dataset.id + '&name=' + event.currentTarget.dataset.goodsname);
  },
  sub_cart:function(){
    var checkobj = this.data.checkobj;
    var cart_ids=new Object;
    var i;
    for (i in checkobj){
      if (checkobj[i].status==true){
        cart_ids[i] = checkobj[i];
      }
    }
    var data=new Object;
    data.cart_ids = JSON.stringify(cart_ids)
    if ($.isEmptyObject(cart_ids)){
      app.HCerror('提示','请至少选择一件商品',false);return;
    }
    var action ="c=Cart&a=sub_cart";
    app.showLoading('加载中...');
    app.ajaxRequest(action, 'POST', data, function (ret) {
      if(ret.status==1){
        app.HCnavigateTo('../buy_order/buy_order?cart_ids=' + ret.cart_ids+'&type='+ret.type);
      }else{
        app.HCerror('提示', ret.msg, false); return;
      }
       
    }, true);
  },
  gotoCart: function () {
    app.HCswitchTab('../../buycart/index/index');
  },
  //获取用户信息授权
  bindGetUserInfo: function (e) {
    var self = this;
    if (wx.getUserProfile){
      wx.getUserProfile({
        desc:'用于完善会员资料',
        success:function(res){
          app.HCsetStorage('profile_Users', res.userInfo);
          app.HCsetStorage('profile_iv', res.iv);
          app.HCsetStorage('profile_encryptedData', res.encryptedData);
          app.getUserInfo(function (ret) {  
            self.setData({
              show_q: false,
              info: ret,
            })
            if ($.is_empty(ret.mobile) && e.detail.userInfo) {
              app.HCnavigateTo('../../login_accredit/login_accredit');
            }
          })
        }
      })
    }else{
      app.getUserInfo(function (ret) {
        self.setData({
          show_q: false,
          info: ret,
        })
        if ($.is_empty(ret.mobile) && e.detail.userInfo) {
          app.HCnavigateTo('../../login_accredit/login_accredit');
        }
      })
    }
  },
  //下拉刷新
  onPullDownRefresh: function () {
    this.getIndex();
    wx.stopPullDownRefresh();
  },
})