// pages/car/edit.js
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isKeyboard: false, //是否显示车牌输入键盘
    inputOnFocusIndex: '', //当前锁定的车号位置
    licensePlate: '', //车牌号
    defaultText: '请选择',

    inputPlates: { //默认显示车牌号
      index0: "",
      index1: "",
      index2: "",
      index3: "",
      index4: "",
      index5: "",
      index6: "",
      index7: ""
    },

    id: '',

    isShow: true,
    current_index: 0,

    blackSwitch:'2',
    whiteSwitch:'2',
    internal:2,

    originalInvoicePhoto: '', //base64码
    originalInvoicePhotoUrl: ''
  },
  //输入框焦点聚焦时隐藏车牌号输入框
  hideKeybord: function () {
    this.setData({
      isKeyboard: false,
      inputOnFocusIndex: ''
    })
  },

  //下拉选择
  bindPickerChange: function (e) { //下拉菜单
    let { pickername } = e.target.dataset
    let getIndex = pickername + 'Index'
    app.util.getPickerIndex(this, getIndex, e);
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (wx.getStorageSync('loginStatus')) {
      //获取详情
      var pages = getCurrentPages();
      var prevPage = pages[pages.length - 2];
      let getInfo = prevPage.data.resData[options.index]

      let getCarNumArr = getInfo.licensePlate ? getInfo.licensePlate.split('') : ''
      let inputPlates = {};
      for (let i = 0; i < getCarNumArr.length; i++) {
        inputPlates['index' + i] = getCarNumArr[i]
      }

      this.setData({
        id:options.id,
        info: getInfo,
        inputPlates: inputPlates,
        isNewEnergy: getCarNumArr.length > 7 ? true : false,
        licensePlate: getInfo.licensePlate,
      })

      this.getSelectData()

    } else {
      wx.switchTab({
        url: '/pages/center/index',
      })
    }
  },

  //获取订单下拉列表、车辆轴数下拉列表
  getSelectData:function(){
    //获取车辆轴数下拉列表
    app.request.GET({
      url: app.API.getCarzheList,
      params: {},
      page: this,
      successFun: true
    }).then(res => {
      this.setData({
        carzheArray:res.data.data,
        carzheIndex: app.util.getDicIndex(res.data.data, this.data.info.vehicleAxles, 'id'),
      })
    })
  },

  //查询详情
  getInfo: function (id) {
    //详情
    app.request.requestGetApi(app.API.api.carDetail, {
      'id': id
    }, this, function (res, _that) {
      let data = res.data.data;
      _that.setData({
        info: data,
        inputPlates: inputPlates,
        isNewEnergy: getCarNumArr.length > 7 ? true : false,
        licensePlate: data.licensePlate,
        projectIndex: app.util.getDicIndex(_that.data.projectArray, data.projectId, 'id'), //请假类型,获取对应下标
      })
    })
  },

  //开关
  onChange(e) {
    let { switchType } = e.currentTarget.dataset
    let number = 0
    if(e.detail=='1'){
      if(this.data.blackSwitch=='1'){
        number = number+1
      }
      if(this.data.whiteSwitch=='1'){
        number = number+1
      }
      if(this.data.internal=='1'){
        number = number+1
      }
      if(number<1){
        // 需要手动对 checked 状态进行更新
        this.setData({ 
          [switchType]: e.detail 
        });
      }else{
        app.util.checkForm('黑白名单及内部车辆最多只能开启一项');
      }
    }else{
      this.setData({ 
        [switchType]: e.detail 
      });
    }
    
    
  },

  //获取车牌号
  licensePlate: function (e) {
    this.setData({
      licensePlate: e.detail.carNum
    })
  },

  // 选择图片
  afterRead: function (e) {
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: res => {
        var base64 = 'data:image/jpeg;base64,' + wx.getFileSystemManager().readFileSync(res.tempFilePaths[0], "base64");
        this.setData({
          originalInvoicePhoto: base64,
          originalInvoicePhotoUrl: res.tempFilePaths[0]
        })
        console.log('上传时的base64:', this.data.originalInvoicePhoto)
      }
    })
  },

  //删除当前选择的图片
  clearImgFun: function () {
    this.setData({
      originalInvoicePhoto: '',
      originalInvoicePhotoUrl: ''
    })
  },

  //提交事件
  formSubmit: function ({detail:{value}}) {
    let reg = /^1[3-9]\d{9}$/;
    var xreg = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-HJ-NP-Z0-9]{4,5}[A-HJ-NP-Z0-9挂学警港澳]{1}$/;
    var creg = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-HJ-NP-Z0-9]{4}[A-HJ-NP-Z0-9挂学警港澳]{1}$/;
    var warn = ""; //弹框时提示的内容
    //formData.certificateNoImage = this.data.originalInvoicePhoto
    if (value.licensePlate == '') {
      warn = "车牌不能为空！";
    } else if (value.licensePlate.length < 7) {
      warn = "请选择完整车牌号！";
    } else if (value.licensePlate.length == 7 && !creg.test(value.licensePlate)) {
      warn = "车牌号格式错误！";
    } else if (value.licensePlate.length == 8 && !xreg.test(value.licensePlate)) {
      warn = "车牌号格式错误！";
    } else if (value.overId == '') {
      warn = "请选择车辆轴数！";
    }
    value.vehicleAxles = value.carzheId
    if (warn != '') {
      app.util.checkForm(warn);
    } else {
      app.request.POST({
        url: app.API.bizvehicleEdit,
        params: value,
        page: this,
        isLoadingTxt: '提交中...',
        isSubmitting: true,
        successFun: true
      }).then(res => {
        wx.showToast({
          title: '修改成功',
          icon: 'success',
          duration: 2000,
          mask:true,
          complete: function () {
            setTimeout(() => {
              wx.navigateBack()
            }, 1500) //延迟时间  
          }
        })
      })
    }
  }

})