const {
  checkMaterialCode,usedMaterial
} = require('../../api/api')
import Dialog from '@vant/weapp/dialog/dialog';
Page({
  data:{
    codeArr: [],
    maxNum: 0,
    isSubmit: true, //是否可提交,扫码失败弹窗关闭前不会重复请求接口
  },
  onLoad(e) {
    // console.log(12121216666, e)
    this.setData({
      maxNum: e.num,
      entryId: e.entryId,
      warehouseId: e.warehouseId,
      spec: e.spec,
      materialType: e.materialType,
      zb: e.zb,
      materialModel: e.model,
    })
    this.ctx = wx.createCameraContext()
  },
  //数组去重
  uniqueArr(arr) {
    if (!Array.isArray(arr)) {
        console.log('type error!')
        return
    }
    var array = [];
    for (var i = 0; i < arr.length; i++) {
        if (array .indexOf(arr[i]) === -1) {
            array .push(arr[i])
        }
    }
    return array;
  },
  error(e) {
    wx.showToast({
      title: '你已设置不允许使用摄像头',
      icon: 'error'
    })
    console.log('用户不允许使用摄像头时触发',e.detail)
  },
  //扫码
  scanFun2(e){
    let that = this;
    let codeArr = this.data.codeArr
    if(this.data.maxNum<=codeArr.length){
      wx.showToast({
        title: '条码数量不能超过'+ this.data.maxNum,
        icon: 'error'
      })
      return
    } 
    if(e.detail.result){
      let result = e.detail.result.split(',');
      if(result.length>1){
        result = result[0]
      }else{
        result = e.detail.result
      }
      if(!this.data.isSubmit){
        return
      }
      usedMaterial({
        userId: wx.getStorageSync('userId'),
        entryId: that.data.entryId,
        barcode: result.trim(),
        warehouseId: that.data.warehouseId,
        flag: 1,
        spec: that.data.spec,
        materialType: that.data.materialType,
        materialModel: that.data.materialModel,
      }).then((res) => {
        wx.hideLoading()
        that.setData({
          isSubmit: false
        })
        if (res.code == 200) {
          // if(res.data){
            // let newResult = res.data
            let newResult = result.trim()
            // newResult.forEach(item=>{
            //   codeArr.push(item)
            // })
            codeArr.push(newResult)
            that.setData({
              codeArr: that.uniqueArr(codeArr),
              isSubmit: true
            })
          // }
          // wx.showToast({
          //   title: '扫码成功',
          //   icon: 'none'
          // })
          // that.getUsedMaterialInfo()
        } else {        
          wx.showModal({
            title: '',
            content: res.msg || res.errMsg,
            showCancel: false,
            complete: (res) => {
              that.setData({
                isSubmit: true
              })
            }
          })
          // wx.showToast({
          //   title: res.msg || res.errMsg,
          //   icon: 'none'
          // })
        }
      })
      // checkMaterialCode({
      //   userId: wx.getStorageSync('userId'),
      //   entryId: that.data.entryId,
      //   barcode: result,
      //   warehouseId: that.data.warehouseId,
      //   flag: 1,
      //   spec: that.data.spec,
      //   materialType: that.data.materialType,
      //   zb: that.data.zb
      // }).then((res) => {
      //   that.setData({
      //     isSubmit: false
      //   })
      //   if (res.code == 200) {
      //     if(res.data){
      //       let newResult = res.data
      //       newResult.forEach(item=>{
      //         codeArr.push(item)
      //       })
      //       // codeArr.push(newResult)
      //       that.setData({
      //         codeArr: that.uniqueArr(codeArr),
      //         isSubmit: true
      //       })
      //     }
      //   } else {
      //     const beforeClose = (action) =>
      //       new Promise((resolve) => {
      //         setTimeout(() => {
      //           if (action === 'confirm') {
      //             that.setData({
      //               isSubmit: true
      //             })
      //             resolve(true);
      //           }
      //         }, 300);
      //       });
      //     Dialog.alert({
      //       message: res.msg || res.errMsg,
      //       beforeClose
      //     });
      //   }
      // })
    }    
  },
  //扫码
  scanFun(e){
    let that = this;
    let codeArr = this.data.codeArr
    if(this.data.maxNum<=codeArr.length){
      wx.showToast({
        title: '条码数量不能超过'+ this.data.maxNum,
        icon: 'error'
      })
      return
    } 
    if(e.detail.result){
      let result = e.detail.result.split(',');
      if(result.length>1){
        result = result[0]
      }else{
        result = e.detail.result
      }
      if(!this.data.isSubmit){
        return
      }
      checkMaterialCode({
        userId: wx.getStorageSync('userId'),
        entryId: that.data.entryId,
        barcode: result.trim(),
        warehouseId: that.data.warehouseId,
        flag: 1,
        spec: that.data.spec,
        materialType: that.data.materialType,
        materialModel: that.data.materialModel
        // zb: that.data.zb
      }).then((res) => {
        that.setData({
          isSubmit: false
        })
        if (res.code == 200) {
          if(res.data){
            let newResult = res.data
            // newResult.forEach(item=>{
            //   codeArr.push(item)
            // })
            codeArr.push(newResult)
            that.setData({
              codeArr: that.uniqueArr(codeArr),
              isSubmit: true
            })
          }
        } else {
          const beforeClose = (action) =>
            new Promise((resolve) => {
              setTimeout(() => {
                if (action === 'confirm') {
                  that.setData({
                    isSubmit: true
                  })
                  resolve(true);
                }
              }, 300);
            });
          Dialog.alert({
            message: res.msg || res.errMsg,
            beforeClose
          });
        }
      })
    }    
  },
  //删除
  delCode(e){
    let index = e.currentTarget.dataset.index
    let codeArr = this.data.codeArr
    codeArr.splice(index,1)
    this.setData({
      codeArr
    })
  },
  //提交
  submit(e){
    let codeArr = this.data.codeArr   
    if(this.data.maxNum<codeArr.length){
      wx.showToast({
        title: '数量不能超过'+ this.data.maxNum,
        icon: 'error'
      })
      return
    } 
    var pages = getCurrentPages(); // 获取页面栈
    var prevPage = pages[pages.length - 2]; // 上一个页面
    prevPage.setData({
      batchCode: codeArr.join(','),// 要设置的值
    })
    setTimeout(()=>{
      prevPage.getBatchCode()
    },300) //加延时是为了上一级页面的弹窗显示
    wx.navigateBack({ delta: 1})
  },
  //返回
  goBack(){
    // var pages = getCurrentPages(); // 获取页面栈
    // var prevPage = pages[pages.length - 2]; // 上一个页面
    // // prevPage.setData({
    // //   batchCode: codeArr.join(','),// 要设置的值
    // // })
    // setTimeout(()=>{
    //   prevPage.getWarehouseList()
    // },300) //加延时是为了上一级页面的弹窗显示
    wx.navigateBack({ delta: 1})
  }
})