<template>
  <section class="AiID">
    <el-input :size="size" v-if="mode=='input'" v-model="idNumber" @change="autocomplete" clearable :disabled="disabled"
              :placeholder="placeholder" :maxLength="18"></el-input>
    <el-row type="flex" v-if="mode=='show'" style="align-items: center">
      <el-button type="text" v-if="!rightBtn&&showEyes" :icon="showIcon" @click="isShow=!isShow"></el-button>
      <span v-if="isShow">{{ value || "-" }}</span>
      <span v-else>{{ hideId }}</span>
      <el-button type="text" v-if="rightBtn&&showEyes" :icon="showIcon" @click="isShow=!isShow"></el-button>
    </el-row>
  </section>
</template>

<script>
import tools from '../../meta/js/utils'

export default {
  name: "AiId",
  model: {
    prop: "value",
    event: "change"
  },
  inject: {
    ElFormItem: {default: ""},
  },
  props: {
    value: String,
    mode: {type: String, default: 'input'},
    rightBtn: Boolean,
    size: String,
    show: {type: Boolean, default: false},
    disabled: Boolean,
    placeholder: String,
    showEyes: {type: Boolean, default: true}
  },
  computed: {
    showIcon() {
      return this.isShow ? 'iconfont iconHide_Content' : 'iconfont iconShow_Content'
    },
    hideId() {
      if (this.value) {
        let idArr = JSON.parse(JSON.stringify(this.value))
        return tools.idCardNoUtil.hideId(idArr)
      } else return "-"
    }
  },
  data() {
    return {
      isShow: false,
      idNumber: ""
    }
  },
  watch: {
    value(v) {
      this.idNumber = v
      this.dispatch('ElFormItem', 'el.form.change', [v]);
      this.autocomplete()
    }
  },
  methods: {
    autocomplete() {
      this.$emit("change", this.idNumber)
      let id = this.idNumber, {$dateFormat, $moment} = tools
      if (id) {
        let birthday = $dateFormat($moment(id.substring(6, 14), 'YYYYMMDD'))
        if (id.length == 18) {
          this.$emit("auto", {
            birthday,
            sex: "" + Number(id.substring(16, 17)) % 2,
            age: Math.ceil($moment.duration($moment().unix() - $moment(birthday, "YYYY-MM-DD").unix(), 's').asYears()),
            areaId: id.substring(0, 6) + "000000",
          })
        }
      }
    },
    dispatch(componentName, eventName, params) {
      let parent = this.$parent || this.$root;
      let name = parent.$options.componentName;

      while (parent && (!name || name !== componentName)) {
        parent = parent.$parent;

        if (parent) {
          name = parent.$options.componentName;
        }
      }
      if (parent) {
        parent.$emit.apply(parent, [eventName].concat(params));
      }
    },
  },
  created() {
    this.idNumber = this.value;
    this.autocomplete()
    this.isShow = this.show
  }
}
</script>

<style lang="scss" scoped>
.AiID {
  line-height: 32px;
}
</style>
