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

  /**
   * 页面的初始数据
   */
  data: {
    id: 0,
    onlyid: 0,
    allgood: [],
    cover: false,
    isgoods: false,
    goodname: '',
    goodid: 0,
    goodonlyid: 0,
    goodtypename: '',
    goodtypeid: 0,
    goodtypeonlyid: 0,
    goodsCode: '',
    goodsBarcode: '',
    purchasePrice: 0,
    purchaseNumber: 0,
    payWayarray: [],
    payWayindex: 0,
    payWay: 1,
    suppliers: [],
    supplierid: 0,
    supplieronlyid: 0,
    suppliername: '请选择',
    prices1: 0,
    submitDate: '请选择',
    productionDate: '请选择',
    begoodTime: '请选择',
    images: [],
    imagessize: 0,
    imgBaseUrl: util.baseImgUrl,
    idx: 0,
    factory: '',
    explains: '',
    imgurl: util.imgurl,
    needpay: 0,
    realPayMoney: 0,
    sellPrice: 0,
    prices1: 0,
    prices2: 0,
    prices3: 0,
    prices4: 0,
    prices5: 0,
    isrealPayMoney: false,
    startYear: 1900,
    endYear: 2999
  },
  changeDateTime(e) {
    this.setData({
      dateTime: e.detail.value
    });
  },
  changeDateTimeColumn(e) {
    this.dateUpdate(e.detail.column, e.detail.value)
  },
  dateUpdate(column, value) {
    var arr = this.data.dateTime,
      dateArr = this.data.dateTimeArray;

    arr[column] = value;
    dateArr[2] = dateTimePicker.getMonthDay(dateArr[0][arr[0]], dateArr[1][arr[1]]);

    this.setData({
      dateTimeArray: dateArr,
      dateTime: arr
    });
  },
  changeDateTime1(e) {
    this.setData({
      dateTime1: e.detail.value
    });
  },
  changeDateTimeColumn1(e) {
    this.dateUpdate1(e.detail.column, e.detail.value)
  },
  dateUpdate1(column, value) {
    var arr = this.data.dateTime1,
      dateArr = this.data.dateTimeArray1;

    arr[column] = value;
    dateArr[2] = dateTimePicker.getMonthDay(dateArr[0][arr[0]], dateArr[1][arr[1]]);

    this.setData({
      dateTimeArray1: dateArr,
      dateTime1: arr
    });
  },
  changeDateTime2(e) {
    this.setData({
      dateTime2: e.detail.value
    });
  },
  changeDateTimeColumn2(e) {
    this.dateUpdate2(e.detail.column, e.detail.value)
  },
  dateUpdate2(column, value) {
    var arr = this.data.dateTime2,
      dateArr = this.data.dateTimeArray2;

    arr[column] = value;
    dateArr[2] = dateTimePicker.getMonthDay(dateArr[0][arr[0]], dateArr[1][arr[1]]);

    this.setData({
      dateTimeArray2: dateArr,
      dateTime2: arr
    });
  },
  getSet() {
    util.query('userSetting/wxapi/getMySetting', {}, function(res) {
      if (res.code === 10000) {
        that.setData({
          setting: res.data
        })
      } else {
        util.showToast('获取失败')
      }

    })

  },
  scan() {
    wx.scanCode({
      success(res) {
        console.log(res)
        if (res && res.errMsg === 'scanCode:ok') {
          that.setData({
            goodsBarcode: res.result
          })
        } else {
          util.showToast('未识别出正确的条码')
        }
      },
      fail(res) {
        console.log(res)
        util.showToast('未识别出正确的条码')
      }
    })
  },
  savegoodsBatch() {

    var data = {
      goods: {
        id: this.data.goodid,
        onlyID: this.data.goodonlyid
      },
      goodsCode: this.data.goodsCode,
      goodsBarcode: this.data.goodsBarcode,
      purchasePrice: this.data.purchasePrice,
      purchaseNumber: this.data.purchaseNumber,
      payWay: this.data.payWay,

      prices1: this.data.prices1,
      prices2: this.data.prices2,
      prices3: this.data.prices3,
      prices4: this.data.prices4,
      prices5: this.data.prices5,

      sellPrice: this.data.sellPrice,
      submitDate: this.data.dateTimeArray[0][this.data.dateTime[0]] + '-' + this.data.dateTimeArray[1][this.data.dateTime[1]] + '-' + this.data.dateTimeArray[2][this.data.dateTime[2]] + ' ' + this.data.dateTimeArray[3][this.data.dateTime[3]] + ':' + this.data.dateTimeArray[4][this.data.dateTime[4]] + ':' + this.data.dateTimeArray[5][this.data.dateTime[5]],
      productionDate: this.data.dateTimeArray1[0][this.data.dateTime1[0]] + '-' + this.data.dateTimeArray1[1][this.data.dateTime1[1]] + '-' + this.data.dateTimeArray1[2][this.data.dateTime1[2]] + ' ' + this.data.dateTimeArray1[3][this.data.dateTime1[3]] + ':' + this.data.dateTimeArray1[4][this.data.dateTime1[4]] + ':' + this.data.dateTimeArray1[5][this.data.dateTime1[5]],
      begoodTime: this.data.dateTimeArray2[0][this.data.dateTime2[0]] + '-' + this.data.dateTimeArray2[1][this.data.dateTime2[1]] + '-' + this.data.dateTimeArray2[2][this.data.dateTime2[2]] + ' ' + this.data.dateTimeArray2[3][this.data.dateTime2[3]] + ':' + this.data.dateTimeArray2[4][this.data.dateTime2[4]] + ':' + this.data.dateTimeArray2[5][this.data.dateTime2[5]],
      image: this.data.images.length > 0 ? this.data.images[0] : '',
      realPayMoney: this.data.realPayMoney,
      factory: this.data.factory,
      explains: this.data.explains,
      image: this.data.images.length > 0 ? this.data.images[0] : ''
    }
    if (this.data.supplierid && this.data.supplierid != 0) {
      data.supplier = {
        id: this.data.supplierid,
        onlyID: this.data.supplieronlyid
      }
    }


    var url = ''
    if (this.data.id) {
      url = 'goodsbatch/wxapi/update'
      data.id = this.data.id
      data.onlyID = this.data.onlyid
      data = Object.assign(this.data.olddata, data)
    } else {
      url = 'goodsbatch/wxapi/create'
    }
    util.query(url, data, function(res) {
      if (res.code === 10000) {
        util.showToast('保存成功')
        setTimeout(function() {
          wx.navigateBack({
            delta: 1
          })
        }, 2000)
      } else {
        util.showToast('保存失败')
      }
    }, 'POST')
  },
  save() {
    if (this.data.goodid) {
      this.savegoodsBatch()
    } else {
      this.saveGoods()
    }

  },

  saveGoods() {
    if (!this.data.goodname) {
      util.showToast('请输入商品名称')
      return
    }
    if (!this.data.goodtypeid && this.data.setting.goodsCategory === 1) {
      util.showToast('请选择商品分类')
      return
    }
    var data = {
      name: this.data.goodname
    }
    if (this.data.goodtypeid) {
      data.goodsCategory = {
        id: this.data.goodtypeid,
        onlyID: this.data.goodtypeonlyid
      }
    }

    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')
  },
  addImage(e) {
    var idx = e.target.dataset.idx
    console.log(idx)
    wx.chooseImage({
      count: idx == -1 ? (1 - that.data.images.length) : 1, // 默认9
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function(res) {
        console.log(res.tempFilePaths);
        wx.showLoading({
          title: '加载中',
        })

        for (var i in res.tempFilePaths) {
          wx.uploadFile({
            url: util.baseurl + 'file/uploadfile',
            filePath: res.tempFilePaths[i],
            name: 'file',
            header: {
              'token': wx.getStorageSync("token")
            },
            success: function(res) {
              wx.hideLoading()
              var d = JSON.parse(res.data);
              if (d.code == 10000) {
                var images = that.data.images;
                if (idx == -1) {
                  images.push(d.imageUrl)
                } else {
                  images[idx] = d.imageUrl
                }
                that.setData({
                  images: images,
                  isblank: false
                })
                that.setData({
                  imagessize: that.data.images.length
                })
              }

            }
          })
        }
      }
    })
  },
  tochoisetype(e) {
    wx.navigateTo({
      url: '/pages/stock/goodstype/goodstype',
    })
  },
  setsellPrice(e) {
    this.setData({
      sellPrice: util.PointNum(e.detail.value)
    })
  },
  setprices5(e) {
    this.setData({
      prices5: util.PointNum(e.detail.value)
    })
  },
  setprices4(e) {
    this.setData({
      prices4: util.PointNum(e.detail.value)
    })
  },
  setprices3(e) {
    this.setData({
      prices3: util.PointNum(e.detail.value)
    })
  },
  setprices2(e) {
    this.setData({
      prices2: util.PointNum(e.detail.value)
    })
  },
  setprices1(e) {
    this.setData({
      prices1: util.PointNum(e.detail.value)
    })
  },
  setfactory(e) {
    this.setData({
      factory: e.detail.value
    })
  },
  setexplains(e) {
    this.setData({
      explains: e.detail.value
    })
  },
  setbegoodTime(e) {
    this.setData({
      begoodTime: e.detail.value
    })
  },
  setproductionDate(e) {
    this.setData({
      productionDate: e.detail.value
    })
  },
  setsubmitDate(e) {
    this.setData({
      submitDate: e.detail.value
    })
  },
  bindsupplierChange(e) {
    this.setData({
      supplierindex: e.detail.value,
      supplierid: this.data.suppliers[e.detail.value].id,
      supplieronlyid: this.data.suppliers[e.detail.value].onlyID,
      suppliername: this.data.suppliers[e.detail.value].name
    })
  },
  getSupplierListData() {
    util.query("supplier/wxapi/list", {}, function(res) {
      if (res.code === 10000) {
        var da = []
        res.data.forEach(function(e) {
          da.push({
            id: e.supplier.id,
            name: e.supplier.name,
            onlyID: e.supplier.onlyID
          })
        })
        that.setData({
          suppliers: da
        })
      } else {
        that.setData({
          suppliers: []
        })
      }

    })
  },
  setrealPayMoney(e) {
    var price = util.PointNum(e.detail.value)
    this.setData({
      realPayMoney: (this.data.purchasePrice * this.data.purchaseNumber < price) ? parseFloat(this.data.purchasePrice * this.data.purchaseNumber).toFixed(2) : price,
      needpay: (this.data.purchasePrice * this.data.purchaseNumber < e.detail.value) ? 0 : parseFloat(this.data.purchasePrice * this.data.purchaseNumber - e.detail.value).toFixed(2),
      isrealPayMoney: true
    })
  },
  payWayChange(e) {
    this.setData({
      payWayindex: e.detail.value,
      payWay: this.data.payWayarray[e.detail.value].key
    })
  },
  setpurchaseNumber(e) {
    var price = util.PointNum(e.detail.value)
    this.setData({
      purchaseNumber: price,
      total: parseFloat(price * this.data.purchasePrice).toFixed(2)
    })
    if (!this.data.isrealPayMoney) {
      this.setData({
        realPayMoney: parseFloat(price * this.data.purchasePrice).toFixed(2),
      })
    }
    this.setData({
      needpay: parseFloat(this.data.purchasePrice * price - this.data.realPayMoney).toFixed(2)
    })
  },
  setpurchasePrice(e) {
    var price = util.PointNum(e.detail.value)
    this.setData({
      purchasePrice: price,
      total: parseFloat(price * this.data.purchaseNumber).toFixed(2)
    })
    if (!this.data.isrealPayMoney) {
      this.setData({
        realPayMoney: parseFloat(price * this.data.purchaseNumber).toFixed(2),
      })
    }
    this.setData({
      needpay: parseFloat(this.data.purchaseNumber * price - this.data.realPayMoney).toFixed(2)
    })
  },
  setgoodsBarcode(e) {
    this.setData({
      goodsBarcode: e.detail.value
    })
  },
  setgoodsCode(e) {
    this.setData({
      goodsCode: e.detail.value
    })
  },
  selectgood(e) {
    this.setData({
      goodid: e.currentTarget.dataset.id,
      goodonlyid: e.currentTarget.dataset.onlyid,
      goodname: e.currentTarget.dataset.name,
      isgoods: false,
      cover: false
    })
    var ag = this.data.allgood
    for (var i in ag) {
      if (ag[i].id === e.currentTarget.dataset.id && ag[i].type) {
        this.setData({
          goodtypename: ag[i].type.name,
          goodtypeid: ag[i].type.id,
          goodtypeonlyid: ag[i].type.onlyid
        })
      }
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    that = this
    util.checklogin(
      function() {
        that.getSet()
        that.getAllGood()
        that.getSupplierListData()
        util.getPayWay(function(e) {
          that.setData({
            payWayarray: e
          })
        })
      })

    var obj = dateTimePicker.dateTimePicker(this.data.startYear, this.data.endYear);
    var obj1 = dateTimePicker.dateTimePicker(this.data.startYear, this.data.endYear);
    var obj2 = dateTimePicker.dateTimePicker(this.data.startYear, this.data.endYear);
    this.setData({
      dateTime: obj.dateTime,
      dateTimeArray: obj.dateTimeArray,
      dateTime1: obj1.dateTime,
      dateTimeArray1: obj1.dateTimeArray,
      dateTime2: obj2.dateTime,
      dateTimeArray2: obj2.dateTimeArray,
    })
    if (options.editeid) {
      this.setData({
        editeid: options.editeid
      })
      this.getDetail(options.editeid)
    } else if (options.copyid) {

      this.getDetail(options.copyid, 1)

    } else {

    }
    var ui = wx.getStorageSync('userinfo')
    if (ui) {
      this.setData({
        createUser: ui.wechatName
      })
    }
  },
  del() {
    wx.showModal({
      title: '确认',
      content: '是否确定删除该批次',
      success(res) {
        if (res.confirm) {
          var data =
            util.query("goodsbatch/wxapi/deletebatch", {
              ids: [{
                id: that.data.editeid
              }]
            }, function(res) {
              if (res.code == 10000) {
                util.showToast('删除成功')
                setTimeout(function() {
                  wx.navigateBack({
                    delta: 1
                  })
                }, 2000)
              } else {
                util.showToast(res.message)
              }
            }, "POST")
        } else if (res.cancel) {

        }
      }
    })
  },
  getDetail(id, iscopy) {
    util.query('goodsbatch/wxapi/findbyid', {
      id: id
    }, function(res) {
      if (res.code === 10000) {
        var da = res.data
        that.setData({
          goodname: da.goods.name,
          goodid: da.goods.id,
          goodonlyid: da.goods.onlyID,
          goodtypename: da.goods.goodsCategory ? da.goods.goodsCategory.name : '',
          goodtypeid: da.goods.goodsCategory ? da.goods.goodsCategory.id : 0,
          goodtypeonlyid: da.goods.goodsCategory ? da.goods.goodsCategory.onlyID : 0,
          goodsCode: da.goodsCode,
          goodsBarcode: da.goodsBarcode,
          purchasePrice: da.purchasePrice,
          purchaseNumber: da.purchaseNumber,
          payWay: da.payWay,
          supplierid: da.supplier ? da.supplier.id : 0,
          supplieronlyid: da.supplier ? da.supplier.onlyID : 0,
          suppliername: da.supplier ? da.supplier.name : '请选择',
          prices1: da.prices1,
          submitDate: da.submitDate ? da.submitDate : '请选择',
          productionDate: da.productionDate ? da.productionDate : '请选择',
          begoodTime: da.begoodTime ? da.begoodTime : '请选择',
          images: da.image ? [da.image] : [],
          imagessize: da.image ? 1 : 0,
          factory: da.factory,
          explains: da.explains,
          needpay: parseFloat(da.purchasePrice * da.purchaseNumber - da.realPayMoney).toFixed(2), //da.needpay ? da.needpay : 0,
          realPayMoney: da.realPayMoney ? da.realPayMoney : 0,
          sellPrice: da.sellPrice,
          prices1: da.prices1,
          prices2: da.prices2,
          prices3: da.prices3,
          prices4: da.prices4,
          prices5: da.prices5,
          olddata: da,
          total: parseFloat(da.purchasePrice * da.purchaseNumber).toFixed(2),
         // createUser: da.userName
        })
        if (res.data.submitDate) {
          var date = res.data.submitDate.split(' ')[0].split('-')
          var time = res.data.submitDate.split(' ')[1].split(':')
          that.dateUpdate(0, parseInt(date[0]) - that.data.startYear)
          that.dateUpdate(1, parseInt(date[1]) - 1)
          that.dateUpdate(2, parseInt(date[2]) - 1)
          that.dateUpdate(3, parseInt(time[0]))
          that.dateUpdate(4, parseInt(time[1]))
          that.dateUpdate(5, parseInt(time[2]))
        }


        if (res.data.productionDate) {
          date = res.data.productionDate.split(' ')[0].split('-')
          time = res.data.productionDate.split(' ')[1].split(':')
          that.dateUpdate1(0, parseInt(date[0]) - that.data.startYear)
          that.dateUpdate1(1, parseInt(date[1]) - 1)
          that.dateUpdate1(2, parseInt(date[2]) - 1)
          that.dateUpdate1(3, parseInt(time[0]))
          that.dateUpdate1(4, parseInt(time[1]))
          that.dateUpdate1(5, parseInt(time[2]))
        }
        if (res.data.begoodTime) {
          date = res.data.begoodTime.split(' ')[0].split('-')
          time = res.data.begoodTime.split(' ')[1].split(':')
          that.dateUpdate2(0, parseInt(date[0]) - that.data.startYear)
          that.dateUpdate2(1, parseInt(date[1]) - 1)
          that.dateUpdate2(2, parseInt(date[2]) - 1)
          that.dateUpdate2(3, parseInt(time[0]))
          that.dateUpdate2(4, parseInt(time[1]))
          that.dateUpdate2(5, parseInt(time[2]))
        }



        if (!iscopy) {
          that.setData({
            id: da.id,
            onlyid: da.onlyID
          })
        }

      } else {
        util.showToast('未发现该批次')
      }
    })
  },
  setname(e) {
    this.setData({
      goodname: e.detail.value
    })
    this.setData({
      goodid: 0
    })
    if (e.detail.value) {
      this.findname(e.detail.value)
    } else {
      this.setData({
        isgoods: false
      })
    }

  },
  findname(name) {
    var da = this.data.allgood
    var j = 0
    for (var i in da) {
      da[i].s = false
      if (da[i].name && da[i].name.indexOf(name) > -1) {
        da[i].s = true
        j++
      }
    }
    this.setData({
      allgood: da
    })
    if (j > 0) {
      this.showgoods()
    } else {
      this.hidecover()
    }
  },
  showgoods() {
    this.showcover()
    this.setData({
      isgoods: true,
    })
  },
  showcover() {
    this.setData({
      cover: true
    })
  },
  hidecover() {
    this.setData({
      cover: false,
      isgoods: false,
    })
  },
  getAllGood() {
    util.query('goods/wxapi/list', {}, function(res) {
      if (res.code === 10000) {
        var da = res.data
        var allgood = []
        for (var i in da) {
          var d = {
            id: da[i].id,
            name: da[i].name,
            s: false,
            onlyID: da[i].onlyID
          }
          if (da[i].goodsCategory) {
            d.type = {
              id: da[i].goodsCategory.id,
              name: da[i].goodsCategory.name,
              onlyid: da[i].goodsCategory.onlyID
            }
          }
          allgood.push(d)
        }
        that.setData({
          allgood: allgood
        })
      } else {
        util.showToast('查询商品失败')
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

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

  },

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

  },

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

  },

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

  }
})