var app = getApp();
var $ = require('../../js/util.js');
var is_first = 1;
Page({
  data: {
    searchlist: [],
    catch_search: [],
    keyword: '',
    param: {
      keyword: '',
      page: 1,
      no_auto_hide_toast: true//关闭自动隐藏弹窗
    },
    current_catid: 0,
    current_order: 0,
    current_childcatid: 0,
    current_screen: [],
    current_brand: [],
    cate_list: [],
    list: [],
    order_list: [],
    screen_list: [],
    menuType: 0,
    isVisible: false,
    animationData: {},
    current_goods: {},//当前选中的商品
    count_total: 0,
    count_total_num: 0,
    showspec: false,
    speclist: {},
    optionslist: {},//临时存储规格参数
    no_num: [],//临时存储不可点击的规格
    current_spec: {},//临时存储当前选中规格
    location_n: '',
    add_address: false,
    hasMore: false,
    dataNull: true,
    show_q: false,
    temp_code: 0,
    brand_list: [],//品牌
    cate_img: true,
    total_page: 1,
    cate_show: 0, //二级展开
    cate_hieght: 0,
    is_keyword: 0,
    is_getUserProfile:false,
    is_sell: 0
  },
  onLoad: function (options) {
    var self = this;
    if (app.globalData.catch_search) {
      self.setData({
        keyword: options.keyword,
        catch_search: app.globalData.catch_search,
      });
    }
    if (wx.getUserProfile){
      self.setData({
        is_getUserProfile:true
      })
    }
    app.getUserInfo(function () {
      self.getIndex();
    });
   
  },
  getIndex: function () {
    var self = this;
    var action = 'c=Search&a=index';
    app.showLoading('加载中...');
    app.ajaxRequest(action, 'GET', '', function (ret) {
      self.setData({
        searchlist: ret.data,
      });
    });
  },
  clear_catch: function () {
    app.globalData.catch_search = [];
    this.setData({
      catch_search: [],
    });
  },
  binddesc: function (event) {
    var value = event.detail.value;
    var param = this.data.param;
    param.keyword = value;
    if (value) {
      this.setData({
        keyword: value,
        param: param,
      });
    } else {
      this.setData({
        is_keyword: 0
      })
    }
  },
  GotoSearch: function (event) {
    var self = this;
    var param = self.data.param;
    param.page = 1;
    param.hasMore = false;
    param.dataNull = true;
    if (event.currentTarget.dataset.keyword) {
      param.keyword = event.currentTarget.dataset.keyword;
      self.setData({
        keyword: event.currentTarget.dataset.keyword,
        param: param,
        list: [],
      })
    }
    if (self.data.keyword == '') {
      app.HCerror('提示', '请输入要搜索的内容', false); return;
    }
    // app.HCchangeData(1, self.data.keyword, function (ret) {

    if (!$.inArray(self.data.keyword, app.globalData.catch_search)) {
      app.globalData.catch_search.push(self.data.keyword);
    }
    app.globalData.search_keyword = self.data.keyword;
    self.setData({
      catch_search: app.globalData.catch_search,
    })
    self.get_list();
    // })
  },

  //搜索结果列表
  get_list: function () {
    var self = this;
    self.setData({
      is_keyword: 1
    })
    if (is_first == 1) {
      app.showLoading('加载中...');
    }
    //app.showLoading('加载中...');
    var action = 'c=Takeout&a=index';
    var param = self.data.param;
    param.is_first = is_first;
    param = $.ObjectToStr(self.data.param);
    var HCshopid = app.globalData.HCshopid;
    // is_first++;
    app.ajaxRequest(action, 'GET', param, function (ret) {
      // console.log(ret); console.log('3*****');
      app.hideLoading();//手动隐藏弹窗
      if (app.globalData.HCshopid == 0) {
        var add_address = true;
        self.setData({
          add_address: add_address
        })
      }
      if (ret.status == 1) {
        if (ret.data) {
          if (ret.data.init_list == '') { ret.data.init_list = new Object; }
          self.setData({
            current_goods: ret.data.init_list,
          });
          if (ret.data.init_list) {
            app.HCsetStorage('catch_current_goods', ret.data.init_list)
          }
          if (ret.data.goods_list) {
            $.init_page_list(self, ret.data.goods_list);
          }
          var is_empty = true;
          if (ret.data.goods_list == '') {
            $.init_page_empty_list(self, ret.msg);
          }
          // self.get_goods_price();
          self.setData({
            count_total_num: ret.cart_info.cart_num,
            count_total: ret.cart_info.cart_total_price,
            is_empty: is_empty,
            goods_count: ret.data.goods_count,
            total_page: ret.data.totalpage,
            is_sell: ret.data.is_sell

          });
          if (self.data.current_catid == 0) {
            self.setData({
              current_catid: ret.data.catid,
            })
            app.HCsetStorage('current_catid', ret.data.catid);
          }
          app.globalData.search_keyword = '';
        }
      } else if (ret.status == 2) {
        self.setData({
          total_page: 0
        });
        $.init_page_empty_list(self, ret.msg);
      }
    }, true);
  },
  get_goods_price: function () {
    var self = this;
    var goods_id = new Array;
    var goods_list = self.data.list
    for (var i in goods_list) {
      goods_id.push(goods_list[i].id);
    }
    var postdata = new Object;
    postdata.goods_ids = goods_id;
    var action = 'c=Takeout&a=get_goods_price';
    var HCshopid = app.globalData.HCshopid;
    postdata.shop_id = HCshopid
    app.ajaxRequest(action, 'POST', postdata, function (ret) {
      if (ret.status == 1) {
        var goods_price_info = ret.data;
        for (var i in goods_price_info) {
          for (var j in goods_list) {
            if (goods_list[j].id == goods_price_info[i].id) {
              goods_list[j].shop_price = goods_price_info[i].shop_price;
              goods_list[j].sprice = goods_price_info[i].sprice;
            }
          }
        }
        self.setData({
          list: goods_list,
        });
      }
    }, true)
  },
  onReachBottom: function () {
    var self = this;
    var param = self.data.param;
    param.page++;
    self.setData({
      param: param
    });
    self.get_list();
  },



  //加入购物车
  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';
    // console.log(data); console.log('1----------'); return false;
    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({
            show_add: false,
            show_cart: 'show',
          })
        } else {
          self.setData({
            show_add: true,
            show_cart: 'hide',
          })
        }
        self.setData({
          current_goods: current_goods,
          count_total_num: ret.cart_info.cart_num,
          count_total: ret.cart_info.cart_total_price
        });
        self.get_cart(self.data.count_total_num);
      } else {
        if (ret.data == 'no_tan') {
          app.HCnavigateTo('../../../smallshop/pages/tuanzhang/change/change');
          return;
        } 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;
    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 = '';
    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();

      current_goods[key_str].num = current_goods_num;

      var data = new Object;
      if (current_goods[key_str].id == current_goods_id) {
        data = current_goods[key_str];
        data.goods_id = current_goods[key_str].id;
        data.goods_attr = JSON.stringify(this.data.current_goods[key_str].spec_format);
        data.is_add = is_add;
      }
      var self = this;
      app.showLoading('加载中...');
      // console.log(data); console.log('p---------'); return false;
      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 () {

  },
  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
    });
  },
  gotoaddress: function () {
    app.HCnavigateTo('../../userinfo/add_address/add_address');
  },
  // GotoCont: function (event){   
  //   app.HCnavigateTo('../cont/cont?id=' + event.currentTarget.dataset.id + '&name=' + event.currentTarget.dataset.goodsname);
  // },
  GotoCont: function (event) {
    var pt_id = event.currentTarget.dataset.pt_id;
    var pt_price = event.currentTarget.dataset.pt_price;
    var is_overdue = event.currentTarget.dataset.is_overdue;
    var is_ptdue = event.currentTarget.dataset.is_ptdue;
    if (pt_id && pt_price > 0 && is_ptdue == 0) {
      app.HCnavigateTo('../../spellgroup/pages/fightgroup/cont/cont?id=' + event.currentTarget.dataset.id + '&name=' + event.currentTarget.dataset.goodsname);
    } else {
      app.HCnavigateTo('../takeout/cont/cont?id=' + event.currentTarget.dataset.id + '&name=' + event.currentTarget.dataset.goodsname);
    }

  },
  ClearKeyword: function () {
    var self = this;
    var param = self.data.param;
    var current_catid = self.data.current_catid;
    if (current_catid == 'search') {
      current_catid = 0;
    }
    param.keyword = '';
    self.setData({
      param: param,
      current_catid: current_catid
    })
    self.get_list();
  },
  onShareAppMessage: function () {
    return {
      title: '商品',
      desc: '选择您心仪的宝贝!',
      path: '/' + $.getCurrentPageUrl() + '?invite_key=' + app.globalData.init_invite_key
    }
  },
  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');
        }
      })
    }
  },
  get_cart: function (num) {
    var number = num
    if (number > 0) {
      wx.setTabBarBadge({
        index: 1,
        text: "" + number + ""
      })
    } else {
      wx.removeTabBarBadge({
        index: 1,
      })
    }
  },
})