var app = getApp();
var $ = require('../../../js/util.js');
Page({
  data: {
    param: {
      id: 0
    },
    id: 0,
    data: {}
  },
  onLoad: function (options) {//接收上个页面传的参数
    if(options.id){
      this.setData({
        param: {
          id: options.id
        },
        id: options.id
      });
    }
    if (options.invite_key) {
      app.globalData.invite_key = options.invite_key;
    } 
    var self = this;
    app.getUserInfo(function (ret) {
      //console.log(ret);
      if (ret) {
        self.getData();
      }
    });
    self.getData();
  },
  onReady: function () {

  },
  onShareAppMessage: function () {
    return {
      title: '优惠券',
      desc: '快来领取优惠券吧!',
      path: '/' + $.getCurrentPageUrl() + '?invite_key=' + app.globalData.init_invite_key + '&id=' + this.data.param.id
    }
  },
  //加载数据
  getData: function (callback) {
    var self = this;
    app.showLoading('加载中...');
    var action = 'c=Coupon&a=countop_count';
    app.ajaxRequest(action, 'GET', $.ObjectToStr(self.data.param), function (ret) {
      if (ret.status == 1) {
        self.setData({
          data: ret.data
        });
      } else {
        app.HCerror('提示', ret.msg); return;
      }
    });
  },
  //领取优惠券
  goToGet: function () {
    var self = this;
    app.showLoading('加载中...');
    var action = 'c=Coupon&a=get_coupon_wx';
    var param = new Object;
    param.id = self.data.id;
    app.ajaxRequest(action, 'POST', param, function (ret) {
      if (ret.status == 1) {
        //console.log(ret);
        app.HCtoast('领取成功');
        if (ret.data.cardId) {
          var cardlist = new Array;
          cardlist.push(ret.data);
          var id = ret.data.add_id;
          app.HCaddCard(cardlist, function (ret) {
             //console.log(ret);
            if (ret.errMsg == "addCard:ok") {
              var code = ret.cardList[0].code;
              self.save_coupon(id, code);
            }
          });
        }
      } else {
        app.HCerror('提示', ret.msg, false);
      }
    }, true);
  },
  // 积分兑换优惠券
  goToPoints:function(event){
    var self = this;
    app.HCerror('提示', '兑换此券需要'+event.currentTarget.dataset.money+'积分，您确定要兑换吗？', true, function (ret) {
      if (ret.confirm) {
        self.goToGet(event);
      }
    })
  },
  save_coupon: function (id, code) {
    var self = this;
    var action = 'c=Coupon&a=save_coupon';
    var param = new Object;
    param.id = id;
    param.code = code;
    app.ajaxRequest(action, 'POST', param, function (ret) {
      console.log(ret);
    },true);
  },
});