var app = getApp();
var $ = require('../../../js/util.js');
Page({
  data: {
    list: [],
    page: 1,//当前页码
    param: {},
    paramfilter: ['shop_price', 'updatetime', 'sell_count'],
    //公共提示
    hasMore: false,//无更多数据提示
    dataNull: true,//未获取到数据提示
    hg_show:false,
    title_class: { 'default':true},
    Countdowndata:{},
    hg_checked: {},//选中的换购商品
    speclist: {},
    optionslist: {},//临时存储规格参数
    no_num: [],//临时存储不可点击的规格
    current_spec: {},//临时存储当前选中规格
    showspec: false,
    show_msg:''
  },
  onLoad: function (options) {
    var self = this;
    if (options.invite_key) {
      app.globalData.invite_key = options.invite_key;
    }
    if (options.id) {
      this.setData({
        param: {
          id: options.id,
          cart_id: options.cart_id,
        },
      });
    }
  },
  onReady: function () {
    var self = this;
    app.getUserInfo(function (ret) {
      if (ret) {
        self.getData();
      }
      self.getData();
    });
  },
  getData: function (callback) {
    var self = this;
    app.showLoading('加载中...');
    var action = 'c=Activity&a=index';
    var body = $.ObjectToStr(self.data.param);
    app.ajaxRequest(action, 'GET', body, function (ret) {
      //console.log(ret);
      if (ret.status == 1) {
        var gift_id=0;
        if (ret.gift_id){
          gift_id = ret.gift_id
        }
        self.setData({
          action_info: ret.actinfo,
          gift_list:ret.gift_list,
          gift_id: gift_id,
          cart_num: ret.cart_num,
          current_goods: ret.init_list
        })
        //使弹窗带上默认值
        var hg_checked = self.data.hg_checked;
        if(ret.gift_list){
          for (var i in ret.gift_list) {
            if (ret.gift_list[i].id == gift_id) {
              hg_checked[ret.gift_list[i].id] = ret.gift_list[i];
              break;
            }
          }
        }
        if (ret.actinfo.act_type==3){
          self.setData({
            show_msg:'查看赠品'
          })
        } else if (ret.actinfo.act_type == 4){
          self.setData({
            show_msg: '换购商品'
          })
        }

        setInterval(function(){
          var Countdowndata = $.Countdown(ret.actinfo.end_time);
          self.setData({
            Countdowndata: Countdowndata,
          })
        },1000);
        $.init_page_list(self, ret.goods_info.list);
      } else if (ret.status == 2){
        self.setData({
          action_info: ret.actinfo,
          gift_list: ret.gift_list,
          gift_id: gift_id,
          cart_num: ret.cart_num,
          current_goods: ret.init_list
        })
        setInterval(function () {
          var Countdowndata = $.Countdown(ret.actinfo.end_time);
          self.setData({
            Countdowndata: Countdowndata,
          })
        }, 1000);
        $.init_page_empty_list(self, ret.msg);
      } else{
        app.HCerror('提示', ret.msg, false);
      }
    },true)
  },
  onReachBottom: function () {
    var self = this;
    var param = self.data.param;
    param.page = 1;
    param.page++;
    self.setData({
      param: param
    });
    self.getData();
  },
  onPullDownRefresh: function () {
    this.setData({
      list: [],
      page: 1,
      param: {},
      hasMore: false,
      dataNull: true
    });
    this.getData();
  },
  change_title:function(event){
    var index = event.currentTarget.dataset.index;
    var self = this;
    var title_class = self.data.title_class;
    var paramfilter = self.data.paramfilter;
    var param = self.data.param;
    param.page = 1;
    param.filter = new Object;
    if (index == 'default'){
      var title_class = new Object;
      title_class['default'] = true;
    } else{
      title_class['default'] = false;
      if (title_class[index]&&title_class[index]=='up'){
        var title_class = new Object;
        title_class[index] = 'cup';
        param.filter[paramfilter[index]] = 1;
      }else{
        var title_class = new Object;
        title_class[index] = 'up';
        param.filter[paramfilter[index]] = 2;
      }
    }
    for (var i in param.filter){
      param[i] = param.filter[i];
    }
    self.setData({
      title_class: title_class,
      param: param
    });
    self.getData();
  },
  hg_goods:function(event){
    var self = this;
    var hg_list = self.data.gift_list;
    var gift_id = self.data.gift_id;
    var hg_checked = self.data.hg_checked;
    //使弹窗带上默认值
    for (var i in hg_list) {
      if (hg_list[i].id == gift_id) {
        hg_checked[hg_list[i].id] = hg_list[i];
        break;
      }
    }
    this.setData({
      hg_show:true,
      hg_checked: hg_checked
    })
  },
  hide_hg:function(event){
    this.setData({
      hg_show: false
    })
  },
  check_goods: function (event) {
    var self = this;
    // var hg_checked = self.data.hg_checked;
    var hg_list = self.data.gift_list;
    var id = event.currentTarget.dataset.id;
    var item = event.currentTarget.dataset.item;
    //console.log(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].id == id) {
          hg_checked[id] = hg_list[i];
        }
      }
    }
    this.setData({
      hg_checked: hg_checked,
      gift_id:id,
    });
  },
  
  sub_hg_goods: function () {
    var self = this;
    var action = 'c=Cart&a=add_pro_goods';
    var hg_checked = self.data.hg_checked;
    var cart_id = self.data.param.cart_id;
    var hg_checked_arr = new Array;
    for (var i in hg_checked) {
      hg_checked_arr = hg_checked[i];
    }
    var data = new Object;
    if ($.isEmptyObject(hg_checked)) {
      data.id = '';
      data.goods_attr = '';
    } else {
      data.id = hg_checked_arr.id;
      data.goods_attr = hg_checked_arr.goods_attr;
    }
    if (cart_id){
      data.cart_ids = cart_id;
    }
    data.pro_id = self.data.param.id;
    app.showLoading('加载中...');
    app.ajaxRequest(action, 'POST', data, function (ret) {
      if (ret.status != 1) {
        app.HCerror('提示', ret.msg, false);
      }
      self.hide_hg();
    }, true);
  },
  addcart:function(event){
    var dataset = event.currentTarget.dataset;
    var current_goods = this.data.current_goods;
    // console.log(current_goods);
    var sub_param=new Object;
    var goods = dataset.id;
    if (current_goods[goods.id]) {
      var this_goods = current_goods[goods.id];
      this_goods.num = parseInt(this_goods.num) + 1;
      if (this_goods.num > parseInt(goods.stock.goods_number)) {
        app.HCerror('提示', '库存不足', false); return;
      }
      current_goods[goods.id] = this_goods;
    } else {
      if (1 > parseInt(goods.stock.goods_number)) {
        app.HCerror('提示', '库存不足', false); return;
      }
      var data = new Object;
      data.id = goods.id;
      data.price = goods.shop_price;
      data.num = 1;
      current_goods[goods.id] = data;
    }
    this.setData({
      current_goods: current_goods
    });
    this.count_total();
    this.addGoodsCart();
   // this.count_total();
  },
  hidespec: function () {
    this.setData({
      showspec: false,
      optionslist: {},
      no_num: []
    });
  },
  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
    });
  },
  setoptions: function (event) {
    var self = this;
    var no_num = self.data.no_num;
    var data = event.currentTarget.dataset;
    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;
    //规格数量
    current_goods_num =1;
    
    //规格价格
    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 = '';
    for (var i in optionslist) {
      keyarr.push(optionslist[i].id);
      name += optionslist[i].optionsval + ' ';
    }
    if ((keyarr.length == parseInt(combinationpricenum)) && parseInt(combinationpricenum) > 0) {//选完所有的规格属性
      keyarr = keyarr.sort();
      var key_str = keyarr.join("_");
      if (!current_goods[key_str]) {
        current_goods[key_str] = new Object;
        current_goods[key_str].id = current_goods_id;//商品id
        current_goods[key_str].num = 0;
        var format = new Object;
        format.key = key_str;
        format.name = name;
        current_goods[key_str].spec_format = format;
        // current_goods[key_str].price = current_goods_price_init + parseFloat(combinationprice[key_str].attr_price);
        current_goods[key_str].price = combinationprice[key_str] ? combinationprice[key_str].attr_price : 0;
      }
      current_goods_price = parseFloat(current_goods[key_str].price) * current_goods_num
    }
    //验证库存
    var is_start = true;
    if ((keyarr.length == parseInt(combinationpricenum)) && parseInt(combinationpricenum) > 0) {
      var stock = self.data.stock;
      if ((current_goods_num + parseInt(current_goods[key_str].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();
      if (current_goods[key_str]) {
        current_goods[key_str].num = parseInt(current_goods[key_str].num) + parseInt(current_goods_num);
      } else {
        current_goods[key_str].num = current_goods_num;
      }
      self.setData({
        current_goods: current_goods,
      });
    }
    //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();
    if (types == 'submit') {
      self.addGoodsCart();
    }
  },
  count_total_spec: function () {

  },
  count_total: function () {
    var current_goods = this.data.current_goods;
    var count_total = 0;
    var count_total_num = 0;
    for (var i in current_goods) {//检查清空当前无效的数据
      if (i == "") {
        delete current_goods[i];
      }
    }
    for (var i in current_goods) {
      var thisnum = parseInt(current_goods[i].num);
      count_total = count_total + parseInt(current_goods[i].price) * thisnum;
      count_total_num = count_total_num + thisnum;
    }
    count_total = $.formatmoney(count_total);
    this.setData({
      count_total: count_total,
      count_total_num: count_total_num
    });
  },
  addGoodsCart:function(){
    var self=this;
    var current_goods = JSON.stringify(this.data.current_goods);
    var action = 'c=Takeout&a=add_cart';
    var param = new Object;
    param.sub_list = current_goods;
    app.ajaxRequest(action, 'POST', param, function (ret) {
      if (ret.status == 1) {
        app.HCtoast('添加成功');
        self.setData({
          cart_num: ret.cart_num
        })
        //app.HCswitchTab('../../buycart/index/index');
      } else {
        if (!ret.msg) ret.msg = '参数错误';
        app.HCerror('提示', ret.msg, false);
      }
    }, true);
  },
  //跳转优惠券详情
  goToDetaile: function (event) {
    app.HCnavigateTo('../cont/cont?id=' + event.currentTarget.dataset.gid);
  },
  gotoCart: function () {
    app.HCswitchTab('../../buycart/index/index');
  }
})