<template>
  <div>
    <img v-if="info.img_url" class="logo_img" :src="info.img_url" :width="width" :height="height" />
    <div v-else class="user_name_div" :style="{
	   width: width,
	   height: height,
	   lineHeight: height, 
	   fontSize: fontSize + 'rem'}">
	   {{name}}
	 </div>
  </div>
</template>
<script>
  export default {
    name: 'userImage',
    props: {
      width: {
        type: String,
        default: '0.8rem'
      },
      height: {
        type: String,
        default: '0.8rem'
      },
      id:{
        type: Number,
        default: 0
      },
      img_url: {
        type: String,
        default: ''
      },
      user_name: {
        type: String,
        default: ''
      },
      fontSize:{
        type: String,
        default: '0.32'
      }
    },
    watch:{
      id: function (val) {
        this.set_info()
        this.name_no()
      },
      img_url: function (val) {
        this.set_info()
        this.name_no()
      },
      user_name: function (val) {
        this.set_info()
        this.name_no()
      }
    },
    // 数据
    data(){
      let info ={name:'',img_url: '',id:0}
      if(this.img_url != ''){
        info.img_url = this.img_url
      }
      if(this.user_name != ''){
        info.name = this.user_name
      }
      return {
        info: info,
        name: '',
      }
    },
    computed:{
    },
    // 方法
    methods:{
      set_info(){
        let info ={name:'',img_url: '',id:0}

        if(this.img_url != ''){
          info.img_url = this.img_url
        }
        if(this.user_name != ''){
          info.name = this.user_name
        }
        this.info = info
      },
      // 加载
      name_no(){
        if(!this.info.img_url){
          let pattern = new RegExp("^[\u4E00-\u9FA5]+");
          if(this.info.name.length > 2){
            if(pattern.test(this.info.name)){
              this.name = this.info.name.substring(this.info.name.length-2,this.info.name.length)
            }else{
              this.name = this.info.name.substring(0,2)
            }
          }else{
            this.name = this.info.name
          }
        }
      }
    },
    // 组件挂载完成
    mounted() {
      this.name_no()
    },
  }
</script>
<style scoped>
  .user_name_div{
	border-radius: 50%;
	background: #238dfa;
	text-align: center;
	color: #fff;
  }
  .logo_img{
    border-radius: 50%;
  }
</style>
