var app = getApp();
var $ = require('../../js/util.js');
Page({
	data: {
		goods_list_show:{},
		goods_list_none:{},
    shop_info:{},
    is_lshop:0, // 是否是自己的小店
    lshop_id:0, // 小店id
    is_littleshop:0,// 是否是店主
    user_shop_id:0,
    info: [], // 晋升
    rank_list: [],
    goods_list: [],
    is_show:0,
	  //公共提示
	  hasMore: false,//无更多数据提示
	  dataNull: true,//未获取到数据提示
    add_address:false,
    current_goods:{},//当前选中的商品
    count_total:0,
    count_total_num:0,
    showspec:false,
    speclist: {},
    optionslist: {},//临时存储规格参数
    no_num: [],//临时存储不可点击的规格
    current_spec: {},//临时存储当前选中规格
    showspec:false,
    count_total_num:'',
    count_total:'',
    uid: app.globalData.mid

	},
	onLoad: function (options) {//接收上个页面传的参数
    	var self = this;
      app.globalData.is_key_first=2;
	    if (options.invite_key) {
	      app.globalData.invite_key = options.invite_key;
	    }
	    if (options.lshop_id){
	      app.globalData.lshop_id=options.lshop_id;
	      self.setData({
          lshop_id:options.lshop_id,
          })
	    }
	},
  // 页面隐藏 lshop_id变为自己
  onHide:function(){
    var self = this;
    if(self.data.user_shop_id){
      app.globalData.lshop_id = self.data.user_shop_id;
    }else{
      // app.globalData.lshop_id = 0;
      setTimeout(function(){
        app.globalData.lshop_id = 0;
      },3600000)
    }
    app.setTabBarItem(function(){}); // 更换底部导航
  },
	onShow: function () {
	    //初始化数据
	    var self = this;
	    // app.getUserInfo(function (ret) {
	    //   if (ret.username != ' ') {
	        self.getIndex();
	    //   }
	    // });
	},
	getIndex: function () {
	    var self = this;
	    var action = 'c=LittleShop&a=choice';
	    var method = 'GET';
	    // var data = self.data.user;
      var data = new Object;
    data.lshop_id = app.globalData.lshop_id;
    data.uid = app.globalData.mid;
     var body = $.ObjectToStr(data);
	    app.showLoading('加载中...');
	    app.ajaxRequest(action, method, body, function (ret) {
        if (ret.status == 1 && ret.url) { // 晋升
          var add_address=false;
          if (app.globalData.HCshopid == 0) {
           add_address = true;
          }
          if (ret.data.init_list == '') { ret.data.init_list = new Object; }
          var count_total_num=0;
          var count_total=0;
          var info='';          
          if(ret.data.cart_info.length){
            count_total_num=ret.data.cart_info.cart_num;
            count_total=ret.data.cart_info.cart_total_price;
          }
          if(ret.data.info)info=ret.data.info;
          self.setData({
            info: info,
            rank_list: ret.data.rank_list,
            goods_list: ret.data.goods_list,
            is_show:0,
            current_goods: ret.data.init_list,
            count_total_num: count_total_num,
            count_total: count_total
          })
          self.setTitle('升级权益');
        } else if (ret.status == 1 && !ret.url){
          self.setData({
            goods_list_show: ret.data.goods_list_show,
            goods_list_none: ret.data.goods_list_none,
            shop_info: ret.data.shop_info,
            is_lshop: ret.data.is_lshop,
            lshop_id: ret.data.shop_id,
            is_littleshop: ret.data.is_littleshop,
            user_shop_id: ret.data.user_shop_id,
            is_show: 1,
          })
          self.setTitle('店铺精选');
        }else{
		        app.HCerror('提示', ret.msg); return;
		    }
        app.setTabBarItem(function(){}); // 更换底部导航
	  	})
	},
  // 设置导航标题
  setTitle: function (title) {
    wx.setNavigationBarTitle({
      title: title
    })
  },
  // 商品详情页
  jumtop: function (event) {
    app.HCnavigateTo('../takeout/cont/cont?id=' + event.currentTarget.dataset.id + '&name=' + event.currentTarget.dataset.goodsname);
  },
  // 晋升
  gotoProlev: function (event) {
    var self = this;
    app.HCnavigateTo('../../smallshop/pages/pro_level/pro_level/pro_level');
    if (self.user_shop_id){
      app.globalData.lshop_id = self.user_shop_id;
    }else{
      app.globalData.lshop_id = 0;
    }
    // self.setData({
    //   is_show: 0,
    // })
    // app.globalData.lshop_id = 0;
    // self.getIndex();
    // app.setTabBarItem(function () { }); // 更换底部导航
  },
  // 编辑资料
  gotoEdit: function (event) {
    app.HCnavigateTo('../../smallshop/pages/editinfo/editinfo');
  },
  //下架
  update_myshop: function (event) {
    var self = this;
    var event = event.currentTarget.dataset;
    var bodyparam = new Object;
    bodyparam = new Object;
    bodyparam.goods_id = event.goodsid;
    bodyparam.type = 1;
    var action = 'c=LittleShop&a=update_myshop';
    app.showLoading('加载中...');
    app.ajaxRequest(action, 'POST', bodyparam, function (ret) {
      // console.log(ret);console.log('1-------------');
      if (ret.status == 1) {
        self.getIndex();
      }
    }, true);
  },
  GotoArticle: function (event) {
    app.HCnavigateTo('../../smallshop/pages/pro_level/cont/cont');
  },
  onShareAppMessage: function () {
    return {
      title: this.data.shop_info.name,
      desc: '选择您心仪的宝贝!',
      path: '/' + $.getCurrentPageUrl() + '?invite_key=' + app.globalData.init_invite_key + '&lshop_id=' + app.globalData.lshop_id
    }
  },
  add_cart: function (event) {
    var dataset = event.currentTarget.dataset;
    var current_goods = this.data.current_goods;
    var goods = dataset.id;
    var goods_number = new Object;
    var num = 1;
    var is_add = 1;
    var data = new Object;
    if (dataset.type == '+') {
      is_add = 1;
    } else if (dataset.type == '-') {
      is_add = 0;
    } else if (dataset.type == '=') {
      var value = event.detail.value;
      if (isNaN(value) || value <= 0) {
        num = 1;
      } else {
        num = event.detail.value;
      }
    }
    if (num > parseInt(goods.stock.goods_number)) {
      app.HCerror('提示', '库存不足', false); return;
    }
    data.goods_id = goods.id;
    data.num = num;
    data.is_add = is_add;
    var self = this;
    app.showLoading('加载中...');
    var action = 'c=Takeout&a=add_carts';
    app.ajaxRequest(action, 'POST', data, function (ret) {
      if (ret.status == 1) {
        if (current_goods[goods.id]) {
          current_goods[goods.id].num = ret.cart_num;
        } else {
          current_goods[goods.id] = data;
        }
        if (current_goods[goods.id].num == 0) {
          delete current_goods[goods.id];
        }
        self.setData({
          current_goods: current_goods,
          count_total_num: ret.cart_info.cart_num,
          count_total: ret.cart_info.cart_total_price
        });
      } else {
        app.HCerror('提示', ret.info, false);
      }
    }, true);
  },
  changespec: function (event) {
    var self = this;
    var data = event.currentTarget.dataset.id;
    var current_goods_price_show = $.formatmoney(data.shop_price);
    self.setData({
      showspec: true,
      speclist: data.format_spec.newarr,
      current_goods_id: data.id,
      current_goods_price: data.shop_price,
      current_goods_price_show: current_goods_price_show,
      current_goods_num: 1,
      combination: JSON.parse(data.format_spec.combination),
      combinationpricenum: data.format_spec.combinationpricenum,
      combinationprice: JSON.parse(data.format_spec.combinationprice),
      stock: data.stock
    });
  },
  hidespec: function () {
    this.setData({
      showspec: false,
      optionslist: {},
      no_num: []
    });
  },
  setoptions: function (event) {
    var self = this;
    var no_num = self.data.no_num;
    var data = event.currentTarget.dataset;
    data.id.p_name=data.p_name;
    var optionslist = self.data.optionslist;
    if (data) {
      if (!no_num[data.id.id]) {
        var current_spec = new Object;
        if (optionslist[data.inx] && optionslist[data.inx].id == data.id.id) {
          delete optionslist[data.inx];
        } else {
          optionslist[data.inx] = data.id;
          current_spec[data.inx] = data.id;
        }
        self.setData({
          optionslist: optionslist,
          current_spec: current_spec
        });
        self.checkspec();//使规格变灰色不能选中的方法
        self.count_total_spec();//计算带规格商品的价格
      }
    }
  },
  checkspec: function () {
    var self = this;
    var combination = self.data.combination;
    var speclist = self.data.speclist;
    //当前已经选中的规格
    var current_spec = self.data.current_spec;
    var check = new Object;//除了当前选中的本身之外都需要校验
    for (var i in speclist) {
      for (var j in current_spec) {
        if (i != j) {
          if (!check[i]) {
            check[i] = speclist[i];
          }
        }
      }
    }
    var checkarr = new Array;
    for (var i in current_spec) {
      checkarr.push(current_spec[i].id);
    }
    var no_num = new Object;
    for (var i in check) {
      for (var j in check[i].options) {
        var temparr = checkarr;
        var tempthisarr = new Array;
        tempthisarr.push(check[i].options[j].id);
        temparr = temparr.concat(tempthisarr);
        //判断当前组合是否存在
        var ischeck = true;
        for (var k in combination) {
          if ($.isContained(combination[k], temparr)) {
            ischeck = false; break;
          }
        }
        if (ischeck) {
          no_num[check[i].options[j].id] = check[i].options[j].id;
        }
      }
    }
    self.setData({
      no_num: no_num,
    });
    self.change_goods_spec('no_num');
  },
  change_goods_spec: function (event) {
    var self = this;
    if (event == 'no_num') {
      var types = '';
    } else {
      var types = event.currentTarget.dataset.type;
    }
    var current_goods_num = self.data.current_goods_num;
    var spec_data = new Object;
    var is_add = 1;
    //规格数量
    if (types == '+') {
      is_add = 1;
      current_goods_num = parseInt(current_goods_num) + 1;
    } else if (types == '-') {
      is_add = 0;
      if (parseInt(current_goods_num) > 1) {
        current_goods_num = parseInt(current_goods_num) - 1;
      }
    } else if (types == '=') {
      var value = event.detail.value;
      if (isNaN(value)) {
        current_goods_num = 1;
      } else {
        current_goods_num = value;
      }
    }
    //规格价格
    var optionslist = self.data.optionslist;
    
    
    
    var combinationprice = self.data.combinationprice;
    var combinationpricenum = self.data.combinationpricenum;
    var current_goods = self.data.current_goods;
    var current_goods_id = self.data.current_goods_id;
    var current_goods_price = parseFloat(self.data.current_goods_price) * parseFloat(current_goods_num);
    var current_goods_price_init = parseFloat(self.data.current_goods_price);
    var keyarr = new Array;
    var name = '';
    var t=0;
    for (var i in optionslist) {
      keyarr.push(optionslist[i].id);
      if(t==0){
        name += optionslist[i].p_name + ':'+optionslist[i].optionsval;
      }else{
        name += ' '+optionslist[i].p_name + ':'+optionslist[i].optionsval;
      }
      
      t++;
    }
    keyarr = keyarr.sort();
    var key_str = keyarr.join("_");
    current_goods[current_goods_id] = new Object;
    current_goods[current_goods_id].id = current_goods_id;//商品id
    if (parseInt(combinationpricenum) > 0) {//选完所有的规格属性
      
      if (!current_goods[current_goods_id]) {
        
        current_goods[current_goods_id].num = 0;
  
      }
      
    }
    var format = new Object;
  format.key = key_str;
  format.name = name;
  current_goods[current_goods_id].spec_format = format;
  // current_goods[current_goods_id].price = current_goods_price_init + parseFloat(combinationprice[key_str].attr_price);
  current_goods[current_goods_id].price = combinationprice[key_str] ? combinationprice[key_str].attr_price : 0;
    current_goods_price = parseFloat(current_goods[current_goods_id].price) * current_goods_num;
    //验证库存
    var is_start = true;
    if (parseInt(combinationpricenum) > 0) {
      var stock = self.data.stock;
      if ((current_goods_num + parseInt(current_goods[current_goods_id].num)) > parseInt(stock.goods_stock_number[key_str]) || parseInt(stock.goods_stock_number) == 0) {
        app.HCerror('提示', '【' + name + '】库存不足', false); return;
      }
      is_start = false;
    }
    if (types == 'submit') {
      if (is_start) {
        app.HCerror('提示', '请选择属性规格', false); return;
      }
      self.hidespec();

      current_goods[current_goods_id].num = current_goods_num;

      var data = new Object;
      if (current_goods[current_goods_id].id == current_goods_id) {
        data = current_goods[current_goods_id];
        data.goods_id = current_goods[current_goods_id].id;
        data.goods_attr = JSON.stringify(this.data.current_goods[current_goods_id].spec_format);
        data.is_add = is_add;
      }      
      var self = this;
      app.showLoading('加载中...');
      var action = 'c=Takeout&a=add_carts';
      app.ajaxRequest(action, 'POST', data, function (ret) {
        if (ret.status == 1) {
          self.setData({
            current_goods: current_goods,
            count_total_num: ret.cart_info.cart_num,
            count_total: ret.cart_info.cart_total_price
          });
        } else {
          app.HCerror('提示', ret.info, false);
        }
      }, true);
    }
    //end
    var current_goods_price_show = $.formatmoney(current_goods_price);
    self.setData({
      current_goods_price_show: current_goods_price_show,
      current_goods_num: current_goods_num
    });
    //self.count_total();
  },
  count_total_spec:function(){

  },
  //立即购买
  sub_card:function(){
    var current_goods = this.data.current_goods;
    var param = new Object;
    var current_goods_num = this.data.current_goods_num;
    var current_goods_id = this.data.current_goods_id;
    var goods_attr=0;
    if(!$.isEmptyObject(current_goods))goods_attr=current_goods[current_goods_id].spec_format.key;
    var little_shop_id = app.globalData.HClittle;
    if (little_shop_id == 0) {
      app.HCnavigateTo('../../../smallshop/pages/tuanzhang/near/near');
      return;
    } 
    var current_goods_temp = new Object;
    current_goods_temp.goods_id = parseInt(current_goods_id);
    current_goods_temp.number = parseInt(current_goods_num);
    current_goods_temp.type = 14;
    current_goods_temp.sub_list = JSON.stringify(current_goods);
    current_goods_temp.goods_attr=goods_attr;
    param = current_goods_temp;
    var self = this;
    app.showLoading('加载中...');
    var action = 'c=Takeout&a=buy_nows';
    app.ajaxRequest(action, 'POST', param, function (ret) {
      if (ret.status == 1) {
        app.HCnavigateTo('../buycart/buy_order/buy_order?goods_id=' + ret.goods_id + '&type=' + ret.type + '&number=' + ret.number + '&goods_attr=' + ret.goods_attr);
        // app.HCtoast('添加成功');
        // self.setData({
        //   cart_num: ret.cart_num,
        //   current_goods_num: 1,
        // });
      } else {
        if (ret.data == 'no_mobile') {
          app.HCnavigateTo('../../login/index');
        } else if (ret.data =='is_tuan'){
          app.HCnavigateTo('../../smallshop/pages/tuanzhang/change/change');
        }else{
          if (!ret.msg) ret.msg = '参数错误';
          app.HCerror('提示', ret.msg, false);
        }
      }
    }, true);
  },
  gotoCart:function(){
    app.HCswitchTab('../buycart/index/index');
  },
  gotoUser:function(){
    app.HCswitchTab('../username/index/index');
  }
})