// pages/product/product.js
// 获取全局的应用实例
const app = getApp();

// 引入utils全局函数
var dou = require('../../utils/util.js');

Page({
  data: {
    comment_list: [],
    page: 1, // 初始页默认值为1
    nomore: false,
    
    // 购物车
    number: 1, // 初始化购买数量
    showShopPopup: false, // 是否显示弹出层
    animationData: {}, // 动画数据
    attribute_data: []
  },
  
  onShow: function () {
    var that = this;
    
    wx.request({
      url: app.mp_url + 'databox.php?rec=cart_number',
      data: {
        'user_id': wx.getStorageSync('user_id'),
        'shell': wx.getStorageSync('shell')
      },
      header: {
        'Connect-Key' : wx.getStorageSync('connect_key')
      },
      success: function(res) {
        if (res.data.cart_number > 0) {
          that.setData({
            cart_number: res.data.cart_number
          })
        }
      }
    })
  },
  
  onLoad: function(options) {
    var that = this
        
    wx.setNavigationBarTitle({
      title: app.title.product_detail
    })

    // 显示转发按钮
    dou.showShareMenu()
   
    wx.request({
      url: app.mp_url + 'databox.php?rec=common',
      header: {
        'Connect-Key' : wx.getStorageSync('connect_key')
      },
      success: function(res) {
        that.setData({
          lang: res.data.lang,
          site: res.data.site
        })
      },
    })
   
    wx.request({
      url: app.mp_url + 'product.php',
      data: {
        'id': options.id,
        'user_id': wx.getStorageSync('user_id'),
        'shell': wx.getStorageSync('shell')
      },
      header: {
        'Connect-Key' : wx.getStorageSync('connect_key')
      },
      success: function(res) {
        that.setData({
          product: res.data.product,
          product_price: res.data.product_price,
          product_point: res.data.product_point,
          comment_list: res.data.comment_list,
          defined: res.data.defined,
          open: res.data.open
        })
       
        // 设置转发标题缓存
        wx.setStorageSync('shareTitle', res.data.product.name)
      },
    })
    
    that.setData({
      item_id: options.id,
      mode: options.mode ? options.mode : 'money'
    })
    
    wx.setStorageSync('product_buy_mode', that.data.mode)
   
    that.attributeList(); // 加载规格属性
    that.commentList(); // 加载评论
  },
  
  // 规格属性
  attributeList: function() {
    var that = this;
    
    wx.request({
      url: app.mp_url + 'product.php?rec=attribute_list',
      data: {
        user_id: wx.getStorageSync('user_id'),
        shell: wx.getStorageSync('shell'),
        id: that.data.item_id,
        mode: that.data.mode,
        attribute_data: that.data.attribute_data
      },
      header: {
        'Connect-Key' : wx.getStorageSync('connect_key')
      },
      success: function(res) {
        that.setData({
          attribute_list: res.data.attribute_list,
          product_price: res.data.product_price,
          product_point: res.data.product_point
        })
      }
    })
  },

  // 获取数据
  commentList: function(concat = false, page = '') {
    var that = this;
    
    wx.request({
      url: app.mp_url + 'databox.php?rec=comment_list',
      data: {
        user_id: wx.getStorageSync('user_id'),
        shell: wx.getStorageSync('shell'),
        module: 'product',
        item_id: that.data.item_id,
        page: page ? page : that.data.page, // 从数据里获取当前页数
      },
      header: {
        'Connect-Key' : wx.getStorageSync('connect_key')
      },
      success: function(res) {
        if (concat) {
          var dataBox = that.data.comment_list; // 从data获取当前datalist数组
          var dataNew = res.data.comment_list; // 从此次请求返回的数据中获取新数组
          
          if (dataNew) {
            dataBox = dataBox.concat(dataNew); // 合并数组
          } else {
            that.setData({
              nomore: true
            })
          }
        } else {
          dataBox = res.data.comment_list;
        }
        
        that.setData({
          comment_list: dataBox,
          loadpage: false
        })
      }
    })
  },
 
  // 模拟radio  
  selectAttribute: function(e) {
    var that = this;
    var key = 'attribute_data_box[' + e.currentTarget.dataset.att_id + ']'
    
    that.setData({
      [key]: e.currentTarget.dataset.value
    });
   
    let attribute_array = that.data.attribute_data_box;
 
    let keyValuePairs = Object.keys(attribute_array).map((key) => {
      return [key, attribute_array[key]];
    });
    
    that.setData({
      attribute_data: Object.fromEntries(keyValuePairs)
    });
   
    that.attributeList();
  },
 
  addToCart: function (e) {
    var that = this

    // 未登录时重新载入当前页面
    dou.checkLoginState('action', '/pages/user/user')
    
    wx.request({
    url: app.mp_url + 'order.php?rec=insert',
    data: {
      user_id: wx.getStorageSync('user_id'),
      shell: wx.getStorageSync('shell'),
      post: JSON.stringify(e.detail.value),
      mode: that.data.mode
    },
    method:'POST',
    header: {
      'Connect-Key' : wx.getStorageSync('connect_key'),
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    success: function (res) {
      if (res.data.wrong) {
        dou.douMsg(res.data.wrong)
      } else {
        if (res.data.mode == 'point') {
          wx.navigateTo({
            url: '/pages/order/checkout'
          })
        } else {
          wx.switchTab({
            url: '/pages/order/order'
          })
        }
      }
    }
   })
  },
 
  onReachBottom: function () { // 触底开始下一页
    var that = this;
    
    if (!that.data.nomore) {
      var page = that.data.page + 1; // 获取当前页数并+1
    
      that.setData({
        page: page, // 更新当前页数
        loadpage: true,//加载动画的显示
      })

      setTimeout (
        function() { //注意function这里不能缺少
          that.commentList(true); // 重新调用请求获取下一页数据
        },1000
      )
    }
  },
 
  // 显示购物车
  showCartForm: function(e) {
    this.setData({
      showCartBg: true
    })
    
    // 显示遮罩层
    var animation = wx.createAnimation({
        duration: 400, //动画的持续时间 默认400ms 数值越大，动画越慢 数值越小，动画越快
        timingFunction: "ease", //动画的效果 默认值是linear
        delay: 0
    })
    this.animation = animation
    animation.translateY(0).step()
    this.setData({
      animationData: animation.export(), // export 方法每次调用后会清掉之前的动画操作。
    })
  },
 
  hideCartForm () {
    // 隐藏遮罩层
    var animation = wx.createAnimation({
      duration: 400,
      timingFunction: "ease",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
    })
    setTimeout(function () {
      this.setData({
        showCartBg: false
      })
      // console.log(this)
    }.bind(this), 200)
  },
 
  // 点击减号
  bindMinus: function() { 
    var number = this.data.number;
    if (number > 1) {
      number --;  
    }
    this.setData({
        number: number,
    });
  },
  
  // 点击加号
  bindPlus: function() {  
    var number = this.data.number;  
    number ++; // 不作过多考虑自增1  
    this.setData({  
        number: number,  
    });
  },
 
  // 输入框事件
  bindManual: function(e) {  
    var number = e.detail.value;  
    this.setData({  
        number: number  
    });  
  },

  // 设置转发标题
  onShareAppMessage: function () {
    return {
      title: wx.getStorageSync('shareTitle')
    }
  },
    
  tel: function(e) {
    wx.makePhoneCall({
      phoneNumber: e.currentTarget.dataset.tel, //此号码并非真实电话号码，仅用于测试
      success: function() {
        console.log("拨打电话成功！")
      },
      fail: function() {
        console.log("拨打电话失败！")
      }
    })
  },
 
  // 只能跳转到tabBar配置页面
  douSwitchTab: function(e) {
    var url = e.currentTarget.dataset.url;
    wx.switchTab({
      url: url
    })
  },
 
  // 非tabBar的页面，可以带参数
  douNavigateTo: function(e) {
    var url = e.currentTarget.dataset.url;
    wx.navigateTo({
      url: url
    })
  }


})