<template>
  <div class="l-flex--col">
    <div class="l-flex--row c-sibling-item--v c-line">
      <div class="c-line__left u-color--black u-bold">{{ config.label }}</div>
      <el-input
        v-if="initial || expanded"
        v-model="cValue"
        class="l-flex__fill c-sibling-item"
        :maxlength="config.maxlength"
        :placeholder="'请输入'+config.tipText"
        :readonly="!expanded"
      />
      <div class="c-sibling-item c-line__right">
        <button
          v-if="expanded === false"
          class="o-button"
          @click="onExpanded"
        >
          {{ initial ? '更换' : '绑定' }}{{ config.label }}
        </button>
        <div
          v-else
          class="u-pointer u-color--blue"
          @click="onUnexpanded"
        >
          收起
        </div>
      </div>
    </div>
    <template v-if="expanded">
      <div class="l-flex--row c-sibling-item--v far c-line">
        <div class="c-line__left" />
        <div class="l-flex__fill l-flex--row c-sibling-item">
          <el-input
            v-model="code"
            class="l-flex__fill c-sibling-item"
            maxlength="6"
            placeholder="验证码"
            @keydown.enter="onBind"
          />
          <el-button
            class="l-flex__none c-sibling-item o-button"
            :disabled="verification"
            @click="sendCode"
          >
            {{ codeText }}
          </el-button>
        </div>
        <div class="c-sibling-item c-line__right" />
      </div>
      <div class="l-flex--row c-sibling-item--v far c-line">
        <div class="c-line__left" />
        <div class="l-flex__fill c-sibling-item l-flex--row">
          <el-button
            class="o-button l-flex__fill"
            @click="onBind"
          >
            绑定
          </el-button>
        </div>
        <div class="c-sibling-item c-line__right" />
      </div>
    </template>
  </div>
</template>

<script>
import {
  validPhone,
  validEmail
} from '@/utils/validate'
import {
  authcodeSend,
  authcodeCheck
} from '@/api/user'

const COUNTDOWN = 60
const config = {
  phone: {
    label: '手机',
    tipText: '手机号',
    maxlength: 11,
    valid: validPhone,
    typeKey: 'phoneNum',
    codeKey: 'phoneNumAuthCode',
    checkKey: 'checkPhoneNum'
  },
  email: {
    label: '邮箱',
    maxlength: 50,
    valid: validEmail,
    tipText: '邮箱',
    typeKey: 'email',
    codeKey: 'emailAuthCode',
    checkKey: 'checkEmail'
  }
}

export default {
  name: 'UserInfoItem',
  props: {
    type: {
      type: String,
      require: true,
      default: 'phone'
    },
    value: {
      type: String,
      default: ''
    },
    initial: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      config: {},
      code: null,
      expanded: false,
      verification: false,
      countDown: COUNTDOWN
    }
  },
  computed: {
    cValue: {
      get () {
        return this.value
      },
      set (v) {
        this.$emit('input', v)
      }
    },
    codeText () {
      return this.verification ? `${this.countDown} s` : '发送验证码'
    }
  },
  watch: {
    initial () {
      this.reset()
    }
  },
  created () {
    this.config = config[this.type]
  },
  beforeDestroy () {
    clearInterval(this.$timer)
  },
  methods: {
    onExpanded () {
      this.cValue = ''
      this.expanded = true
    },
    onUnexpanded () {
      this.cValue = this.initial
      this.expanded = false
    },
    reset () {
      this.cValue = this.initial
      this.expanded = false
      this.code = ''
      this.verification = false
      this.countDown = COUNTDOWN
      clearInterval(this.$timer)
    },
    sendCode () {
      if (this.verification) {
        return
      }
      if (!this.value) {
        this.$message({
          type: 'warning',
          message: `${this.config.tipText}不能为空`
        })
        return
      }
      if (!this.config.valid(this.value)) {
        this.$message({
          type: 'warning',
          message: `${this.config.tipText}格式错误`
        })
        return
      }
      if (this.value === this.initial) {
        this.$message({
          type: 'warning',
          message: `${this.config.tipText}不能相同`
        })
        return
      }
      authcodeSend({
        [this.config.typeKey]: this.value
      })
        .then(({ success, errMessage }) => {
          if (success) {
            this.$message({
              type: 'success',
              message: '验证码已发送...'
            })
            this.verification = true
            this.countDown = COUNTDOWN
            this.$timer = setInterval(() => {
              this.countDown--
              if (this.countDown <= 0) {
                this.verification = false
                this.countDown = COUNTDOWN
                clearInterval(this.$timer)
              }
            }, 1000)
          } else {
            console.log(errMessage)
          }
        })
        .catch(err => {
          console.log(err)
        })
    },
    onBind () {
      if (!this.value) {
        this.$message({
          type: 'warning',
          message: `${this.config.tipText}不能为空`
        })
        return
      }
      if (!this.code) {
        this.$message({
          type: 'warning',
          message: `验证码不能为空`
        })
        return
      }
      if (this.value === this.initial) {
        this.$message({
          type: 'warning',
          message: `${this.config.tipText}不能相同`
        })
        return
      }
      authcodeCheck({
        [this.config.typeKey]: this.value,
        [this.config.codeKey]: this.code
      }).then(({ success, data }) => {
        if (success) {
          if (data[this.config.checkKey]) {
            this.$emit('update', () => this.reset())
            return
          }
        }
        this.$message({
          type: 'error',
          message: `验证码错误`
        })
      }).catch(err => {
        console.log(err)
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.c-line {
  width: 460px;

  &__left {
    flex: 0 0 116px;
    padding-right: $spacing;
    font-size: 14px;
    text-align: right;
  }

  &__right {
    flex: 0 0 100px;
  }
}

.o-button {
  &:hover {
    color: #fff;
  }

  &.is-disabled {
    color: $blue;
    border: 1px solid $blue;
  }
}
</style>
