<template>
	<uni-data-select v-model="select" :localdata="options" :disabled="readonly" @change="change"></uni-data-select>
</template>

<script>
	import {
		getAllChildren
	} from '@/api/system'
	import * as staticAll from './options.js'
	export default {
		name: "simpleSelect",
		props: {
			value: {
				type: [String, Number],
				required: false,
				default: null,
			},
			data: {
				type: [String, Array],
				required: true
			},
			loadType: {
				type: String,
				required: false,
				default: "local"
			},
			field: {
				type: String,
				required: false,
				default: "default"
			},
			ext: {
				type: Object,
				required: false,
				default: () => ({}),
			},
			readonly: {
				type: Boolean,
				required: false,
				default: false,
			}
		},
		computed: {
			isLocal() {
				return this.loadType === 'local'
			},
			isDict() {
				return this.loadType === 'dict'
			},
			isStatic() {
				return this.loadType === 'static'
			}
		},
		data() {
			return {
				select: this.value,
				options: [],
			};
		},
		watch: {
			value(n, o) {
				this.select = n
			},
			data(n, o) {
				this.init()
			}
		},
		mounted() {
			this.init()
		},
		methods: {
			init() {
				this.options = []
				if (this.isDict) {
					this.loadDict()
				} else if (this.isLocal) {
					this.options = this.data
				} else if (this.isStatic) {
					this.loadStatic()
				}
			},
			loadDict() {
				getAllChildren({
					enumid: this.data,
					isQueryFristNode: true,
					...this.ext
				}).then(resp => {
					const list = resp.data || []
					this.options = list.map(d => {
						const ret = {
							text: d.enumname,
							raw: d,
						}

						if (this.field === 'default') {
							ret.value = d.enumid
						} else if (this.field.startsWith('raw.')) {
							const [
								_,
								f
							] = this.field.split('\.')
							ret.value = d[f]
						}

						return ret
					})
				})
			},
			loadStatic() {
				const opts = staticAll[this.data]
				this.options = opts
			},
			change(n) {
				const o = this.options.find(d => d.value === n)
				this.$emit('input', this.select)
				this.$emit('on-change', this.select, o)
			}
		}
	}
</script>

<style>

</style>