// pages/details/details.js

const getReq = require('../../config.js').getReq;
const app = getApp();
import recordSource from '../../utils/recordSource';
var WxParse = require('../../wxParse/wxParse.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    imgUrls: [],
    datas: {},
    goodsIdMap: '',
    bundleList: '', // 套餐
    getOneSummary: [],
    indicatorDots: true,
    vertical: false,
    autoplay: true,
    interval: 2000,
    duration: 500,
    animation_flag: false,
    isExplain: false,
    sec_index: 0,
    goodsNumber: 1,
    cartOrBuy: '',
    getgift: '',
    options_goods_id: '',
    countTime: 50, /// 测试倒计时
    basicStar: './../image/basic_star.png',
    activeStar: '../../image/star.png',
    halfStar: '../../image/half_star.png',
    starSrcs: [],
    comments: [],
    current: 0,
    carouselImgs: [],
    currentPrice: '', // 商品当前价格,
    promotionDays: '',
    bundleIndex: -1,
    swiperHeight: '',
    show: false,
    firstLoad: true,
    fromSource: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      options_goods_id: options.goods_id
    })
    this.getDatas(options.goods_id)
    var that = this;
    getReq(app,{
      act: 'goods_common',
      op: 'detail',
      goods_id: options.goods_id
    }, function (res) {
      var str = res.split(/<[\/]?body>/gi)[1];
      WxParse.wxParse('article', 'html', str, that);
    });
  },
  
  getDatas(goods_id) {

    let fromSource = recordSource(app, `act=goods_common&op=index&goods_id=${goods_id}&client_type=mini`)
    wx.showLoading({
      title: '加载中',
    })
    var self = this
    getReq(app,{
      act: 'goods_common',
      op: 'index',
      goods_id,
      from: fromSource
    }, function (res) {
      wx.hideLoading()
      if (res.code == 200) {
        self.createStars(res.datas.common_info.comments_rate)
        if (res.datas.comments) {
          self.createComments(res.datas.comments)
        }

        let goodsIdMap = ''
        if (!self.data.goodsIdMap) {
          goodsIdMap = new Map()
          res.datas.summary.map(item => {
            goodsIdMap.set(item['goods_id'], item)
          });
        }
        let oneSummary = self.getOneSummary(res.datas.summary, goods_id)
        let bundleList = ''
        if (oneSummary['have_bundle']) {
          let bundlingMap = new Map()
          res.datas['bundling'].map(item => {
            bundlingMap.set(item['bl_id'], item)
          })
          let goodsSumaryMap = goodsIdMap ? goodsIdMap : self.data.goodsIdMap
          bundleList = self.createBundles(oneSummary['bundles'], bundlingMap, goodsSumaryMap)
        }
        let getgift = self.getgift(res.datas.summary, goods_id)
        let differencePrice = (oneSummary.goods_price - oneSummary.bonus_price).toFixed(2)
        oneSummary = Object.assign({}, { differencePrice }, oneSummary)
        let promotionDays = ''
        if (oneSummary['act_type'] == 2) {
          promotionDays = self.getPromotionDays(oneSummary['act_id'], res.datas.limitime)
        }
        self.setData({
          datas: res.datas,
          getOneSummary: oneSummary,
          imgUrls: res.datas.common_info.images,
          getgift,
          promotionDays,
          goodsIdMap,
          bundleList,
          firstLoad: false,
          fromSource: app.globalData.fromSource
        })
      }
      else {
        wx.showToast({
          icon: 'none',
          title: res.message,
          duration: 1500
        })
      }
    })
  },
  getOneSummary(sumarys, goods_id) {
    let getOneSummary 
     sumarys.find((item, index) => {
      if(item.goods_id == goods_id) {
        item['bonus_price'] = parseFloat(item['bonus_price'])
        item['goods_promotion_price'] = parseFloat(item['goods_promotion_price'])
        item['goods_price'] = parseFloat(item['goods_price'])
        getOneSummary = item
      return true
      }
    })
    return getOneSummary
  },
  secSku(e) {
    let goodsId = e.currentTarget.dataset.goodsid
    let sec_index = e.currentTarget.dataset.secindex
    if (this.data.sec_index == sec_index) {
      return
    }
    let getOneSummary = this.getOneSummary(this.data.datas.summary, goodsId)
    let getgift = this.getgift(this.data.datas.summary, goodsId)
    if (getOneSummary.goods_storage < 1) {
      wx.showToast({
        title: '客官！暂时没有库存！',
        icon: 'none',
        duration: 1500
      })
      return
    }
    this.setData({
      sec_index,
      getOneSummary,
      goodsNumber: 1,
      getgift
    })
  },
  createBundles(bundles, bundlingMap, goodsIdMap) {
    let bundlesList = []
    bundles.map(item => {
      if (bundlingMap.get(item)) {
        let bundlesSumary = []
        let bundling = bundlingMap.get(item)
        let goodsTotalPrice = 0
        bundling['goods'].map(good => {
          let resultGood = goodsIdMap.get(good['goods_id'])
          resultGood['bl_goods_price'] = good['bl_goods_price']
          goodsTotalPrice += parseFloat(resultGood['goods_price'])
          bundlesSumary.push(resultGood)
        })
        let reduce_price = goodsTotalPrice - bundling['bl_price']
        bundling['reduce_price'] = reduce_price
        bundlesList.push({
          bundling,
          bundlesSumary
        })
      }
    })
    return bundlesList
  },
  goodsNumHandle(e) {
    let type = e.currentTarget.dataset.type
    if (type == 'minus') {
      if (this.data.goodsNumber <= 1) {
        wx.showToast({
          title: '客官！不能再少了！',
          icon: 'none',
          duration: 1500
        })
        return
      }
      else {
        this.setData({
          goodsNumber: --this.data.goodsNumber
        })
      }
    }
    else {
      if (this.data.goodsNumber >= this.data.getOneSummary['goods_storage']) {
        wx.showToast({
          title: '客官！只有这么多了！',
          icon: 'none',
          duration: 1500
        })
        return
      }
      else {
        this.setData({
          goodsNumber: ++this.data.goodsNumber
        })
      }
    }
  },
  checkSubmit() {
    if (!app.globalData.userInfo) {
      app.navigateto('/pages/login/login')
      return;
    }
    let cartOrBuy = this.data.cartOrBuy
    this.setData({
      animation_flag: false
    })
    if (cartOrBuy == 'isCart') {
      wx.showLoading({
        title: '加载中',
      })
      getReq(app,{
        act: 'cart',
        op: 'addex',
        quantity: this.data.goodsNumber,
        goods_id: this.data.getOneSummary.goods_id
      }, function (res) {
        wx.hideLoading()
        if (res.code == 200) {
          wx.showToast({
            icon: 'none',
            title: '添加成功！',
            duration: 1500
          })
        }
        else {
          wx.showToast({
            icon: 'none',
            title: res.message,
            duration: 1500
          })
        }
      })
    }
    else if (cartOrBuy == 'isBuy') {
      if (this.data.getOneSummary.is_fcode) {
        if (!this.data.getOneSummary.has_fcode) {
          wx.showToast({
            title: '您没有该商品F码,请领取F码后再购买.',
            icon: 'none',
            duration: 1500
          })
          return
        }
      }


      if (this.data.getOneSummary.goods_storage < 1) {
        wx.showToast({
          title: '客官！暂时没有库存！',
          icon: 'none',
          duration: 1500
        })
        return
      }
      app.navigateto(`/pages/confirmOrder/confirmOrder?goods_id=${this.data.getOneSummary.goods_id}&iscart=0&num=${this.data.goodsNumber}`)
    }
    else {
      return
    }

  },
  animation_flag(e) {
    let cartOrBuy = e.currentTarget.dataset.cartorbuy || 'none'
    let flag = e.currentTarget.dataset.flag
    let animation_flag = flag == 'true' ? true : false
    this.setData({
      animation_flag,
      cartOrBuy,
    })
  },
  isExplain_flag(e) {
    let flag = e.currentTarget.dataset.flag
    let isExplain = flag == 'true' ? true : false
    this.setData({
      isExplain
    })
  },
  getgift(sumarys, goods_id) {
    let goods = this.getOneSummary(sumarys, goods_id)
    let giftSummary = ''
    if (goods.have_gift) {
      giftSummary = this.getGiftSummary(sumarys, goods.gifts)
    }
    return giftSummary
  },
  getGiftSummary(sumarys, gifts) {
    let arr = []
    gifts.map(item => {
      sumarys.filter(sum => {
        if (item.gift_goods_id == sum.goods_id) {
          arr.push({
            sum,
            gifts: item
          })
        }
      })
    })
    return arr
  },
  getPromotionDays(actId, limitime) {
    let limit = limitime.filter(item => {
      return item['xianshi_id'] == actId
    })
    let days = Math.floor((limit[0]['end_time'] * 1000 - new Date().getTime()) / (60 * 60 * 24 * 1000));
    return days;
  },
  createStars(rate) {
    let starSrcs = []
    for (let i = 0; i < 5; i++) {
      if (i < Math.floor(rate)) {
        starSrcs.push(this.data.activeStar)
        continue
      }
      if (i < Math.round(rate)) {
        starSrcs.push(this.data.halfStar)
        continue
      }
      starSrcs.push(this.data.basicStar)
    }
    this.setData({
      starSrcs
    })
  },
  createComments(basicComments) {
    let comments = []
    comments = basicComments.map(item => {
      let addtime = item.addtime || ''
      if (addtime) {
        let date = new Date(addtime * 1000);
        let year = date.getFullYear();
        let month = date.getMonth() + 1;
        let day = date.getDate();
        let transform_addtime = `${year}-${month}-${day}`
        item['transform_addtime'] = transform_addtime
      }
      return item
    })
    this.setData({
      comments
    })
  },
  allComments() {
    app.navigateto(`/pages/comments/comments?common_id=${this.data.datas.comment.common_id}`)
    return;
  },
  showCarousel(e) {
    let carouselImgs = e.currentTarget.dataset.images
    let current = e.currentTarget.dataset.current
    this.setData({
      show_carousel: true,
      carouselImgs,
      current
    })
  },
  hideCarousel() {
    this.setData({
      show_carousel: false
    })
  },
  // 套装切换展开样式
  toggleBundle(e) {
    let { index } = e.currentTarget.dataset
    if (index == this.data.bundleIndex) {
      index = -1
    }
    this.setData({
      bundleIndex: index
    })
  },
  bundleDetail(e) {
    let { id } = e.currentTarget.dataset
    if (id == this.data.options_goods_id) return;
    app.navigateto(`/pages/details/details?goods_id=${id}&title=商品详情`)
  },
  addBundleCart(e) {
    if (!app.globalData.userInfo) {
      app.navigateto('/pages/login/login')
      return;
    }
    let bl_id =  e.currentTarget.dataset.blid
    getReq(app,{
      act: 'cart',
      op: 'addex',
      quantity: 1,
      bl_id
    }, function (res) {
      if (res.code == 200) {
        wx.showToast({
          icon: 'none',
          title: '添加成功！',
          duration: 1500
        })
      }
      else {
        wx.showToast({
          icon: 'none',
          title: res.message,
          duration: 1500
        })
      }
    })
  },
  swiperImgLoad(e) {
    if (this.data.swiperHeight) return;
    let swiperHeight = e.detail.height / e.detail.width * 750
    this.setData({
      swiperHeight,
      show: true
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (app.globalData.backLogin && !this.data.firstLoad) {
      app.setFromSource(this.data.fromSource)
      this.getDatas(this.data.getOneSummary.goods_id);
    }
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    let goods_id = this.data.options_goods_id
    let goods_name = this.data.getOneSummary.goods_mobile_name
    let imageUrl = this.data.imgUrls[0];
    return {
      title: `${app.globalData.channel}为您推荐:${goods_name}`,
      path: `/pages/details/details?goods_id=${goods_id}`,
      imageUrl: imageUrl
    }
  }
})