<template>
  <div class="inputp">
    <div class="inputs">
      <u-icon name="search" size="35" class='searchimg' @click='search'/>
      <input type="text" v-model="searchval" :placeholder="placeholder" @blur="search" confirm-type="search" inputmode="search" ref='searchinput' :focus='isfocus'
             class='scaninput' @confirm='search' >
      <u-icon name="scan" size="35" class="scanimg" @click='clickscan'/>
    </div>
  </div>
</template>

<script>
export default {
  name: 'SearchInput',
  props: {
    hasscanbtn: Boolean,//是否有扫码按钮
    isfocus: Boolean,//是否默认focus
    hasgosearch: Boolean,//是否要跳转到搜索界面
    types: Number,//跳转的时候的参数type值
    placeholder: {
      type: String,
      default: '搜索车辆编号'
    },
    gourl: {//跳转的搜索页面
      type: String,
      default: '/pages/scan/scan'
    }
  },
  data() {
    return {
      showsearchbtn: false,
      searchval: ''
    };
  },
  methods: {
    // 点击input的时候
    clickinput() {
      // var me = this;
      // if (me.hasgosearch) {
      //   console.log('需要跳转')
      //   uni.navigateTo({
      //     url: `${me.gourl}?type=${me.types}`
      //   })
      // }
    },
    // 搜索
    search() {
      var me = this;
      if (me.searchval === '') {
        uni.showToast({
          icon: 'none',
          title: '请先输入搜索内容'
        })
        return;
      }
      me.$emit('serach', me.searchval)
    },
    // 点击扫码的时候
    clickscan() {
      var me = this;
      if (me.hasscanbtn) {
        uni.navigateTo({
          url: `${me.gourl}?cameratype=scan&type=${me.types}`
        })
        return;
      }
      uni.scanCode({
        success(res) {
          var result = res.result;
          var arrs = result.split('?')[1].split('&')
          var code = '';
          arrs.forEach(e => {
            var arr = e.split('=')
            if (arr[0] === 'code') {
              code = arr[1];
            }
          })
          me.searchval = code;
        }
      })
    }
  },
  watch: {
    searchval(v) {
      var me = this;
      me.$emit('inputchange', v)
      if (v != '') {
        me.showsearchbtn = true;
      } else {
        me.showsearchbtn = false;
      }
    }
  }
}
</script>

<style lang="less" scoped>
.inputp {
  padding: 20upx;

  .inputs {
    background: #F2F2F2;
    border-radius: 20upx;
    position: relative;

    .scaninput {
      padding: 20upx 80upx 20upx 80upx;
      line-height: 1em;
      height: 1em;
      min-height: 1em;
    }

    .searchimg {
      width: 1em;
      height: 1em;
      position: absolute;
      top: 25upx;
      left: 20upx;
    }

    .scanimg {
      width: 1em;
      height: 1em;
      position: absolute;
      top: 25upx;
      right: 20upx;
    }

    .searchbtn {
      position: absolute;
      right: 20upx;
      top: 15upx;
      border-radius: 5upx;
      background: #007AFF;
      color: #fff;
      width: 4em;
      line-height: 2em;
      text-align: center;
      font-size: 0.8em;
    }
  }
}
</style>
