<template>
  <div class="edit-user-form">
    <el-drawer
      :title="$t('pages.editUserForm.dialog.title')"
      :visible="true"
      :before-close="handleClose"
      :close-on-press-escape="false"
      :wrapper-closable="false"
      :modal-append-to-body="true"
      :append-to-body="true"
      custom-class="drawer-auto-layout"
    >
      <div class="edit-user-profile-form">
        <div class="drawer-form">
          <el-form
            ref="dataForm"
            v-loading="listLoading"
            :rules="rules"
            :model="formData"
            label-position="left"
            label-width="70px"
          >
            <el-form-item :label="$t('pages.editUserForm.form.nickname')" prop="userNickname">
              <el-input
                v-model.trim="formData.userNickname"
                :placeholder="$t('pages.editUserForm.placeholder.nickname')"
              />
            </el-form-item>

            <el-form-item :label="$t('pages.editUserForm.form.gender')" prop="userSex">
              <el-select
                v-model="formData.userSex"
                :placeholder="$t('pages.editUserForm.placeholder.gender')"
                style="width: 100%;"
              >
                <el-option
                  v-for="item in genders"
                  :key="item.value"
                  :label="getGenderLabel(item.value)"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>

            <el-form-item :label="$t('pages.userBaseInfo.labels.age')" prop="email">
              <el-date-picker
                v-model="formAgeDate"
                style="width: 100%;"
                type="date"
                :placeholder="$t('pages.editUserForm.placeholder.birthDate')"
                value-format="yyyy-MM-dd"
              />
            </el-form-item>
            <el-form-item :label="$t('pages.userBaseInfo.labels.country')" prop="email">
              <contry-select
                v-if="formData.countryId"
                v-model="formData.countryId"
                @change="contrySelectChange"
              />
            </el-form-item>
          </el-form>
        </div>
        <div class="drawer-footer">
          <el-button @click="handleClose()">{{ $t('pages.editUserForm.action.close') }}</el-button>
          <el-button type="primary" @click="handleSubmit()">{{ $t('pages.editUserForm.action.submit') }}</el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import { genders } from '@/constant/user'
import { getUserBaseInfo, updateBaseInfo } from '@/api/app-user'
import { formatDate, getAge } from '@/utils'
import ContrySelect from '@/components/data/ContrySelect'
export default {
  name: 'EditUserForm',
  components: { ContrySelect },
  props: {
    userId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      genders,
      listLoading: false,
      rules: {
        userNickname: [
          {
            required: true,
            message: this.$t('pages.editUserForm.validation.nicknameRequired'),
            trigger: 'blur'
          }
        ],
        userSex: [{
          required: true,
          message: this.$t('pages.editUserForm.validation.genderRequired'),
          trigger: 'blur'
        }]
      },
      formData: {
        userNickname: '',
        userSex: '',
        age: '',
        bornYear: '',
        bornMonth: '',
        bornDay: '',
        countryId: '',
        countryName: '',
        countryCode: ''
      },
      formAgeDate: ''
    }
  },
  watch: {
    userId: {
      handler(newVal) {
        if (newVal) {
          this.renderData()
        }
      },
      immediate: true
    },
    formAgeDate: {
      immediate: true,
      deep: true,
      handler(newVal) {
        if (newVal && newVal.length > 0) {
          this.formData.bornYear = formatDate(newVal, 'yyyy')
          this.formData.bornMonth = formatDate(newVal, 'MM')
          this.formData.bornDay = formatDate(newVal, 'dd')
          this.formData.age = getAge(newVal)
          return
        }
      }
    }
  },
  methods: {
    getGenderLabel(value) {
      return value === 0
        ? this.$t('pages.userBaseInfo.words.female')
        : this.$t('pages.userBaseInfo.words.male')
    },
    renderData() {
      const that = this
      that.listLoading = true
      getUserBaseInfo(that.userId)
        .then(res => {
          that.listLoading = false
          Object.assign(that.formData, res.body)
          console.log('that.formData', that.formData)
          if (
            that.formData.bornYear &&
            that.formData.bornMonth &&
            that.formData.bornDay
          ) {
            that.formAgeDate =
              that.formData.bornYear +
              '-' +
              that.formData.bornMonth +
              '-' +
              that.formData.bornDay
          }
        })
        .catch(er => {
          that.listLoading = false
        })
    },
    handleSubmit() {
      const that = this
      that.$refs.dataForm.validate(valid => {
        if (!valid) {
          console.error('error submit!!')
          return false
        }
        that.listLoading = true
        updateBaseInfo(that.formData)
          .then(res => {
            that.listLoading = false
            that.$emit('success', Object.assign({}, that.formData))
            that.handleClose()
          })
          .catch(err => {
            that.listLoading = false
            that.$emit('fial', err)
            that.handleClose()
          })
      })
    },
    handleClose() {
      this.$emit('close')
    },
    contrySelectChange(id, row) {
      this.formData.countryId = row.id
      this.formData.countryCode = row.code
      this.formData.countryName = row.name
    }
  }
}
</script>
