<script>
import axios from "@/utils/request";
export default{
  props: ['options','fetchOptions','value','multiple','width'],
  setup(props,context){
    
  },
  data() {
    return {
      innnerOptions: []
    }
  },
  methods: {

  },
  watch: {
    options: {
      handler(val) {
        if(val) this.innnerOptions = val;
      },
      immediate: true
    }
  },
  mounted() {
    if (this.fetchOptions) {//动态请求options
      this.loadOptions();
    }
  },
  methods: {
    getNestedValue(obj, path) {
      return path.split('.').reduce((acc, part) => acc && acc[part], obj);
    },
    async loadOptions() {
      try {
        const { baseURL, url, method, data, dataType ,dataPath="data.list",labelKey="name",valueKey="id" } = this.fetchOptions;
        const response = await axios.request({
          baseURL: baseURL || '',
          url,
          method,
          data: method.toLowerCase() === 'post' ? data : {},
          params: method.toLowerCase() === 'get' ? data : {},
          responseType: dataType || 'json'
        });
        const optionsData = this.getNestedValue(response, dataPath);
        this.innnerOptions = optionsData.map(item => ({
          value: item[valueKey],
          label: item[labelKey]
        }));
      } catch (error) {
        console.error('Error fetching options:', error);
      }
    }
  }

}


</script>

<template>
  <el-select v-model="value" :multiple="multiple" :style="{width: (width ? width : 192) + 'px' }" placeholder="请选择">
    <el-option
      v-for="item in innnerOptions"
      :key="item.value"
      :label="item.label"
      :value="item.value"
    />
  </el-select>
</template>

<style scoped>

</style>
