<template>
  <div v-clickoutside="{obj: editUser, func: esc}" class="right-box right-box-asset">
    <div class="right-box__header">
      <div class="header__title">{{editUser.id ? $t('config.user.editUser') : $t('config.user.createUser')}}</div>
      <div class="header__operation">
        <span v-cancel="{obj: editUser, func: esc}"><i class="nz-icon nz-icon-close"></i></span>
      </div>
    </div>
    <div class="right-box__container">
      <div class="container__form">
        <el-form ref="userForm" :model="editUser" :rules="editUser.id ? rules2 : rules" class="right-box-form right-box-form-left" label-position="top" label-width="120px">
          <!--name-->
          <el-form-item :label="$t('config.user.name')" prop="name">
            <el-input id="account-input-name" v-model="editUser.name" :disabled="editUser.username==='admin' && editUser.id==1"
                      maxlength="64" placeholder="" show-word-limit size="small" type="text"></el-input>
          </el-form-item>
          <!--username-->
          <el-form-item :label="$t('config.user.username')" prop="username">
            <el-input id="account-input-username" v-model="editUser.username" :disabled="editUser.username==='admin' && editUser.id==1"
                      maxlength="64" placeholder="" show-word-limit size="small" type="text"></el-input>
          </el-form-item>
          <!--password-->
          <el-form-item :label="$t('config.user.password')" prop="pin">
            <el-input id="account-input-password" v-model="editUser.pin"  maxlength="16" placeholder=""
                      show-word-limit size="small" type="password" @blur="passwordBlur"></el-input>
          </el-form-item>
          <!--passwordChange-->
          <el-form-item :label="$t('config.user.confirmPwd')" label-width="200px" prop="pinChange">
            <el-input id="account-input-passwordChange" v-model="editUser.pinChange"  maxlength="16" placeholder=""
                      show-word-limit size="small" type="password"></el-input>
          </el-form-item>
          <!--email-->
          <el-form-item label="E-mail" prop="email">
            <el-input id="account-input-email" v-model="editUser.email" placeholder="" size="small" type="text"></el-input>
          </el-form-item>
          <!--mobile-->
          <el-form-item :label="$t('config.user.mobile')" prop="mobile">
            <el-input id="account-input-mobile" v-model.number="editUser.mobile" placeholder="" size="small" type="text"></el-input>
          </el-form-item>
          <!--enable-->
          <el-form-item :label="$t('config.user.enable')">
            <el-switch id="account-input-status" v-model="editUser.status" :disabled="isCurrentUser(editUser.username) || (editUser.username==='admin' && editUser.id==1) " active-color="#ee9d3f" active-value="1"
                       inactive-value="0">
            </el-switch>
          </el-form-item>
          <!--roles-->
          <el-form-item :label="$t('config.user.roles')" prop="roleIds">
            <el-select id="account-input-roleIds" v-model="editUser.roleIds" :disabled="(editUser.username==='admin') && editUser.id==1" multiple clearable collapse-tags placeholder="" popper-class="right-box-select-dropdown prevent-clickoutside" size="small" @change="()=>{this.$forceUpdate()}">
              <template v-for="role in roles">
                <el-option :key="role.id" :label="role.i18n?$t(role.i18n):role.name" :value="role.id"></el-option>
              </template>
            </el-select>
          </el-form-item>
          <el-form-item v-if="editUser.id" :label="$t('config.user.createTime')">
            <div class="right-box-form-content-txt">{{editUser.createAt}}</div>
          </el-form-item>

        </el-form>
      </div>
    </div>
    <div class="right-box__footer">
      <button id="asset-edit-cancel" v-cancel="{obj: editUser, func: esc}" class="footer__btn footer__btn--light">
        <span>{{$t('overall.cancel')}}</span>
      </button>
      <button id="asset-edit-save" :class="{'footer__btn--disabled': prevent_opt.save}" :disabled="prevent_opt.save" class="footer__btn" @click="save">
        <span>{{$t('overall.save')}}</span>
      </button>
    </div>
  </div>
</template>

<script>
import { host, port } from '@/components/common/js/validate'
export default {
  name: 'userBox',
  components: {
  },
  props: {
    obj: {
      type: Object
    }
  },
  computed: {
    isCurrentUser () {
      return function (username) {
        return localStorage.getItem('nz-username') == username
      }
    }
  },
  data () {
    const vm = this
    const validatePassword = (rule, value, callback) => { // 确认密码的二次校验
      if (value === '' && this.editUser.pin) {
        callback(new Error(this.$t('config.user.inputConfirmPwd')))
      } else if (value !== this.editUser.pin) {
        callback(new Error(this.$t('config.user.confirmPwdErr')))
      } else {
        callback()
      }
    }
    return {
      editUser: {},
      url: 'sys/user',
      rightBox: { model: { show: false } },
      rules: { // 表单校验规则
        name: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        username: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        pin: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        pinChange: [
          { validator: validatePassword, trigger: 'blur' },
          { required: true, message: '', trigger: 'blur' }
        ],
        roleIds: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        email: [
          { type: 'email', message: this.$t('validate.email') }
        ]
      },
      rules2: { // 表单校验规则
        username: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        pinChange: [
          { validator: validatePassword, trigger: 'blur' }
        ],
        roleIds: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        email: [
          { type: 'email', message: this.$t('validate.email') }
        ]
      },
      roles: []
    }
  },
  watch: {
    obj: {
      deep: true,
      immediate: true,
      handler (n) {
        this.editUser = JSON.parse(JSON.stringify(n))
        if (this.editUser.roles && this.editUser.roles.length > 0) {
          this.editUser.roleIds = this.editUser.roles.map(t => t.id)
        }
      }
    }
  },
  mounted () {
    this.getRoles()
  },
  methods: {
    clickOutside () {
      this.esc(false)
    },
    /* 关闭弹框 */
    esc (refresh) {
      this.prevent_opt.save = false
      this.$emit('close', refresh)
    },
    /* 密码失去焦点 检验确认密码 */
    passwordBlur () {
      if (this.editUser.pin && this.editUser.pinChange) {
        this.$refs.accountForm.validateField('passwordChange')
      }
    },
    getRoles () {
      this.roles = []
      this.$get('sys/role?pageSize=-1').then(response => {
        if (response.code === 200) {
          this.roles = response.data.list
        } else {
          this.$message.error('load roles faild')
        }
      })
    },
    save () {
      if (this.prevent_opt.save) { return } ;
      this.prevent_opt.save = true

      this.$refs.userForm.validate((valid) => {
        if (valid) {
          if (this.editUser.id) {
            this.$put(this.url, this.editUser).then(res => {
              this.prevent_opt.save = false
              if (res.code === 200) {
                this.$message({ duration: 2000, type: 'success', message: this.$t('tip.saveSuccess') })
                this.esc(true)
              } else {
                this.$message.error(res.msg)
              }
            })
          } else {
            this.$post(this.url, this.editUser).then(res => {
              this.prevent_opt.save = false
              if (res.code === 200) {
                this.$message({ duration: 2000, type: 'success', message: this.$t('tip.saveSuccess') })
                this.esc(true)
              } else {
                this.$message.error(res.msg)
              }
            })
          }
        } else {
          this.prevent_opt.save = false
          return false
        }
      })
    }
  }
}
</script>
<style lang="scss">
  @import '@/assets/css/common/rightBoxCommon.scss';
</style>
