<template>
  <view class="comp_form_query_search">
    <button class="scanBtn" hover-class="hover" @click="imageScan"><iconfont class="iconfont" icon="scan"/></button>
    <input :value="Value" placeholder="请输入" @change="change" @focus="focus" :type="controls[KEY].type" confirm-type="search" :disabled="controls[KEY].disabled"/>
    <button class="icon" @click="clear"><iconfont class="iconfont" icon="close-circle-fill" v-if="showClearIcon"/></button>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onBeforeMount, onMounted, onUnmounted, watch, nextTick } from 'vue'

const props = <any>defineProps({
  KEY: { type: String, required: true, }, // 组件字段
  data: { type: String, default: '', }, // 组件数据 v-modal
  controls: { type: Object, default: () => {}, }, // 组件配置
})
const Value:any = computed({ //v-modal:data
  get: () => props.data[props.KEY],
  set: v => emit('update:data', v)
})
const emit = defineEmits(['update:data','change:data','focus','blur', 'clear' , 'select'])


const showClearIcon = ref(false)

const change = (e:any) => {
  emit('change:data', e.detail.value)
  emit('select', e.detail.value)
  showClearIcon.value = Value.value ? true : false
}
const focus = () => {
  if(Value.value){
    clear()
  }
}
const clear = () => {
  Value.value = ''
  emit('change:data', '')
  emit('select', '')
  showClearIcon.value = false
}

const imageScan = () => {
  // 允许从相机和相册扫码
  uni.scanCode({
    success: function (res) {
      Value.value = res.result
      emit('select', res.result)
      emit('change:data', res.result)
    }
  });
}

onBeforeMount(async() => {
})
onMounted(()=>{
})
onUnmounted(() => {
})



</script>

<style lang="scss">
.comp_form_query_search{
  width: 100%;
  box-sizing: border-box;
  position: relative;
  display: flex;
  background: #fff;
  border-radius: 20rpx;
  >.scanBtn{
    flex-grow: 0;
    height: 32px;
    line-height: 32px;
    background: $primary-color;
    opacity: 0.8;
    color: #fff;
    padding: 0 20rpx;
    border-radius: 20rpx 0 0 20rpx;
    transition: 0.3s all;
    &:hover{
      opacity: 1;
    }
  }
  >input{
    font-size: 13px;
    padding: 10rpx 15rpx;
    flex-grow: 1;
    flex-shrink: 1;
  }
  
  .icon{
    position: absolute;
    right: 0;
    top: 0;
    border: none;
    outline: none;
    background: none;
    height: 32px;
    color: #666;
    z-index: 2;
    .iconfont{
      height: 32px;
      >view{
        height: 32px;
        line-height: 32px;
      }
    }
    &::after{
      border: none;
      outline: none;
      background: none;
    }
  }
}
</style>
