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:{},//优惠活动
    lg_info:{},//小店商品信息 jxr
    is_show: 0, //jxr
    isshop_show: 0, //jxr
    Countdowndata: {},
    // 初始化的宽高
    cropperInitW: SCREEN_WIDTH,
    cropperInitH: SCREEN_WIDTH,
    recomm_info:[],//猜你喜欢
    //分享
    share: 0,
    tw_share: 0,
    img_url: '',
    share_img: '',
    template: {},
    template2: {},
    windowHeight: 0,
    is_getUserProfile:false,
    is_shop_id: 0,//门店id
  },
  //立即购买
  sub_card: function () {
    var self = this;
    var goods_info = self.data.goods_info;
    app.getUserInfo(function (ret) {
      if ($.is_empty(ret.username)) {
        self.setData({
          show_q: true
        })
      } else {
        var user_info = ret;
        if ($.is_empty(user_info.mobile)) {
          app.HCnavigateTo('../../login/index');
          return;
        }
        var current_goods = self.data.current_goods;
        var goods_attrs = self.data.goods_attrs;
        var current_goods_num = self.data.current_goods_num;
        var param = self.data.param;
        if (goods_attrs.combinationnum > 0) {
          if ($.isEmptyObject(current_goods)) {
            self.setData({
              showspec: true
            })
            return;
            //app.HCerror('提示', '请选择属性规格', false); 
          }
        }
        var current_goods_temp = new Object;
        current_goods_temp.goods_id = goods_info.goods_id;
        current_goods_temp.number = current_goods_num;
        current_goods_temp.type = 14;
        current_goods_temp.price = goods_info.min_price;
        current_goods_temp.sub_list = JSON.stringify(current_goods);
        param = current_goods_temp;

        app.showLoading('加载中...');
        var action = 'c=Takeout&a=buy_nows';
        app.ajaxRequest(action, 'POST', param, function (ret) {
          //console.log(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);
          } else {
            if (ret.data == 'no_mobile') {
              app.HCnavigateTo('../../login_accredit/login_accredit');
            } else {
              if (!ret.msg) ret.msg = '参数错误';
              app.HCerror('提示', ret.msg, false);
            }
          }
        }, true);
      }
    });
  },
  onLoad: function (options) {//接收上个页面传的参数
    if (options.id) {
      this.setData({
        param: {
          id: options.id,
          type:0
        },
      });
    }
    if (options.name){
      app.HCsetNavigationBarTitle(options.name);
    }
    
    if (options.invite_key) {
      app.globalData.invite_key = options.invite_key;
    }
    if (options.lshop_id){ // 分享的小店商品 保存该小店
      app.globalData.lshop_id=options.lshop_id;
    }
    if (wx.getUserProfile){
      this.setData({
        is_getUserProfile:true
      })
    }
  },
  onReady: function () {
    // app.HCgetlocation(function(ret){
    //   console.log(ret);
    // });
    //初始化数据
    var self = this;
    self.setData({
      is_shop_id: app.globalData.HCshopid
    })
    app.getUserInfo(function (ret) {
      //console.log(ret);
        self.getIndex();
    });
  },
  getIndex: function () {
    var self = this;
    var action = 'c=Takeout&a=cont';
    var param = $.ObjectToStr(self.data.param);
    app.showLoading('加载中...');
    app.ajaxRequest(action, 'GET', param, function (ret) {
      if(ret && ret.status==1){
        self.setData({
          template: ret.shareimg,
          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,
          stock: ret.goods_info.stock,
          current_goods_id: ret.goods_info.goods_id,
          is_collect: ret.goods_info.is_collection,
          cart_num: ret.cart_num,
          promat_info:ret.promat_info,
          lg_info: ret.lg_info,
         
          recomm_info: ret.recommend,
          is_share_show:0,//分享
          is_fuwu_show:0,//服务
        });
        if (ret.isshop_show){
          self.setData({
            isshop_show: ret.isshop_show,
          })
        }
        app.HCsetNavigationBarTitle(ret.goods_info.goods_name);
        if (ret.activelist) {
          self.setData({ 
            activity_list: ret.activelist
            })
        }
        if(ret.promat_info.id){
          setInterval(function () {
            var Countdowndata = $.Countdown(ret.promat_info.end_time);
            self.setData({
              Countdowndata: Countdowndata
            })
          }, 1000);
        }
        //jxr start
        if (ret.lg_info && ret.lg_info.is_putaway==0) {
          self.setData({
            is_show:1 
          })
        }
        //jxr end
        setTimeout(function () {
          self.getdetialIndex();
        }, 1000)
        
      }else{
        app.HCerror('提示', ret.msg, false); return;
      }
      
    },true);
  },
  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;" '),
        })
      } else {
        // app.HCerror('提示', ret.msg, false); return;
        self.setData({
          info: '',
        })
      }
    });
  },
  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;
          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].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 ((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;
      }
      
    }
    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);
    if(keyarr.length>0){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 ((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) {
        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('../../buycart/index/index');
  },
  gotocont:function(event){
    if(event.currentTarget.dataset.is_overdue==0 && event.currentTarget.dataset.pt_id>0){
      app.HCnavigateTo('../../../spellgroup/pages/fightgroup/cont/cont?id=' + event.currentTarget.dataset.id + '&name=' + event.currentTarget.dataset.name);
    }else{
      this.setData({
        param: {
          id: event.currentTarget.dataset.id,
          type:0
        },
      });
      this.getIndex();
    }
  },
  /**
   * 加入购物车
   */
  add_cart:function(){
    var current_goods = this.data.current_goods;
    var goods_attrs = this.data.goods_attrs;
    var current_goods_num = this.data.current_goods_num;
    if (goods_attrs.combinationnum>0){
      if ($.isEmptyObject(current_goods)){
        app.HCerror('提示', '请选择属性规格', false); return;
      }
    }else{
      var goods_info = this.data.goods_info;
      var current_goods_temp = new Object;
      var current_goods = new Object;
      current_goods[goods_info.goods_id] = new Object;
      current_goods_temp.id = goods_info.goods_id;
      current_goods_temp.num = current_goods_num;
      current_goods_temp.price = goods_info.min_price;
      current_goods[goods_info.goods_id] = current_goods_temp;
    }
    var self = this;
    // app.showLoading('加载中...');
    var action = 'c=Takeout&a=add_cart';
    var param = new Object;
    for (var i in current_goods){
      current_goods[i].num = current_goods_num;
    }
    param.sub_list = JSON.stringify(current_goods);
    param.add_type = 'cont';
    app.ajaxRequest(action, 'POST', param, function (ret) {
      if (ret.status == 1) {
        app.HCtoast('添加成功');
        self.setData({
          cart_num: ret.cart_num,
          current_goods_num:1,
        });
      } 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 + '&lshop_id=' + app.globalData.lshop_id,
      imageUrl: this.data.share_img
    }
  },
  onImgOK(e) {
    console.log(123);
     console.log(e.detail.path);
    this.setData({ share_img: e.detail.path });
  },
  onImgOK2(e) {
    //console.log(e);
    this.setData({ img_url: e.detail.path });
  },
  LookBigimg: function (event) {
    var imgsrc = event.currentTarget.dataset.item;
    app.HCpreviewImage(imgsrc);
  },
  getmatter: function (event) {
    var goods_id = event.currentTarget.dataset.goods_id;
    app.HCnavigateTo('../../userinfo/posters/index?goods_id=' + goods_id);
  },
  //下架
  update_myshop: function (event) {
    var self = this;
    var event = event.currentTarget.dataset;
    var bodyparam = new Object;
    bodyparam = self.data.param;
    bodyparam.goods_id = event.id;
    bodyparam.shop_id = event.lshop_id;
    bodyparam.type = event.type;
    var action = 'c=LittleShop&a=update_myshop';
    app.showLoading('加载中...');
    app.ajaxRequest(action, 'POST', bodyparam, function (ret) {
      // console.log(ret);
      if (ret.status == 1) {
        if (event.type==0){
          self.setData({
            is_show: 1,
          });
        }else{
          self.setData({
            is_show: 0,
          });
        }
      }
    }, true);
  },
  // 分享
  get_share:function(event){
    this.setData({
      is_share_show: 1,
    });
  },
  // 服务
  openfuwu:function(event){
    var self = this;
    self.setData({
      is_fuwu_show: 1,
    });
  },
  saveformid: function (e) {
    var formId = e.detail.formId;
    if (formId) app.saveformid(formId);
  },
  // 关闭遮罩
  close_mask:function(event){
    var self = this;
    self.setData({
      is_fuwu_show: 0,
      is_share_show: 0,
      showspec:false,
      tw_share:0,
    });
  },
  // 图文分享
  popmask: function () {
    var self = this;
    var action = 'c=Takeout&a=cont_tgercode';
    var params = self.data.param;
    params.invite_key = app.globalData.init_invite_key;
    self.setData({
      param: params
    });
    var param=[];
    param = self.data.param;
    param.uid = wx.getStorageSync('ui') ? wx.getStorageSync('ui') : 1;
    param.invite_key=app.globalData.init_invite_key;
    app.showLoading('加载中...');
    app.ajaxRequest(action, 'POST', param, function (ret) {
      if (ret.status == 1) {
        self.setData({
          tw_share: 1,
          is_share: 0,
          template2: ret.data
        })
      } else {
        app.HCtoast(ret.msg);
      }
    });
  },
  // 保存到本地
  saveimg: function () {
    var self = this;
    wx.getImageInfo({
      src: self.data.img_url,
      success: function (sres) {
        wx.saveImageToPhotosAlbum({
          filePath: sres.path,
          success: function (fres) {
            if (fres.errMsg == 'saveImageToPhotosAlbum:ok') {
              app.HCtoast('保存成功', 1000);
            } else {
              app.HCtoast('保存失败,请重新保存', 1000);
            }
          }
        })
      }
    })
  },
  gotoIndex: function (ret) {
    app.HCswitchTab('../../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');
        }
      })
    }
  },
})