<template>
  <span v-if="isLook">{{ selectLook || '-' }}</span>
  <el-select
    v-else
    v-model="select"
    :multiple="props.formItem.isMultiple"
    :disabled="disabled"
    clearable
  >
    <el-option
      v-for="item in selectOptions"
      :key="item[selectField.value]"
      :label="item[selectField.label]"
      :value="item[selectField.value]"
    />
  </el-select>
</template>

<script setup lang="ts">
import { useOptions } from '../hooks/useOptions'
import { watch, ref, computed } from 'vue'

const props = defineProps({
  modelValue: {
    type: [String, Number, Array],
    default: () => ''
  },
  mode: {
    type: String,
    default: 'add'
  },
  formItem: {
    type: Object,
    default: () => {}
  },
  formData: {
    type: Object,
    default: () => {}
  },
  disabled: {
    type: Boolean,
    default: false
  }
})

const emits = defineEmits(['update:modelValue'])

const { options, field, isLook, select, select_look, getDynamicOptions, getUrlParams } = useOptions(
  props,
  emits
)

const selectLook = ref('')
selectLook.value = select_look
const selectField = ref(field)
const selectOptions = ref(options)

// 是否调用专门接口获取数据
const isApi = computed(
  () => typeof props.formItem.formHead === 'string' && props.formItem.formHead.includes('api')
)
// 是否包含动态参数部分 如果是 需要根据参数对应的值的变化进行动态更新
const dynamicKey = computed(() => {
  return isApi.value ? getUrlParams(props.formItem.formHead)[0] : ''
})
// 动态监听关联参数变化 进行被关联字段的重置操作
watch(
  () => props.formData?.[dynamicKey.value || props.formItem.prop],
  async (newValue, oldValue) => {
    // 1. 是api类型的
    if (isApi.value) {
      // 2. 如果有动态参数
      if (dynamicKey.value) {
        // 3. 动态参数对应的值有变化，并且不是初始化
        if (oldValue && newValue !== oldValue) {
          select.value = props.formItem.isMultiple ? [] : ''
        }
      }
      // 拿到返回的数据
      const res = await getDynamicOptions()
      selectOptions.value = res.options
      selectField.value = {
        value: 'id',
        label: 'name',
        remark: 'remark'
      }
      // 带api的查看详情处理
      if (isLook) {
        selectLook.value = props.formItem.isMultiple
          ? props.modelValue
              .map((i) => {
                const label = selectOptions.value.find((j) => j[selectField.value.value] === i)[
                  selectField.value.label
                ]
                const remark = selectOptions.value.find((j) => j[selectField.value.value] === i)[
                  selectField.value.remark
                ]
                return remark ? `${label}(${remark})` : label
              })
              .join('，')
          : selectOptions.value.find((j) => j[selectField.value.value] === props.modelValue)[
              selectField.value.label
            ]
      }
    }
  },
  {
    immediate: true,
    deep: true
  }
)
</script>
