<template>
  <view class="comp_form_input_select" >
    <view class="item_input" @click="openPick()">{{ Value }} <iconfont class="iconfont" icon="right"/></view>

    <multiple-picker 
        title="请选择" 
        :show="selectMultiple.show" 
        :columns="selectMultiple.options" 
        :defaultIndex="selectMultiple.index" 
        @confirm="confirmMultiple" 
        @cancel="selectMultiple.show = false"
    ></multiple-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 EXEC from '@/common/utils/exec'
import { getCarryData, clearCarryData } from '../js/index'


const selectMultiple:any = reactive({
  show: false,
  index: [],
  options: [],
})
const openPick = () => {
  selectMultiple.show = true
  selectMultiple.options = optionsList.value
}

const confirmMultiple = (e:any) => {
    selectMultiple.index = []
    for(let i=0;i<optionsList.value.length;i++){
      for(let data of e.value){
        if(optionsList.value[i].value == data){
          selectMultiple.index.push(i)
        }
      }
    }
    Value.value = e.value
    emit('change:data', e.value)
    selectMultiple.show = false;
}

const props = 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 _select:any =  computed( ()=> props.controls[props.KEY].select ) // 获取配置中select配置

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


const showClearIcon = ref(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

    timer.value = setTimeout(()=>{
        getDefaultValue(newOptions[0], newOptions)
        clearTimeout(timer.value)
    },100)
}
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)){
      let value:any = props.controls[props.KEY]['def_value'].split(',')
      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(props.controls[props.KEY].select?.type == "comp_id" || props.controls[props.KEY].select?.type == "SYS|system3"){
          // 系统下拉，公司下拉，默认为当前url中的值
          if(props.controls[props.KEY].select?.type == "comp_id" )
              value = EXEC['comp_id']
          else if(props.controls[props.KEY].select?.type == "SYS|system3" )
              value = EXEC['system_id']
      }
      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,
  ()=>{
    selectMultiple.index = []
    for(let i=0;i<optionsList.value.length;i++){
      for(let data of Value.value){
        if(optionsList.value[i].value == data){
          selectMultiple.index.push(i)
        }
      }
    }
    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,
  }
) 

</script>

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

  .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>
