<template>
  <div class="edit-box" v-if="value !== null">
    <back-bar :title="`${$t('h5.edit')} ${$t(`h5.${type}`)}`"></back-bar>
      <el-input :placeholder="`${$t('h5.input')} ${$t(`h5.${type}`)}`" v-model="value" clearable autofocus></el-input>
      <div class="submit-wrap">
        <el-button type="primary" size="medium" @click="submit">完成</el-button>
      </div>
  </div>
</template>

<script>
import Vue from 'vue'
import API from '@/api'
import { Input } from 'element-ui'
import backBar from '@/components/backBar'
import { mapState, mapMutations, mapActions } from 'vuex'

Vue.component(Input.name, Input)

export default {
  name: 'editNickname',
  components: {
    backBar
  },
  computed: {
    ...mapState({
      group: state => state.group,
      userInfo: state => state.userInfo,
      groupName: state => state.group.groupName,
      groupNotice: state => state.group.groupNotice,
      nickname: state => state.userInfo.nick_name,
      username: state => state.userInfo.user_name
    }),
    type () {
      return this.$route.params.type
    }
  },
  data () {
    return {
      value: null
    }
  },
  methods: {
    ...mapMutations([
      'updateGroup',
      'setUserNickName',
      'updateMemberInfo',
      'setUserUserName',
      'initGroup',
      'changeSessionId'
    ]),
    ...mapActions([
      'updateSessionItem',
      'getUserInfo',
      'getGroupInfo'
    ]),
    submit () {
      if (!this.value.length) {
        this.$showTips(this.$t('userinfo.inputIsEmpty'))
        return
      }
      let value = this.value

      switch (this.type) {
        case 'nickname':
          if (value.length > 16) {
            this.$showTips(this.$t('userinfo.nickTooLong'))
            return
          }
          this.changeNickname(value)
          break
        case 'username':
          if (/^[a-zA-Z_0-9-]{5,20}$/i.test(value)) {
            this.changeUsername(value)
          } else {
            this.$showTips(this.$t('userinfo.wrongPattern'))
          }
          break
        case 'groupName':
          if (value.length > 16) {
            this.$showTips(this.$t('userinfo.groupNameTooLong'))
            return
          }
          this.changeGroupName(value)
          break
        case 'groupNotice':
          this.changeGroupNotice(value)
          break
      }
    },
    changeNickname (value) {
      API.user.changeNickName({
        nick_name: value
      }).then(({ data }) => {
        this.setUserNickName(value)
        this.updateMemberInfo({
          userId: this.$store.state.userId,
          nickName: value
        })
        this.successBack('/editMe')
      })
    },
    changeUsername (value) {
      API.user.changeUserName({
        user_name: value
      }).then(({ data }) => {
        this.setUserUserName(value)
        this.updateMemberInfo({
          userId: this.$store.state.userId,
          userName: value
        })
        this.successBack('/editMe')
      })
    },
    changeGroupName (value) {
      let { groupId } = this.group
      API.group.changeTitle({
        group_id: groupId,
        title: value
      }).then(({ data }) => {
        // 更新侧边栏
        this.updateSessionItem({
          sessionId: groupId,
          data: {
            name: value
          }
        })

        // 更新群组数据
        this.$store.commit('updateGroup', {
          key: 'groupName',
          data: value
        })

        this.successBack(`/groupSet/${groupId}`)
      })
    },
    changeGroupNotice (value) {
      let { groupId } = this.group
      API.group.changeNotice({
        group_id: groupId,
        notice: value
      }).then(() => {
        this.$showTips(this.$t('public.updateSucc'))

        this.$store.commit('updateGroup', {
          key: 'groupNotice',
          data: value
        })

        this.successBack(`/groupSet/${groupId}`)
      })
    },
    successBack (url) {
      this.$showTips(this.$t('public.updateSucc'))
      setTimeout(() => {
        this.$router.replace(url)
      }, 2000)
    }
  },
  async mounted () {
    if (this.type === 'nickname' || this.type === 'username') {
      !this.userInfo && await this.getUserInfo()
    } else {
      if (!this.group.groupId) {
        let groupId = this.$route.params.id
        this.initGroup({
          groupId: groupId,
          useCache: false
        })
        this.changeSessionId(groupId)
        await this.getGroupInfo()
      }
    }
    this.value = this[this.type]
  }
}
</script>

<style lang="scss">
.edit-box{
    .el-input__inner{
        height: px2rem(106);
        line-height: px2rem(106);
        border: none;
        border-radius: 0;
    }

    .submit-wrap{
      display: flex;
      justify-content: flex-end;
      margin-top: px2rem(10);
      padding: 0 px2rem(10);
    }
}
</style>
