<template>
    <div id="countrycode" >
        <Select v-model="value1" filterable clearable>
            <Option :key="index" v-for="(item,index) in dataList" :value="item.value">{{ item.label }}</Option>
        </Select>
    </div>
</template>

<script>
import codeData from '@/utils/countryCodeData.js';

export default {
    name: 'countrycode',
    props:['value'],
    model: {
        prop: "value", //绑定的值，通过父组件传递
        event: "update", //自定义时间名    
    },
    data() {
        return {
            lang: localStorage.getItem('local'),
            value1:'',
        }
    },
    computed:{
        dataList(){
            let data = []
            let LowerCaseLang = this.lang.toLowerCase()
            let k = ''
            switch (LowerCaseLang) {
                case 'zh-tw':
                    k = 'CountryTw'
                    break;
                case 'zh-cn':
                    k = 'CountryCn'
                    break;
                case 'zh-hk':
                    k = 'CountryTw'
                    break;
                default:
                    k = 'CountryEn'
                    break;
            }
            Object.keys(codeData).forEach(function(key){
                let OItem = codeData[key]
                //let lowerCaseCulture = OItem.Culture !='' ? OItem.Culture.toString().toLowerCase() : ''
                let label;
                label = '+' + OItem.Code + '(' + OItem[k] + ')'
                data.push({
                    label: label,
                    value: OItem.Code
                })
                //优先通过ip判断，如果ip判断结果为en-us则根据语系判断
                //if(LowerCaseLang == lowerCaseCulture){
                //    _this.value1 = OItem.Code
                //}
            })
            return data
        }
    },
    created:  function () {
        this.$api.regist.checkIp().then(
            res => {
                let LowerCaseLang = this.lang.toLowerCase()
                if (res !== 'en-us') {
                    LowerCaseLang = res
                }
                let k = Object.keys(codeData).filter((key) => {
                    return codeData[key].Culture.toString().toLowerCase() == LowerCaseLang
                })
                if (k) {
                    this.value1 = codeData[k].Code
                }
            },
            err => {
                console.log(err)
            }
        )
    },
    watch:{
        value1: function(newVal, oldVal){
            if(newVal == undefined) newVal = ''
            this.$emit("update", newVal); //子组件与父组件通讯，告知父组件更新绑定的值
        }
    },
    methods: {
    }
}
</script>
