<template>
  <view class="comp_form_input_select" >
    <picker 
      mode="selector" 
      @change="chooseItem" 
      range-key="label"
      :value="active_index" 
      :range="optionsList"
      :disabled="controls[KEY].disabled"
    >
      <view class="item_input">{{label}} <iconfont class="iconfont" icon="right"/></view>
      
    </picker>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onBeforeMount, onMounted, onUnmounted, watch, nextTick,  getCurrentInstance} from 'vue'
import { translate } from '@/common/utils/language/index'
import { getOptionsToType, filter, setMappings, getOption } from '@/common/utils/select'
import lodash from 'lodash'
import { getCarryData, clearCarryData } from '../js/index'
import EXEC from '@/common/utils/exec'

const props = <any>defineProps({
  KEY: { type: String, required: true, }, // 组件字段
  data: { type: String, default: '', }, // 组件数据 v-modal
  controls: { type: Object, default: () => {}, }, // 组件配置
})
const active_index = <any>ref(0)
const Value:any = computed({ //v-modal:data
  get: () => props.data[props.KEY],
  set: v => emit('update:data', v)
})
const _select:any =  computed( ()=> props.controls[props.KEY].select ) // 获取配置中select配置

const emit = defineEmits(['update:data','change:data','focus','blur', 'clear'])


const showClearIcon = ref(false)
// 事件 ========================================================================================
const label = ref('')
const chooseItem = async (item:any) => {
  let data = optionsList.value[item.detail.value].value
  Value.value = data
  emit('change:data', data)
}
const clear = () => {
  Value.value = ''
  emit('change:data', '')
  showClearIcon.value = false
}

// 选线 ========================================================================================
const optionsList:any = ref([])
const timer:any = ref(null)
const setOptionsList:any = () => { // 设置选项列表到控件上；选项已处理过联动、过滤等
    clearTimeout(timer.value)
    let staticOptions:any = [] // 固定options
    if(_select.value.options){
        staticOptions = optionFilter(_select.value.options, props.controls[props.KEY])
    }    

    let apiOptions:any = []  // 接口options  
    apiOptions = optionFilter(OPTIONS.value, props.controls[props.KEY])

    // 合并固定选项和接口选项
    let newOptions = staticOptions.concat(apiOptions) 
    optionsList.value =  newOptions
    optionsList.value = optionsList.value.reverse()

    let i = 0 
    if(props.controls[props.KEY].required){
      i = 0 
    }else{
      optionsList.value.unshift({value: '', label: translate('please select')})
      i = 1
    }
    timer.value = setTimeout(()=>{
      if(Value.value){
        for(let i in optionsList.value){
          if(Value.value == optionsList.value[i].value){
            active_index.value = Number(i)
            label.value = optionsList.value[i].label
            break
          }
        }
        if(!label.value) label.value = Value.value
      }else{
        getDefaultValue(newOptions[i], newOptions)
      }
      clearTimeout(timer.value)
    },200)
}
const debounceSetOptionsList = lodash.throttle(setOptionsList, 100, { // 获取列表防抖
    leading: true,
    trailing: true,
})
// 处理列表选项；处理联动、过滤等
const optionFilter = (options:any = [] ,controls:any) => filter(options, controls)
const OPTIONS:any = ref([])

const getTypeOptions = (Refresh = false) => { 
  /**
   *  1，调用时机：1在创建时调用、2在OPTIONS为空时或者alawayAPI为true时下拉调用、3主动点击控件刷新按钮时
   */
  let type = _select.value.type || ''
  if(!type) {
      debounceSetOptionsList()
      return
  }

  // 判断是否存在父级并且必填
  if(props.controls[props.KEY].parents?.length>0){
      for(let parentKey of props.controls[props.KEY].parents){
          if(!props.controls[props.KEY].params[parentKey] || props.controls[props.KEY].params[parentKey].length==0){
              OPTIONS.value = []
              optionsList.value = []
              return
          }
      } 
  }

  getOptionsToType({type:_select.value.type, params: props.controls[props.KEY].params, system: _select.value.system}, Refresh).then(async res => {
      OPTIONS.value = res
  }).then(()=>{
      debounceSetOptionsList()
      
  })


}

const getDefaultValue = (item:any, rows:any) => {
  if(_select.value.getDefault && props.controls[props.KEY]['def_value'] && props.controls[props.KEY]['def_value']!='$$SELECT()' && _select.value.getDefault != 'true'&& (!Value.value ||  Value.value.length==0)){
      if(_select.value.multiple){ // 多选时，值的类型是数组；
          let value:any = props.controls[props.KEY]['def_value'].split(',')
          Value.value = value
          emit('change:data', value)
      }else{ // 单选时，值是字符串
          let value:any = props.controls[props.KEY]['def_value']
          Value.value = value
          emit('change:data', value)
      }
  }else if(_select.value.getDefault && item && (!Value.value ||  Value.value.length==0)){
      let value:any = item.value
      if(_select.value.multiple){ // 多选时，值的类型是数组；
          Value.value = [value]
          emit('change:data', [value])
      }else{ // 单选时，值是字符串 
          Value.value = value
          emit('change:data', value)
      }
  }
  else if(props.controls[props.KEY].required && rows.length==1 && (!Value.value ||  Value.value.length==0) ){ 
      let value:any = item.value
      Value.value = value
      emit('change:data', value)
  }
}

// 生命周期 ========================================================================================
onBeforeMount(async() => {
})
onMounted(()=>{
  getTypeOptions(false)
})
onUnmounted(() => {
})




// 监听 ========================================================================================
// 监听联动
watch(  
    ()=>props.controls[props.KEY].params,
    (newData,oldData)=>{
      getTypeOptions(false)
    },
    { immediate: false, deep: true, }
)
watch(
  ()=>Value.value,
  ()=>{
    for(let i in optionsList.value){
      if(Value.value == optionsList.value[i].value){
        active_index.value = Number(i)
        label.value = optionsList.value[i].label
        props.controls[props.KEY].select.activeOption = optionsList.value[i]
        break
      }
    }
    if(!label.value) label.value = Value.value
    setMappings(props.data, props.controls[props.KEY])
    if(Value.value){
      getCarryData({ formData:props.data, key:props.KEY, carry: props.controls[props.KEY]['carry'],  })
    }else{
      clearCarryData({ formData:props.data, key:props.KEY, carry: props.controls[props.KEY]['carry'] })
    }
  },
  { 
    immediate: true, deep: true,
  }
) 

</script>

<style lang="scss">
.comp_form_input_select{
  width: 100%;
  position: relative;
  display: flex;
  text-align: right;

  .item_input{
    display: flex;
    justify-content: flex-end;
    
    .iconfont{
      height: 80rpx;
      color: #999;
      font-size: 24rpx;
      margin-left: 10rpx;
      >view{
        height: 80rpx;
        line-height: 80rpx;
      }
    }
  }
  
  picker{
    line-height: 80rpx;
    height: 80rpx;
    text-align: right;
    flex-grow: 1;
    flex-shrink: 1;
  }
}
</style>
