<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '编辑'"
    :close-on-click-modal="false"
    :visible.sync="visible"
  >
    <el-form
      :model="dataForm"
      :rules="dataRule"
      ref="dataForm"
      @keyup.enter.native="handleConfirm()"
      label-width="80px"
    >
      <el-form-item label="员工姓名" prop="realName">
        <el-input
          v-model="dataForm.realName"
          placeholder="真实姓名"
          clearable
          maxlength="20"
          show-word-limit
        ></el-input>
      </el-form-item>
      <el-form-item label="工号" prop="userNo">
        <el-input
          v-model="dataForm.userNo"
          placeholder="工号"
          clearable
          maxlength="20"
          show-word-limit
        ></el-input>
      </el-form-item>
      <el-form-item label="账号" prop="username">
        <el-input
          v-model="dataForm.username"
          placeholder="登录帐号"
          clearable
          maxlength="20"
          show-word-limit
        ></el-input>
      </el-form-item>
      <el-form-item label="手机号" prop="mobile">
        <el-input v-model="dataForm.mobile" placeholder="手机号" maxlength="11"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password" :class="{ 'is-required': !dataForm.id }">
        <el-input
          clearable
          maxlength="20"
          show-word-limit
          v-model="dataForm.password"
          type="password"
          placeholder="密码"
        ></el-input>
      </el-form-item>
      <el-form-item label="确认密码" prop="comfirmPassword" :class="{ 'is-required': !dataForm.id }">
        <el-input
          clearable
          maxlength="20"
          show-word-limit
          v-model="dataForm.comfirmPassword"
          type="password"
          placeholder="确认密码"
        ></el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="dataForm.email" placeholder="邮箱"></el-input>
      </el-form-item>
      <el-form-item label="状态" size="mini" prop="status">
        <el-radio-group v-model="dataForm.status">
          <el-radio :label="1">启用</el-radio>
          <el-radio :label="0">停用</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <el-form-item label="关联角色" size="mini" prop="roleIdList">
      <el-checkbox-group v-model="dataForm.roleIdList">
        <el-checkbox
          v-for="role in roleList"
          :key="role.roleId"
          :label="role.roleId"
        >{{ role.roleName }}</el-checkbox>
      </el-checkbox-group>
    </el-form-item>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="handleConfirm()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { isEmail, isMobile } from '@/utils/validate'
import { apiSysUserInfo, apiSysRoleSelect, apiSysUserConfirm } from '@/api/api_sys'

export default {
  data () {
    var validatePassword = (rule, value, callback) => {
      if (!this.dataForm.id && !/\S/.test(value)) {
        callback(new Error('密码不能为空'))
      } else {
        callback()
      }
    }
    var validateComfirmPassword = (rule, value, callback) => {
      if (!this.dataForm.id && !/\S/.test(value)) {
        callback(new Error('确认密码不能为空'))
      } else if (this.dataForm.password !== value) {
        callback(new Error('确认密码与密码输入不一致'))
      } else {
        callback()
      }
    }
    var validateEmail = (rule, value, callback) => {
      if (!isEmail(value)) {
        callback(new Error('邮箱格式错误'))
      } else {
        callback()
      }
    }
    var validateMobile = (rule, value, callback) => {
      if (!isMobile(value)) {
        callback(new Error('手机号格式错误'))
      } else {
        callback()
      }
    }
    let validateRole = (rule, value, callback) => {
      if (value.length < 1) {
        callback(new Error('至少选择一个角色。'))
      } else {
        callback()
      }
    }
    return {
      visible: false,
      roleList: [],
      dataForm: {
        id: 0,
        realName: '',
        username: '',
        userNo: '',
        password: '',
        comfirmPassword: '',
        salt: '',
        email: '',
        mobile: '',
        roleIdList: [],
        status: 1
      },
      dataRule: {
        realName: [{ required: true, message: '员工姓名不能为空', trigger: 'blur' }],
        userNo: [{ required: true, message: '工号不能为空', trigger: 'blur' }],
        username: [{ required: true, message: '账号不能为空', trigger: 'blur' }],
        password: [{ validator: validatePassword, trigger: 'blur' }],
        comfirmPassword: [{ validator: validateComfirmPassword, trigger: 'blur' }],
        email: [
          { validator: validateEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '手机号不能为空', trigger: 'blur' },
          { validator: validateMobile, trigger: 'blur' }
        ],
        roleIdList: [
          { required: true, message: '至少选择一个角色类型', trigger: 'blur' },
          { validator: validateRole, trigger: 'blur' }
        ]
      },
      apiType: '' // api类型
    }
  },
  methods: {
    init (id) {
      this.handleGetSysRoleSelect()
      if (id) {
        this.dataForm.id = id || 0
        this.handleEdit()
        this.apiType = '/update'
      } else {
        this.apiType = '/save'
      }
    },
    // 获取角色选择列表
    handleGetSysRoleSelect (id) {
      apiSysRoleSelect({}).then(res => {
        this.roleList = res && res.code === 0 ? res.list : []
        this.visible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
        })
      })
    },
    // 编辑
    handleEdit () {
      apiSysUserInfo({}, `/${this.dataForm.id}`).then(res => {
        if (res && res.code === 0) {
          this.$nextTick(() => {
            this.dataForm.username = res.user.username
            this.dataForm.realName = res.user.realName
            this.dataForm.userNo = res.user.userNo
            this.dataForm.salt = res.user.salt
            this.dataForm.email = res.user.email
            this.dataForm.mobile = res.user.mobile
            this.dataForm.roleIdList = res.user.roleIdList
            this.dataForm.status = res.user.status
          })
          this.visible = true
        }
      })
    },
    // 提交
    handleConfirm () {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          let params = {
            'userId': this.dataForm.id || undefined,
            'realName': this.dataForm.realName,
            'userNo': this.dataForm.userNo,
            'username': this.dataForm.username,
            'password': this.dataForm.password,
            'salt': this.dataForm.salt,
            'email': this.dataForm.email,
            'mobile': this.dataForm.mobile,
            'status': this.dataForm.status,
            'roleIdList': this.dataForm.roleIdList
          }
          apiSysUserConfirm(params, this.apiType).then(res => {
            if (res && res.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.visible = false
                  this.$emit('refreshDataList')
                }
              })
            } else {
              this.$message.error(res.msg)
            }
          })
        }
      })
    }
  }
}
</script>
