<!-- 省市区三级联动 -->
<template>
  <el-cascader :options="options" v-model="selectedOptions" @change="handleChange" v-bind='$attrs'></el-cascader>
</template>

<script>
    import {
        CodeToText,
        TextToCode,
        regionData,
        regionDataPlus,
        provinceAndCityData,
        provinceAndCityDataPlus,
    } from 'element-china-area-data'
    export default {
        name: 'enoDistpicker',
        data() {
            return {
                options: [],
                selectedOptions: [],
            }
        },
        model: {
            prop: 'district',
            event: 'change',
        },
        props: {
            cascaderLevel: {
                type: String,
                default: 'third',
            },
            district: Array,
        },
        components: {},
        computed: {},
        watch: {
            district: {
                handler(newVal) {
                    if(!newVal||!newVal.length){
                        this.selectedOptions = [];
                        return
                    }
                    let province = TextToCode[newVal[0]].code
                    let city = TextToCode[newVal[0]][newVal[1]].code
                    let country = TextToCode[newVal[0]][newVal[1]][newVal[2]].code
                    this.selectedOptions = [province, city, country]
                },
                immediate: true,
            },
        },
        created() {
            switch (this.cascaderLevel) {
                case 'third':
                    this.options = regionData
                    break
                case 'thirdAll':
                    this.options = regionDataPlus
                    break
                case 'second':
                    this.options = provinceAndCityData
                    break
                case 'secondAll':
                    this.options = provinceAndCityDataPlus
                    break
            }
        },
        methods: {
            handleChange(value) {
                if (!value || !value.length) return
                if (this.cascaderLevel.includes('second')) {
                    this.$emit('change', [
                        CodeToText[value[0]],
                        CodeToText[value[1]],
                        value,
                    ])
                } else if (this.cascaderLevel.includes('third')) {
                    this.$emit('change', [
                        CodeToText[value[0]],
                        CodeToText[value[1]],
                        CodeToText[value[2]],
                        value,
                    ])
                }
            },
        },
    }
</script>

<style scoped lang='less'>
  .el-cascader {
    line-height: 32px;
  }
</style>
