<template>
  <el-select v-model="proxyValue"
             :clearable="clearable"
             :placeholder="placeholder"
             :filterable="filterable || allowCreate || config?.remote"
             :allow-create="allowCreate"
             :disabled="disabled"
             :multiple="multiple"
             :remote="config?.remote"
             :remoteMethod="config?.remoteMethod && remoteMethod"
             :style="{width}">
    <el-option v-for="(option, index) in options"
               :key="index"
                 :disabled="option[optionProps.disabled]"
               :label="option[optionProps.label] ?? option"
               :value="option[optionProps.value] ?? option">
    </el-option>
  </el-select>
</template>
<script>
import { ElSelect, ElOption } from 'element-plus'
import { computed } from 'vue'
import { useFormInput, useOptions } from '@cip/components/hooks/form-input'
import { formInputProps } from '../../form-input-props'

export default {
  components: { ElSelect, ElOption },
  props: formInputProps,
  emits: ['update:modelValue', 'update:otherValue'],
  setup (props, context) {
    const { width, securityConfig, proxyOtherValue, ...formInput } = useFormInput(props, context)
    // 是否多选
    const multiple = computed(() => {
      return securityConfig.value.multiple ?? false
    })
    const { optionProps, options, getOptions, getValue, getModelValue, getOtherValue } = useOptions(props, multiple, formInput.emitInput, formInput.emitOtherValue)
    // 是否可搜索
    const filterable = computed(() => {
      return securityConfig.value.filterable ?? false
    })
    // 是否允许创建
    const allowCreate = computed(() => {
      return securityConfig.value.allowCreate ?? false
    })
    // 另一个键
    const otherKey = computed(() => {
      return securityConfig.value.otherKey ?? ''
    })
    // 内部代理一个Value
    const proxyValue = computed({
      get () {
        return getValue(props.modelValue)
      },
      set (value) {
        const modelValue = getModelValue(value)
        context.emit('update:modelValue', modelValue)
        if (otherKey.value) {
          const otherValue = getOtherValue(modelValue, value)
          context.emit('update:otherValue', otherValue)
        }
      }
    })
    const remoteMethod = async (query) => { options.value = await securityConfig.value.remoteMethod(query, props.dependOnValues) }
    if (securityConfig.value.remoteMethod) {
      const query = proxyOtherValue[0] ? proxyOtherValue[0].value : ''
      remoteMethod(query)
    }
    return {
      ...formInput,
      securityConfig,
      multiple,
      options,
      getOptions,
      filterable,
      allowCreate,
      proxyValue,
      width,
      optionProps,
      remoteMethod
    }
  }
}
</script>

<style lang="less" scoped>
.el-select{
  width: 100%;
}
</style>
