<template>
  <div class="app-container menus-edit">
    <el-form ref="userInfoFormRef" label-width="100px" :model="userInfo" :rules="rules">
      <!-- <el-form-item label="用户头像：">
        <el-input v-show="false" v-model="user.avatar" />
        <upload-image tip="建议尺寸：60 * 60px" />
      </el-form-item> -->
      <el-form-item label="登录名：" prop="loginAccount">
        <el-input v-model="userInfo.loginAccount" :placeholder="`通过登录名登录时请加上前缀，例如：${prefix}_test`">
          <template slot="prepend">{{ prefix }}_</template>
        </el-input>
      </el-form-item>
      <el-form-item v-if="!userInfo.id" label="密码：" prop="password">
        <el-input v-model="userInfo.password" placeholder="请输入密码" type="password" />
      </el-form-item>
      <el-form-item label="联系人：" prop="linkMan">
        <el-input v-model="userInfo.linkMan" placeholder="请输入联系人" />
      </el-form-item>
      <el-form-item label="手机号：" prop="mobile">
        <el-input
          v-model="userInfo.mobile"
          placeholder="请输入手机号"
          maxlength="11"
          show-word-limit
          @input="onMobileInput"
        />
      </el-form-item>
      <el-form-item label="状态：">
        <el-radio-group v-model="userInfo.status">
          <el-radio :label="1">启用</el-radio>
          <el-radio :label="0">停用</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="用户角色：" prop="roleList">
        <el-checkbox-group v-model="userInfo.roleList">
          <el-checkbox v-for="item in roleList" :key="item.id" :label="item.id">{{ item.roleName }}</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item>
        <!-- 确认 取消 -->
        <div class="control-box">
          <el-button type="warning" @click="navigateBack">返回</el-button>
          <el-button type="primary" @click="onSubmit">保存</el-button>
        </div>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { fetchRoleList, createUser, getUser, updateUser } from '@/api/system'
import { isMobile } from '@/utils/validate'
import { mapGetters } from 'vuex'
import { deepClone } from '@/utils'

export default {
  data() {
    // 校验角色
    const validateRoleList = (rule, value, callback) => {
      if (value instanceof Array) {
        if (value.length === 0) {
          callback(new Error('请至少选择一个角色'))
        } else {
          callback()
        }
      } else {
        callback(new Error('角色列表为一个数组'))
      }
    }
    // 校验手机号
    const validateMobile = (rule, value, callback) => {
      if (isMobile(value)) {
        callback()
      } else {
        callback(new Error('请输入合法的手机号'))
      }
    }
    return {
      editType: 'add',
      userInfo: {
        id: 0,
        loginAccount: '',
        password: '',
        linkMan: '',
        mobile: '',
        status: 1,
        roleList: [],
        roleIds: ''
      },
      roleList: [],
      rules: {
        loginAccount: [
          { required: true, message: '登录名不能为空', trigger: 'blur' },
          { min: 2, max: 15, message: '长度在 2 到 15 个字符', trigger: 'blur' }
        ],
        linkMan: [{ required: true, message: '联系人不能为空', trigger: 'blur' }],
        mobile: [
          { required: true, message: '手机号不能为空', trigger: 'blur' },
          { validator: validateMobile, trigger: 'blur' }
        ],
        password: [{ required: true, message: '密码不能为空', trigger: 'blur' }],
        roleList: [{ required: true, validator: validateRoleList, trigger: 'change' }]
      }
    }
  },
  computed: {
    ...mapGetters(['prefix'])
  },
  created() {
    this.editType = this.$route.query.type
    this.fetchRoleList()
    if (this.editType === 'edit') {
      this.userInfo.id = this.$route.query.id
      this.fetchUserInfo()
    }
  },
  methods: {
    // 获取角色列表
    fetchRoleList() {
      fetchRoleList().then((res) => {
        this.roleList = [...this.roleList, ...res.data.list]
      })
    },
    // 修改保存用户信息
    updateUserInfo() {
      const userInfo = deepClone(this.userInfo)
      userInfo.roleIds = userInfo.roleList.join(',')
      userInfo.loginAccount = `${this.prefix}_${userInfo.loginAccount}`
      updateUser(userInfo.id, userInfo).then((res) => {
        this.$message.success('修改用户成功')
        this.$store.dispatch('tagsView/delView', this.$route)
        this.$router.back()
      })
    },
    // 保存用户信息
    createUserInfo() {
      const userInfo = deepClone(this.userInfo)
      userInfo.roleIds = userInfo.roleList.join(',')
      userInfo.loginAccount = `${this.prefix}_${userInfo.loginAccount}`
      createUser(userInfo).then((res) => {
        this.$message.success('添加用户成功')
        this.$store.dispatch('tagsView/delView', this.$route)
        this.$router.back()
      })
    },
    // 提交表单
    onSubmit() {
      this.$refs.userInfoFormRef.validate((valide) => {
        if (!valide) return
        if (this.editType === 'add') {
          this.createUserInfo()
        } else {
          this.updateUserInfo()
        }
      })
    },
    // 获取用户信息
    fetchUserInfo() {
      getUser(this.userInfo.id).then((res) => {
        this.setUserInfo(res.data)
      })
    },
    // 设置用户信息
    setUserInfo(data) {
      for (const key in data) {
        if (Object.hasOwnProperty.call(this.userInfo, key)) {
          this.userInfo[key] = data[key]
        }
      }
      const prefix = this.prefix + '_'
      const prefixLen = prefix.length
      if (this.userInfo.loginAccount.startsWith(prefix)) {
        this.userInfo.loginAccount = this.userInfo.loginAccount.substring(prefixLen)
      }
      this.userInfo.roleList = data.roleIds.split(',').map((item) => parseInt(item))
    },

    // 输入手机号时
    onMobileInput() {
      this.userInfo.mobile = this.userInfo.mobile.replace(/[^\w\.\/]/gi, '')
    }
  }
}
</script>

<style scoped lang="scss">
.menus-edit {
  width: 600px;
  margin: 0 auto;
  margin-top: 100px;

  ::v-deep {
    .el-input-group__prepend {
      background: transparent;
      padding: 0 10px 0 15px;
    }
  }
}
</style>
