const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    code:'',
    modelList:[],
  },
  scanCode() {
    var that = this;
    wx.scanCode({ //扫描API
      scanType:['barCode','qrCode'],
      success(res) { //扫描成功
        console.log(res) //输出回调信息
        that.setData({
          code: res.result
        });
        wx.showToast({
          title: '扫码成功',
          duration: 1000
        })
      },
      fail:function(err){
        app.showToptip(that, 'error', '扫码失败');
      }
    })
  },
  setCode(e){
    this.setData({
      code:e.detail.value
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({id:options.type})
    this.getProductModel(options.type);
  },
  getProductModel(type){
    var that = this;
    app.requestP({
      url:'/productModel/ListByType',
      method:'post',
      contentType:' application/json',
      data:{
        type
      }
    }).then(res=>{
      that.setData({
        modelList:res.data.data
      })
    }).catch(err=>{
      app.showToptip(that,'error',err.data.msg)
    })
  },
  formSubmit(e){
    var value = e.detail.value;
    var code = this.data.code;
    const {name,companyName} = value;
    var that = this;
    var arr = [];
    delete value.code
    Object.keys(value).forEach(function (e,index) {
      if(value[e].length == 0){
        app.showToptip(that, "error",'信息不能为空！');
        arr = [];
        throw new Error('err');
      }else {
        if(index > 1){
          arr.push({'keyStr':e,'valueStr':value[e]})
          // arr.push("{keyStr:"+e+",valueStr:"+value[e]+"}")
        }
      }
    })
    if(arr){
      app.requestP({
        url:'/product/createProduct',
        method:'post',
        contentType:' application/json',
        data:{
          code,name,companyName,
          content:JSON.stringify(arr),
          typeId:that.data.id
        }
      }).then(res=>{
        app.showToptip(that,'success',res.data.msg);
        wx.navigateBack({
          delta: 1,
        },
        );
      }).catch(err=>{
        app.showToptip(that,'error',err.data.msg)
      })
    }
  },
})