var app = getApp();
var $ = require('../../../../js/util.js');
let SCREEN_WIDTH = 750
Page({
  data: {
    array: [{
      mode: 'scaleToFill',
      text: 'scaleToFill：不保持纵横比缩放图片，使图片完全适应'
    }],
    imgUrls: [],
    indicatorDots: true,//轮播图上的小点
    autoplay: true,//是否自动播放
    interval: 3000,//轮播图切换间隔
    duration: 1000,//轮播图间隔动画
    showspec:false,
    attr_list:{},
    optionslist: {},//临时存储规格参数
    no_num: [],//临时存储不可点击的规格
    current_spec: {},//临时存储当前选中规格
    current_goods: {},//当前选中的商品
    count_total: 0,
    count_total_num: 0,
    activity_list:{},//优惠活动
    Countdowndata: {},
    // 初始化的宽高
    cropperInitW: SCREEN_WIDTH,
    cropperInitH: SCREEN_WIDTH,
    group_list:[],
    time:0,
  },
  onLoad: function (options) {//接收上个页面传的参数
    if (options.id) {
      this.setData({
        param: {
          id: options.id,
          type:0
        },
      });
    }
    if(options.order_id){
      var param=this.data.param;
      param.order_id = options.order_id;
      this.setData({
        param:param
      })
    }
    app.HCsetNavigationBarTitle(options.name);
    if (options.invite_key) {
      app.globalData.invite_key = options.invite_key;
    }
  },
  onReady: function () {
    // app.HCgetlocation(function(ret){
    //   console.log(ret);
    // });
    //初始化数据
    var self = this;
    app.getUserInfo(function (ret) {
      //console.log(ret);
      if (ret) {
        self.getIndex();
      }
    });
      //self.getIndex();
  },
  getIndex: function () {
    var self = this;
    var action = 'c=FightGroup&a=cont';
    var param = $.ObjectToStr(self.data.param);
    app.showLoading('加载中...');
    app.ajaxRequest(action, 'GET', param, function (ret) {
      if(ret && ret.status==1){
        self.setData({
          goods_info:ret.goods_info,
          imgUrls: ret.goods_info.goods_imgs,
          goods_attrs: ret.goods_attrs,
          attr_list: ret.goods_attrs.newarr,
          common_list: ret.commlist,
          dp_count: ret.dp_count,
          combination: ret.goods_attrs.combination,
          combinationpricenum: ret.goods_attrs.combinationpricenum,
          combinationprice: JSON.parse(ret.goods_attrs.combinationprice),
          current_goods_price: ret.goods_info.min_price,
          current_goods_price_show: $.formatmoney(ret.goods_info.min_price),
          current_goods_num: 1,
          
          current_goods_id: ret.goods_info.goodsid
        });
        if (ret.group_list){
          self.setData({
            group_list: ret.group_list,
          })
          self.countDown();
        }
        if (ret.time){
          self.setData({
            time: ret.time
          })
        }
        if (ret.goods_info.stock){
          self.setData({
            stock: ret.goods_info.stock,
          })

        }
        self.getdetialIndex();
      }else{
        app.HCerror('提示', ret.msg, false); return;
      }
      
    },true);
  },
  countDown: function () {
    var list = this.data.group_list;
    for (var i in list) {
      list[i].Countdowndata = $.Countdown(list[i].end_time);
    }
    this.setData({
      group_list: list
    })
    setTimeout(this.countDown, 1000);
  },
  changespec:function(event){
    var self=this;
    self.setData({
      showspec:true,
    })
  },
  getdetialIndex: function () {
    var self = this;
    var action = 'c=Takeout&a=cont_detial';
    var param = $.ObjectToStr(self.data.param);
   // app.showLoading('加载中...');
    app.ajaxRequest(action, 'GET', param, function (ret) {
      if (ret && ret.status == 1) {
        self.setData({
          info: ret.data.replace(/\<img/gi, '<img style="max-width:100%;height:auto;float:left;" '),
        })
        // self.setData({
        //   info: ret.data
        // });
        // if (ret.data) {
        //   WxParse.wxParse('HCcontent', 'html', ret.data, self);
        // }
      } else {
        app.HCerror('提示', ret.msg, false); return;
      }
    });
  },
  setoptions: function (event){
    var self = this;
    var no_num = self.data.no_num;
    var data = event.currentTarget.dataset;
    var optionslist = self.data.optionslist;
    data.id.p_name=data.p_name;
    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();//使规格变灰色不能选中的方法
        
      }
    }
  },
  hidespec: function () {
    this.setData({
      showspec: false,
      optionslist: {},
      no_num: []
    });
  },
  checkspec: function () {
    var self = this;
    var combination = JSON.parse(self.data.combination);
    var speclist = self.data.attr_list;
    //当前已经选中的规格
    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;
    //规格数量
    if (types == '+') {
      current_goods_num = parseInt(current_goods_num) + 1;
    } else if (types == '-') {
      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].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 ((keyarr.length == parseInt(combinationpricenum)) && 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(self.data.current_goods_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[current_goods_id].num)) > parseInt(stock.goods_stock_number[key_str])) {
      //   app.HCerror('提示', '【' + name + '】库存不足', false); return;
      // }
      is_start = false;
    }
    if (types == 'submit') {
      if (is_start) {
        self.changespec(); return;
        //app.HCerror('提示', '请选择属性规格', false); return;
      }
      self.hidespec();
      if (current_goods[current_goods_id]) {
        current_goods[current_goods_id].num = parseInt(current_goods[current_goods_id].num) + parseInt(current_goods_num);
      } else {
        current_goods[current_goods_id].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();
  },
  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
    });
  },
  collect_goods: function (event){
    var self=this;
    var goods_id = event.currentTarget.dataset.id;
    var action = 'c=Takeout&a=collect_goods';
    var param = $.ObjectToStr(self.data.param);
    app.showLoading('加载中...');
    app.ajaxRequest(action, 'GET', param, function (ret) {
      if(ret && ret.status==1){
        self.setData({
          is_collect:1
        })
      }else{
        self.setData({
          is_collect:0
        })
      }
    },true)
  },
  //图文详情
  gotoDetial:function(event){
    app.HCnavigateTo('../cont_detial/cont_detial?id=' + event.currentTarget.dataset.id);
  },
  //优惠活动跳转
  gotoPromat: function (event){
    app.HCnavigateTo('../../activity/cont/cont?id=' + event.currentTarget.dataset.id);
  },
  gotoComment:function(event){
    app.HCnavigateTo('../../comment/list/list?id=' + event.currentTarget.dataset.id);
  },
  gotoCart: function (event) {
    app.HCswitchTab('../../../../pages/buycart/index/index');
  },
//立即购买
  sub_card:function(){
    var current_goods = this.data.current_goods;
    var goods_info = this.data.goods_info;
    var goods_attrs = this.data.goods_attrs;
    var current_goods_num = this.data.current_goods_num;
    var param = this.data.param;
    if (goods_attrs.combinationnum > 0) {
      if ($.isEmptyObject(current_goods)) {
        this.setData({
          showspec:true
        })
        return;
        //app.HCerror('提示', '请选择属性规格', false); return;
      }
    }
    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;
    var goods_attr=0;
    if(!$.isEmptyObject(current_goods))goods_attr=current_goods[param.id].spec_format.key;
    current_goods_temp.goods_id = goods_info.goodsid;
    current_goods_temp.number = current_goods_num;
    current_goods_temp.type = 6;
    current_goods_temp.price = goods_info.min_price;
    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('加载中...');
    console.log(goods_attrs);
    var action = 'c=Takeout&a=sub_cart';
    app.ajaxRequest(action, 'POST', param, function (ret) {
      if (ret.status == 1) {
        app.HCnavigateTo('../../../../pages/buycart/buy_order/buy_order?goods_id=' + ret.data.goods_id + '&type=' + ret.data.type + '&number=' + ret.data.number + '&pid=' + self.data.goods_info.pid + '&pt_id=' + self.data.goods_info.pt_id + '&goods_attr=' + ret.data.goods_attr);
        // app.HCtoast('添加成功');
        // self.setData({
        //   cart_num: ret.cart_num,
        //   current_goods_num: 1,
        // });
      } else {
        if (ret.data == 'no_mobile') {
          app.HCnavigateTo('../../../../pages/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);
  },
  onShareAppMessage: function () {
    return {
      title: this.data.goods_info.goods_name,
      desc: '选择您心仪的宝贝!',
      path: '/' + $.getCurrentPageUrl() + '?invite_key=' + app.globalData.init_invite_key+'&id='+this.data.param.id
    }
  },
  LookBigimg: function (event) {
    var imgsrc = event.currentTarget.dataset.item;
    app.HCpreviewImage(imgsrc);
  },
  
  onshare:function(){
    wx.showShareMenu({
      withShareTicket: true
    })
  },
  GotoBuy: function (event) {
    app.HCnavigateTo('../cont_group/cont_group?order_id=' + event.currentTarget.dataset.id);
  },
  GotoGoods:function(event){
    app.HCnavigateTo('../../../../pages/takeout/cont/cont?id=' + event.currentTarget.dataset.id + '&name=' + event.currentTarget.dataset.goods_name);
  }
})