<script lang="ts" setup>
import { onBeforeMount, ref } from 'vue'
import type { FormRules } from 'naive-ui'
import { useDictionary } from '@/store/modules/dictonary'
import { useConfig } from '@/store/modules/asideConfig'
import { isString } from '@/utils/is'

const props = defineProps<{
  value: string[] | null
  label: string
}>()

const emit = defineEmits<{
  (e: 'update:value', value: string[]): void
}>()

const formValue = ref({
  plans: props.value,
})
const configUseStore = useConfig()
const isLoadValue = ref(false)

configUseStore.$subscribe(() => {
  if (isLoadValue.value) {
    isLoadValue.value = false
    return
  }
  const asideValue = configUseStore.getAsideValue
  if (asideValue.izvisitpro) {
    if (typeof asideValue.izvisitpro == 'string') {
      const list = asideValue.izvisitpro.split(',')
      formValue.value.plans = list
    }
    else {
      formValue.value.plans = asideValue.izvisitpro
    }
  }
  else {
    formValue.value.plans = []
  }
})
if (isString(formValue.value.plans)) {
  const list = (formValue.value.plans as string).split(',')
  formValue.value.plans = list
}
const rules: FormRules = {
  plans: [
    {
      required: false,
      type: 'array',
      trigger: ['blur', 'change'],
    },
  ],
}

const options = ref([])
const configStore = useDictionary()
const labStyle = {
  fontWeight: 'bold',
}

onBeforeMount(async () => {
  const list = await configStore.fetchIzvisitproList()
  options.value = list
})
function onChange(value: Array<string>) {
  isLoadValue.value = true
  emit('update:value', value)
}
</script>

<template>
  <n-form :model="formValue" style="padding: 0px 10px;" :rules="rules">
    <n-form-item :label="label" path="plans" :label-style="labStyle">
      <n-select
        v-model:value="formValue.plans"
        filterable :max-tag-count="2" placeholder="请选择省份" multiple :options="options"
        @update:value="onChange"
      />
    </n-form-item>
  </n-form>
</template>

<style lang="less" scoped></style>
