<template>
  <!-- 自定义下拉组件 -->
  <a-select
    show-search
    allowClear
    v-model:value="dataValue"
    @change="dataValueChange"
    style="width: 100%"
    :placeholder="placeholder"
    :disabled="readonly || disabled"
    :mode="isRadio ? '' : 'multiple'"
    :filter-option="dataFromType == 1 ? false : filterOption"
    @search="fetchSearch"
    @blur="dataValueBlur"
    @focus="dataValueFocus"
    @click="dataValueClick"
  >
    <a-select-option :value="realValueType == 1 ? item.id : item.code" v-for="item in dictList" :key="item.id" :label="item.name">{{
      item.name
    }}</a-select-option>
  </a-select>
</template>

<script setup name="CustomSelectComponent">
import { debounce } from 'lodash-es';
import { ref, onMounted, watch, computed } from 'vue';
import Request from '@/utils/request/request-util';

const props = defineProps({
  value: {
    type: [String, Array],
    default: undefined
  },
  //当前行配置
  record: {
    type: Object,
    default: {}
  },
  // 当前行数据
  formData: {
    type: Object,
    default: {}
  },
  //是否禁用
  disabled: {
    type: Boolean,
    default: false
  },
  placeholder: {
    type: String,
    default: '请选择'
  },
  // 是否只读
  readonly: {
    type: Boolean,
    default: false
  },
  // 是否是设计
  isDesgin: {
    type: Boolean,
    default: false
  },
  // 是否正常保存，不是转json格式
  normal: {
    type: Boolean,
    default: false
  },
  // 是否多选
  multiple: {
    type: Boolean,
    default: false
  },
  // 数据来源， 1： 动态接口；2：自定义填充
  dataSources: {
    type: Number,
    default: 1
  },
  // 后端接口, 用于动态接口
  backendUrl: {
    type: String,
    default: ''
  },
  // 取值类型 1: id;2: code
  valueType: {
    type: Number,
    default: 1
  },
  // 数据列表，用于自定义填充
  dataList: {
    type: Array,
    default: []
  }
});

const emits = defineEmits(['update:value', 'onChange', 'onBlur', 'onFocus', 'onClick']);

// 选中的值
const dataValue = ref(null);

// 可选中列表
const dictList = ref([]);

// 是否有关联字段
const linkFieldCode = ref('');

// 是否单选
const isRadio = computed(() => {
  if (props.record?.itemMultipleChoiceFlag || props.multiple) {
    return false;
  }
  return true;
});

// 数据来源
const dataFromType = computed(() => {
  if (props.record?.formItemSelect?.dataFromType) {
    return props.record.formItemSelect.dataFromType;
  } else if (props.dataSources) {
    return props.dataSources;
  }
  return 1;
});

// 真实取值类型 1: id;2: code
const realValueType = computed(() => {
  if (props.record?.formItemSelect?.valueType) {
    return props.record?.formItemSelect?.valueType;
  } else if (props.valueType) {
    return props.valueType;
  }
  return 1;
});

// 动态数据接口
const realBackendUrl = computed(() => {
  if (props.record?.formItemSelect?.backendUrl) {
    return props.record?.formItemSelect?.backendUrl;
  } else if (props.backendUrl) {
    return props.backendUrl;
  }
  return '';
});

onMounted(() => {
  if (props.record?.formItemSelect?.linkFieldCode) {
    linkFieldCode.value = props.record.formItemSelect.linkFieldCode;
  }

  if (props.dataSources == 2) {
    dictList.value = props.dataList;
  }
  getDictList();
  setValueData();
});

// 获取选择列表
const getDictList = searchText => {
  if (props.isDesgin || dataFromType.value != 1 || !realBackendUrl.value) return;
  let params = {
    searchText: searchText
  };
  if (linkFieldCode.value) {
    params[linkFieldCode.value] = props.formData[linkFieldCode.value];
    params.valueType = realValueType.value;
  }
  Request.get(realBackendUrl.value, params).then(res => {
    if (props.backendUrl) {
      dictList.value = res.data;
    } else {
      props.record.dictList = res.data;
    }
  });
};

// 后端搜索
const fetchSearch = debounce(value => {
  getDictList(value);
}, 500);

// 自定义过滤
const filterOption = (input, option) => {
  return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0;
};

// 更改值
const dataValueChange = () => {
  let data = '';
  if (!isRadio.value) {
    data = props.normal ? dataValue.value : dataValue.value?.length === 0 ? '' : JSON.stringify(dataValue.value);
  } else {
    data = dataValue.value;
  }
  emits('update:value', data);
  emits('onChange', props.record);
};

const setValueData = () => {
  // 多选
  if (!isRadio.value) {
    dataValue.value = props.value ? (props.normal ? props.value : JSON.parse(props.value)) : [];
  } else {
    dataValue.value = props.value;
  }
};

const dataValueClick = () => {
  emits('onClick', props.record);
}

const dataValueBlur = () => {
  emits('onBlur', props.record);
}

const dataValueFocus = () => {
  emits('onFocus', props.record);
}

watch(
  () => props.formData[linkFieldCode.value],
  val => {
    if (val) {
      getDictList();
    }
  },
  { deep: true }
);

watch(
  () => props.value,
  val => {
    setValueData();
  },
  { deep: true }
);

watch(
  () => props.record?.dictList,
  val => {
    if (val) {
      dictList.value = val;
    }
  },
  { deep: true, immediate: true }
);
</script>

<style></style>
