// pages/stock/stock/stock.js
let util = require('../../../utils/util.js');
var that
Page({

  /**
   * 页面的初始数据
   */
  data: {
    baseImgUrl: util.baseImgUrl,
    imageurl: util.imgurl,
    data: [],
    isfirst: true,
    isadd: false,
    goodid: 0,
    goodonlyid: 0,
    adduser: '',
    name: '',
    code: '',
    num: 0,
    price: 0,
    stocktype: [{
      key: -2,
      name: '全部库存'
    }, {
      key: 1,
      name: '有库存'
    }, {
      key: 0,
      name: '无库存'
    }, {
      key: -1,
      name: '临缺商品'
    }],
    stocktypeindex: 0,
    uss: [],
    ussindex: 0,
    totalMoney: 0,
    stockAmount: 0,
    multiIndex: [0, 0],
    typename: '全部分类'
  },
  ussChane(e) {
    this.setData({
      ussindex: e.detail.value
    })
    this.getData()
  },
  getalltype() {
    util.query('goodscategory/wxapi/listall', {}, function(res) {
      if (res.code === 10000) {
        var fda = []

        res.data.forEach(function(e) {
          if (e.fatherID === '0') {
            e.child = []
            fda.push(e)
          }
        })
        res.data.forEach(function(e) {
          if (e.fatherID !== '0') {
            fda.forEach(function(fe) {
              if (fe.id + '' === e.fatherID) {
                fe.child.push(e)
              }
            })
          }
        })
        fda.unshift({
          id: -1,
          name: '全部分类',
          child: [{
            id: -2,
            name: '全部分类'
          }]
        })

        that.setData({
          types: fda,
          showda: that.freshdata(0, fda)
        })

      }
    })
  },
  freshdata(i, da) {
    var showda = [
      [],
      []
    ]

    da.forEach(function(e) {
      showda[0].push(e.name)
    })
    if (da.length > 0) {
      da[i].child.forEach(function(fe) {
        showda[1].push(fe.name)
      })
    }
    return showda
  },

  bindMultiPickerChange(e) {
    //console.log('aaa')
    var multiIndex = e.detail.value
    //  multiIndex[1] = e.detail.value
    that.setData({
      multiIndex: multiIndex,
      typename: this.data.showda[1][this.data.multiIndex[1]]
    })
    this.getData()
  },
  bindMultiPickerColumnChange(e) {
    //console.log('bbb')
    if (e.detail.column === 0) {
      that.setData({
        showda: that.freshdata(e.detail.value, this.data.types),
        multiIndex: [e.detail.value, 0]
      })
    }
    if (e.detail.column === 1) {
      var multiIndex = this.data.multiIndex
      multiIndex[1] = e.detail.value
      that.setData({
        multiIndex: multiIndex
      })
    }

  },
  getDefaultBook() {
    util.query('accountbook/wxapi/getdefault', {}, function(res) {
      if (res.code === 10000) {
        res.data.userInfos.unshift({
          key: 0,
          wechatName: '全部进货人'
        })
        that.setData({
          uss: res.data.userInfos
        })
      }
    })
  },
  stockChange(e) {
    this.setData({
      stocktypeindex: e.detail.value
    })
    this.getData()
  },
  save() {
    if (!this.data.name) {
      util.showToast('请输入名称')
      return
    }
    if (this.data.goodid === 0) {
      this.saveGoods()
    } else {
      this.savegoodsBatch()
    }
  },
  savegoodsBatch() {

    var data = {
      goods: {
        id: this.data.goodid,
        onlyID: this.data.goodonlyid
      },

      goodsBarcode: this.data.code,
      purchasePrice: this.data.price,
      purchaseNumber: this.data.num
    }

    util.query('goodsbatch/wxapi/create', data, function(res) {
      if (res.code === 10000) {
        util.showToast('保存成功')
        setTimeout(function() {
          that.hideAdd()
          that.getData()
        }, 2000)
      } else {
        util.showToast('保存失败')
      }
    }, 'POST')
  },
  saveGoods() {
    var data = {
      name: this.data.name
    }
    util.query('goods/wxapi/create', data, function(res) {
      if (res.code === 10000) {
        that.setData({
          goodid: res.goodsId,
          goodonlyid: res.goodsOnlyId
        })
        that.save()
      } else {
        util.showToast('保存失败')
      }
    }, 'POST')
  },
  setname(e) {
    this.setData({
      name: e.detail.value
    })
  },
  setprice(e) {
    this.setData({
      price: util.PointNum(e.detail.value)
    })
  },
  setnum(e) {
    this.setData({
      num: util.PointNum(e.detail.value)
    })
  },
  hideAdd() {
    that.setData({
      isadd: false
    })
  },
  querycode(code) {
    util.query('goodsbatch/wxapi/list', {
      goodsBarcode: code
    }, function(res) {
      if (res.code === 10000 && res.data && res.data.length > 0) {
        res.data.forEach(function(e) {
          if (e.goods) {
            that.setData({
              goodid: e.goods.id,
              goodonlyid: e.goods.onlyID,
              name: e.goods.name
            })

          }
        })

      }
      that.setData({
        isadd: true,
        code: code
      })
    })
  },
  scancode() {
    that.setData({
      goodid: 0,
      goodonlyid: 0,
      name: ''
    })
    wx.scanCode({
      success(res) {
        console.log(res)
        if (res && res.errMsg === 'scanCode:ok') {
          that.querycode(res.result)
        } else {
          util.showToast('未识别出正确的条码')
        }
      },
      fail(res) {
        console.log(res)
        util.showToast('未识别出正确的条码')
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    that = this
    util.checklogin(
      function() {
        var ui = wx.getStorageSync('userinfo')
        that.setData({
          adduser: ui.wechatName
        })
        that.getData()
        that.getDefaultBook()
        that.getalltype()
      }
    )
    var ui = wx.getStorageSync('userinfo')
    if (ui) {
      this.setData({
        uid: ui.uid
      })
    }
  },
  scanlogo(e) {
    wx.scanCode({
      success(res) {
        console.log(res)
        if (res && res.errMsg === 'scanCode:ok') {
          that.setData({
            names: res.result
          })
          that.search()
        } else {
          util.showToast('未识别出正确的条码')
        }
      },
      fail(res) {
        console.log(res)
        util.showToast('未识别出正确的条码')
      }
    })
  },
  setnames(e) {
    this.setData({
      names: e.detail.value
    })
  },

  search(e) {
    this.getData()
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },
  toaddstock() {
    wx.navigateTo({
      url: '/pages/stock/addstock/addstock',
    })
  },
  down(e) {
    var da = this.data.data
    da[e.currentTarget.dataset.index].sel = true
    this.setData({
      data: da
    })
  },
  up(e) {
    var da = this.data.data
    da[e.currentTarget.dataset.index].sel = false
    this.setData({
      data: da
    })
  },
  getData() {
    var param = {}
    if (this.data.stocktypeindex != 0) {
      param.stockStatus = this.data.stocktype[this.data.stocktypeindex].key
    }
    if (this.data.ussindex != 0) {
      param.uid = this.data.uss[this.data.ussindex].uid
    }
    if (this.data.multiIndex[0] != 0) {
      param.goodsCategoryId = this.data.types[this.data.multiIndex[0]].child[this.data.multiIndex[1]].id
    }
    if (this.data.names) {
      param.name = this.data.names
    }
    util.query('goodsbatch/wxapi/listbygroup', param, function(res) {
      if (res.code === 10000) {
        var da = []
        res.data.forEach(function(e) {
          if (e.goods && e.goodsBatchList && e.goodsBatchList.length > 0) {
            var all = 0,
              allcb = 0
            e.goodsBatchList.forEach(function(r) {
              r.goodsBatch.time = r.goodsBatch.submitDate ? (r.goodsBatch.submitDate.split(' ')[0]) : ''
              r.goodsBatch.allcb = (r.goodsBatch.purchasePrice ? r.goodsBatch.purchasePrice : 0) * (r.stockAmount ? r.stockAmount : 0)
              all += (r.goodsBatch.purchasePrice ? r.goodsBatch.purchasePrice : 0)
              allcb += r.goodsBatch.allcb
            })
            da.push({
              goods: e.goods,
              goodsStockAmount: e.goodsStockAmount,
              perprice: (all / e.goodsBatchList.length).toFixed(2),
              allcb: allcb.toFixed(2),
              goodsBatchList: e.goodsBatchList,
              type: e.goodsBatchList.length > 1 ? 2 : 1,
              sel: false,
              time: e.goodsBatchList[0].goodsBatch.submitDate ? (e.goodsBatchList[0].goodsBatch.submitDate.split(' ')[0]) : ''
            })
          }
        })
        //  da = da.sort(function(a, b) {
        //  return b.goodsBatchList[0].goodsBatch.id - a.goodsBatchList[0].goodsBatch.id
        //  })
        that.setData({
          data: da,
          stockAmount: res.stockAmount.toFixed(2),
          totalMoney: res.totalMoney.toFixed(2)
        })
      } else {
        that.setData({
          data: [],
          stockAmount: 0,
          totalMoney: 0
        })
      }
    })
  },
  tocopy(e) {
    wx.navigateTo({
      url: '/pages/stock/addstock/addstock?copyid=' + e.currentTarget.dataset.id,
    })
  },
  toedite(e) {
    wx.navigateTo({
      url: '/pages/stock/addstock/addstock?editeid=' + e.currentTarget.dataset.id,
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    if (!this.data.isfirst) {
      this.getData()
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {
    this.setData({
      isfirst: false
    })
  },

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

  },

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

  },

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

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})