<!--pages/AISearch/AISearch.wxml-->
<view class="ai_content">
  <view class="img_box" bindtap="chooseImg">
    <view class="upload_img" wx:if="{{tempFiles}}"><image src="{{tempFiles}}"></image></view>
    <view class="upload_img_icon" wx:if="{{!tempFiles}}"><image src="../../img/img_add.png"></image></view>
  </view>
  <view class="detail_box">
    <view class="title"><text>AI识别</text></view>
    <!-- <view class="number">

        <input type="text" placeholder="请输入车牌" value="{{carNumber}}" bindinput="changeNumber" />

    </view>    -->

    <view class="code_box">
      <view class="input_box" wx:for="{{carNumerArr}}" wx:key="index">
        <input 
        type="text" 
        value="{{item}}"
        data-index="{{index}}" 
        bindinput="_handleInput"
        focus="{{item.focus}}" 
        value="{{item.value}}" 
         />
      </view>
    </view>
   



    <view class="title"><text>车辆归属</text></view>
    <scroll-view scroll-y="true" class="car_list">
      <view class="car_box" wx:if="{{carInfoList.length > 0}}" wx:for="{{carInfoList}}" wx:key="index">
        <view class="car_item" bindtap="jumpToCarDetail" data-carid="{{item.carId}}" data-carnumber="{{item.carNumber}}">
          <view class="car_number"><text>{{item.carNumber}}</text></view>
          <view class="car_info"><text>{{item.factoryName}} {{item.seriesName}} {{item.modelName}} {{item.cylinder}}缸</text></view>
        </view>
      </view>
      <view class="no_list"  wx:if="{{carInfoList.length <= 0 && showBtn}}" >
        <view class="info"><text>系统中未查询到该车牌号码</text></view>
        <view class="btn_box" bindtap="addCar">添加车辆</view>
      </view>
    </scroll-view>
  </view>
</view>

wxss:

/* pages/AISearch/AISearch.wxss */

.ai_content {
  background: #F5F7FB;
  height: 100vh;
}
.img_box {
  height: 146px;
  /* box-sizing: border-box; */
  padding-top: 16px;
  /* padding-left: 50px; */
}
.img_box .upload_img {
  width: 160px;
  height: 120px;
  box-sizing: border-box;
  margin-left: calc((100vw - 160px) / 2);
  border-radius: 8px;
  overflow: hidden;
}
.img_box .upload_img image {
  width: 100%;  
  height: 100%;
}

.img_box .upload_img_icon {
  width: 160px;
  height: 120px;
  box-sizing: border-box;
  margin-left: calc((100vw - 160px) / 2);
  background: #FFFFFF;
  box-shadow: 4px 4px 4px 4px rgba(230, 230, 230, 0.25);
  border-radius: 8px;
  overflow: hidden;
  position: relative;
}
.img_box .upload_img_icon image {
  width: 24px;  
  height: 24px;
  position: absolute;
  top: calc(50% - 12px);
  left: calc(50% - 12px);
}




/* 输入框 */
.showKeyboard {
    display: flex;
    flex-direction: row;
}
.code_box {
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: white;
}







.detail_box {
  height: calc(100vh - 160px - 12px);
  background: #fff;
  border-radius: 8px 8px 0 0;
  /* width: calc(100vw - 32px); */
  /* margin: 0 auto; */
  /* padding: 16px; */
}
.detail_box .title {
  font-size: 16px;
  color: #0D0E12;
  width: calc(100vw - 32px);
  padding-left: 16px;
  padding-top: 16px;
}
.detail_box .number {
  display: flex;
  margin-top: 12px;
  width: calc(100vw - 32px);
  padding-left: 16px;
}
.detail_box .number .data {
  width: 12%;
  height: 42px;
  line-height: 42px;
  text-align: center;
  background: #F6F6F9;
  border-radius: 4px;
  /* padding: 10px; */
  margin-right: 6px;
}

.detail_box .number input {
    width: 100%;
    height: 44px;
    background: #F6F6F9;
    border-radius: 4px;
    font-size: 16px;
    text-align: center;
    letter-spacing:6px;
}





.detail_box .car_list {
  margin-top: 12px;
  height: calc(100vh - 160px - 32px - 16px - 104px);
}
.detail_box .car_list .car_box {
  background: #FFFFFF;
  padding: 16px;
  box-shadow: 0px 10px 30px rgba(102, 106, 149, 0.12);
  border-radius: 8px;
  margin-top: 8px;
  width: calc(100vw - 64px);
  margin-left: 16px;
}
.detail_box .car_list .car_box .car_item .car_number{
  font-size: 14px;
  color: #000000;
  line-height: 24px;
}
.detail_box .car_list .car_box .car_item .car_info {
  color: #787E86;
  font-size: 12px;
  line-height: 24px;
}

.no_list {
    width: calc(100% - 32px);
    padding-left: 16px;
    overflow: hidden;
}
.no_list .info {
    height: 48px;
    line-height: 48px;
    font-size: 12px;
    color: #999999;
    float: left;
}
.no_list .btn_box {
    float: right;
    height: 48px;
    width: 150px;
    background: #2B54FC;
    border-radius: 8px;
    text-align: center;
    line-height: 48px;
    font-size: 16px;
    color: #FFFFFF;
}


.code_box {
    display: flex;
    width: calc(100% - 32px);
    padding-left: 16px;
    padding-top: 16px;
}
.input_box {
    width: 12%;
    height: 44px;
    background: #F6F6F9;
    border-radius: 4px;
    margin-right: 0.5%;
    text-align: center;
    line-height: 44px;
}
.code_box input {
    /* position: absolute; */
    width: 100%;
    height: 100%;
}

js:

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

  /**
   * 页面的初始数据
   */
  data: {
    baiduToken:'',
    tempFiles:'',
    // carNumber:'',
    // carNumberArr:['', '', '', '', '', '' ,'', ''],
    carInfoList:[],

    showBtn: false,


    carNumerArr:[
        {value: "",focus: false,},
        {value: "",focus: false,},
        {value: "",focus: false,},
        {value: "",focus: false,},
        {value: "",focus: false,},
        {value: "",focus: false,},
        {value: "",focus: false,},
        {value: "",focus: false,},
    ],
    num_text:''



  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if(options.carNumber){
      let carNumber = options.carNumber.split("")
      let carNumerArr = []
      for(let i = 0; i < carNumber.length; i++){
        carNumerArr.push({
          value: carNumber[i],
          focus: false
        })
      }
      this.setData({
        carNumerArr: carNumerArr
      })
      this.getListData()
    }
  },









  // 上传车牌图片  
  chooseImg(e) {
    if (this.NextTap) {
      return;
    }
    this.NextTap = true;
    setTimeout(() => {
      this.NextTap = false;
    }, 1500)//1.5秒之后可以再次点击,防止用户重复点击
    this.chooseWxImage('type')//拍照
  },
  /**
   * 上传照片
   * @param {*} type 
   */
  chooseWxImage: function (type) {
    let that = this
    that.getBaiduToken()    // 提前获取access_Token
    wx.chooseMedia({
      count: 1, //默认9
      mediaType: ['image'],
    sizeType: ['compressed'], //可以指定是原图还是压缩图,默认二者都有   
    sourceType: ['album','camera'], //选择图片的来源
    success: (res) => {
          wx.showLoading({          
            title: '上传中',        
          })
          let tempFiles = res.tempFiles[0].tempFilePath
          console.log(tempFiles)
          this.setData({
            tempFiles: tempFiles,
            carNumber:[]
          })
          wx.getFileSystemManager().readFile({
            filePath: tempFiles,          
            encoding: 'base64',          
            success: function(res) {            
            //   console.log("[读取图片数据success]",res.data);            
              that.scanImageInfo(res.data);    // 调用百度API解析图片获取文字      
            },            
            fail: function(res){            
              console.log("[读取图片数据fail]",res)          
            },            
            complete: function(res){            
              wx.hideLoading()          
            }    
          })
          
      }
    })
  },

   // 获取百度access_token  
    getBaiduToken: function(){
        var apiKey = '*******';    
        var secKey = '*******';    
        var tokenUrl = `https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=${apiKey}&client_secret=${secKey}`;    
        var that = this;    
        wx.request({        
            url: tokenUrl,        
            method: 'POST',        
            dataType: 'json',        
            header:{            
                'content-type': 'application/json; charset-UTF-8'        
            },        
            success: function(res){            
                // console.log("[BaiduToken获取成功]",res);            
                that.setData({                
                    baiduToken: res.data.access_token                            })        
            },        
            fail: function(res){            
                console.log("[BaiduToken获取失败]",res);
            }    
        })  
    },

    // 百度ORC接口调用  
    scanImageInfo: function(imageData){    // 这里的imageData是图片转换成base64格式的数据
        var that = this;
        const detectUrl = `https://aip.baidubce.com/rest/2.0/ocr/v1/license_plate?access_token=${that.data.baiduToken}`    // baiduToken是已经获取的access_Token
        // console.log('123',detectUrl) 
        return new Promise(function(resolve,reject){        
            wx.request({            
                url: detectUrl,            
                data: {                
                    image: imageData            
                },            
                method: 'POST',            
                dataType: 'json',            
                header:{                
                    'Content-Type': 'application/x-www-form-urlencoded'    // 必须的        
                },            
                success: function(res, resolve){              
                    var word = res.data.words_result.number                  
                    let carNumber = word.split("")
                    let carNumberArr = []
                    carNumber.forEach(item => {
                        carNumberArr.push({
                            focus: false,
                            value: item
                        })
                    })
                    let delLen = 8 - carNumberArr.length
                    let delArr = []
                    for(let i = 0; i < delLen; i++){
                        delArr.push({value:'', focus: false})
                    }
                    let newCarNumerArr = [...carNumberArr,  ...delArr]
                    that.setData({
                        carNumerArr: newCarNumerArr
                    })
                    that.getListData()
                    },            
                fail : function(res,reject){              
                    console.log('get word fail:',res.data);    
                },            

            })
        }) 
    },

// 获取车辆
    getListData(){
        let carNumerArr = this.data.carNumerArr
        let num = ''
        for(let i = 0; i < carNumerArr.length; i++){
            num += carNumerArr[i].value
        }
        this.setData({
            num_text: num
        })
        if(num.length >= 3){
            app.$post.post(`/wx/..........Info?carNumber=${num}`, {}, true).then(res => {
                if(res.code == 0){
                    this.setData({
                        carInfoList: res.data,
                        showBtn: true
                    })
                }else{
                wx.showToast({
                    title: res.msg,
                    icon: 'none'
                })
                }
            })
        }else{
            wx.showToast({
                title: "车牌号至少3位",
                icon: 'none'
            })
        }

        
  
    },

// 修改车牌
// changeNumber(e){
//     let value = e.detail.value
//     let len = value.length
//     if(len >= 3){
//         this.setData({
//             carNumber: value
//         })
//         this.getListData()
//     }

// },

_handleInput(e){
    let index = e.currentTarget.dataset.index
    let carNumerArr = this.data.carNumerArr
    if(e.detail.value){
        let value = e.detail.value.substr(-1)   
        carNumerArr[index].value = value
        for(let i = 0; i < carNumerArr.length; i++){
            carNumerArr[i].focus = false
        }
        if(index == carNumerArr.length -1){
            carNumerArr[index].focus = true
        }else{
            carNumerArr[index+1].focus = true
        }
        
        
    }else{
        carNumerArr[index].value = ''
        for(let i = 0; i < carNumerArr.length; i++){
            carNumerArr[i].focus = false
        }
        if(index !== 0){
            carNumerArr[index-1].focus = true
        }else{
            carNumerArr[0].focus = true
        }
        
    }
    
    this.setData({
        carNumerArr,
    })
    this.getListData()
},

// 跳转
jumpToCarDetail(e){
  let carId = e.currentTarget.dataset.carid
  let carNumber = e.currentTarget.dataset.carnumber
  wx.redirectTo({
    url: `地址?carId=${carId}&carNumber=${carNumber}`
  })
},
// 添加车辆
addCar(){
    wx.redirectTo({
        url: `地址?carNumber=${this.data.num_text}&router=AISearch`
      })
},




  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.passwordBox = this.selectComponent('#passwordBox') // 获取密码框组件,用来操作组件内部的方法
  },

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

  },

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

  },

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

  },

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

  },

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