<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="username">
        <el-input v-model="userInfo.username" placeholder="登录名" />
      </el-form-item>
      <el-form-item v-if="!userInfo.id" label="密码：" prop="password">
        <el-input v-model="userInfo.password" placeholder="密码" />
      </el-form-item>
      <el-form-item label="联系人：">
        <el-input v-model="userInfo.linkMan" placeholder="联系人" />
      </el-form-item>
      <el-form-item label="手机号：" prop="mobile">
        <el-input v-model="userInfo.mobile" placeholder="手机号" />
      </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'

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 (value && isMobile(value)) {
        callback()
      } else {
        callback(new Error('请输入合法的手机号'))
      }
    }
    return {
      editType: 'add',
      userInfo: {
        id: 0,
        username: '',
        password: '',
        linkMan: '',
        mobile: '',
        status: 1,
        roleList: [],
        roleIds: ''
      },
      roleList: [],
      rules: {
        username: [
          { required: true, message: '请输入登录名', trigger: 'blur' },
          { min: 2, max: 15, message: '长度在 2 到 15 个字符', trigger: 'blur' }
        ],
        mobile: [{ validator: validateMobile, trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
        roleList: [{ required: true, validator: validateRoleList, trigger: 'change' }]
      }
    }
  },
  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() {
      this.userInfo.roleIds = this.userInfo.roleList.join(',')
      updateUser(this.userInfo.id, this.userInfo).then(res => {
        this.$message.success('修改用户成功')
        this.$store.dispatch('tagsView/delView', this.$route)
        this.$router.back()
      })
    },
    // 保存用户信息
    createUserInfo() {
      this.userInfo.roleIds = this.userInfo.roleList.join(',')
      createUser(this.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) {
      console.log(data)
      for (const key in this.userInfo) {
        if (Object.hasOwnProperty.call(data, key)) {
          this.userInfo[key] = data[key]
        }
      }
      this.userInfo.roleList = data.roleIds.split(',').map(item => parseInt(item))
    }
  }
}
</script>

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