<template>
    <div class="w100p">
        <el-cascader class="w100p"
            :options="list"
            :model-value="value"
            :show-all-levels="showAllLevels"
            :props="propsSync"
            :placeholder="placeholder"
            filterable
            clearable
            @change="onChange" />
    </div>
</template>

<script>
import {findParents} from "@/js_sdk/lib/findParents";

export default {
    name: "st-cascader",
    emits: ["change", "update:modelValue"],
    props: {
        modelValue: [String, Number,Array],
        list: {
            type: Array,
            default() {
                return [];
            }
        },
        labelKey: {
            type: String,
            default() {
                return "label";
            }
        },
        valueKey: {
            type: String,
            default() {
                return "value";
            }
        },
        childrenKey: {
            type: String,
            default() {
                return "children";
            }
        },
        expandTrigger: {
            type: String,
            default() {
                return "hover";
            }
        },
        showAllLevels: {
            type: Boolean,
            default: true
        },
        checkStrictly: {
            type: Boolean,
            default: true
        },
        placeholder: String
    },
    data() {
        return {
            value: this.modelValue
        }
    },
    computed: {
        propsSync() {
            return {
                value: this.valueKey,
                label: this.labelKey,
                children: this.childrenKey,
                expandTrigger: this.expandTrigger,
                checkStrictly: this.checkStrictly
            };
        }
    },
    watch: {
        modelValue: {
            handler() {
                this.value = this._setValue();
            },
            immediate: true
        },
        list: {
            handler() {
                this.value = this._setValue();
            },
            immediate: true
        }
    },
    methods: {

        onChange(values = []) {
            if (!this.$s.isArray(values)) values = [];
            this.value = values;
            let singleValue = values[values.length - 1] ?? "";
            this.$emit("update:modelValue", singleValue);
            this.$emit("change", {value: singleValue, values});
        },

        _setValue() {
            if (this.$s.isNull(this.modelValue)) return [];
            if (Array.isArray(this.modelValue)) return this.modelValue;
            let parents = findParents(this.list, this.modelValue, this.valueKey, this.childrenKey).map(item => item[this.valueKey]);
            return parents.length > 0 ? [...parents, this.modelValue] : [this.modelValue];
        }
    }
}
</script>