import { defineStore } from 'pinia';
import { getDictionaryType, getDictionary } from '@/api/sys/categories.ts'
import { ref } from 'vue'

export const useOnlineFormDesignStore = defineStore('onlineFormDesign', () => {
  const selectOptions = ref({})
  const selectDictionaryData = ref([])
  const timeout = ref()
  function setSelectOptions(key, code){
    let params = { code }
    getDictionary(params).then(res => {
      let data: any[] = []
      res.forEach(item => {
        data.push({
          value: item.itemValue,
          label: item.itemName,
        })
      })
      selectOptions.value[key] = data
    }).catch(error => {
      console.log(error)
    })
  }
  function getSelectOption(key){
    return selectOptions.value[key]? selectOptions.value[key] : []
  }
  function setSelectDictionaryData (dataList) {
    selectDictionaryData.value = dataList
  }
  function getSelectDictionaryData() {
    return selectDictionaryData.value
  }
  function getSelectData(value: string) {
    if (timeout.value) {
      clearTimeout(timeout.value);
      timeout.value = null;
    }
    function fake() {
      getDictionaryType()
        .then(res => {
            let data: any[] = [];
            res.forEach(item => {
              data.push({
                value: item.itemCode,
                label: item.itemName,
              })
            })
            if(value !== ""){
              data = data.filter(item => {
                return item.label.indexOf(value) > -1
              })
            }
            setSelectDictionaryData(data)
        });
    }
    timeout.value = setTimeout(fake, 300);
  }
  return {
    selectOptions,
    selectDictionaryData,
    setSelectOptions,
    getSelectOption,
    setSelectDictionaryData,
    getSelectDictionaryData,
    getSelectData,
  }
})