<!--
  @description: 系统设置->用户管理-新增/编辑用户
  @author: 肖文龙
  @routerPath:
  @date:  2020/09/11
-->
<template>
  <div>
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      custom-class="el-dialog__body-p0"
      width="800px"
    >
      <div class="main mb10">
        <el-form ref="dataForm" :rules="rules" :model="fromData" :inline-message="true">
          <div class="page-title">
            基本信息
          </div>
          <table class="from_table">
            <!-- 所属机构 -->
            <tr>
              <td> <el-form-item label="所属机构" prop="departname" /></td>
              <td colspan="3">
                <el-input
                  ref="departname"
                  v-model="fromData.departname"
                  placeholder="请选择"
                  style="width: calc(100% - 164px)"
                  disabled
                />
                <el-button type="primary" class="ml10 choose" @click="organSelect">
                  选择
                </el-button>
                <el-button type="primary" @click="organTree('clear')">
                  清空
                </el-button>
              </td>
            </tr>
            <tr>
              <!-- 真实姓名 -->
              <td><el-form-item label="真实姓名" prop="realName" /></td>
              <td><el-input v-model="fromData.realName" maxlength="10" minlength="6" /></td>
              <!-- 手机号码 -->
              <td><el-form-item label="手机号码" prop="mobilePhone" /></td>
              <td><el-input v-model="fromData.mobilePhone" /></td>
            </tr>
            <tr>
              <!-- 身份证号 -->
              <td><el-form-item label="身份证号" prop="idCard" /></td>
              <td><el-input v-model="fromData.idCard" /></td>
              <!-- 常用邮箱 -->
              <td><el-form-item label="常用邮箱" prop="email" /></td>
              <td><el-input v-model="fromData.email" /></td>
            </tr>
          </table>
          <div class="page-title">
            账号信息
          </div>
          <table class="from_table">
            <tr>
              <!-- 用户名 -->
              <td> <el-form-item label="用户名" prop="userName" /></td>
              <td>
                <el-input v-if="!addUser" v-model="fromData.userName" maxlength="500" />
                <span v-if="addUser">{{ fromData.userName }}</span>
              </td>
              <!-- 用户状态 -->
              <td><el-form-item label="用户状态" prop="status" /></td>
              <td>
                <span v-if="fromData.status===1">激活</span>
                <span v-if="fromData.status===0">冻结</span>
              </td>
            </tr>
            <tr v-if="!addUser">
              <!-- 密码 -->
              <td> <el-form-item label="密码" prop="password" /></td>
              <td><gx-input v-model="fromData.password" type="password" gx-placeholder="passWord" /></td>
              <!-- 确认新密码 -->
              <td><el-form-item label="确认新密码" prop="rePassword" /></td>
              <td><gx-input v-model="fromData.rePassword" type="password" gx-placeholder="repeatPassword" /></td>
            </tr>
          </table>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="loading" type="primary" @click="saveData">
          确定
        </el-button>
        <el-button :loading="loading" @click="dialogVisible = false">
          取消
        </el-button>
      </div>
    </el-dialog>
    <!-- 所属机构弹框 -->
    <organTree-dialog ref="organTree" @call-back="organTree" />
  </div>
</template>

<script>
/* api */
import { findUserByUserId } from '@/api/common/user.js'
import { addUser, updateUserNew } from '@/api/common/user'
/* 公用方法 */
import { userName, makeSureId, passWord, characters1_auto, validateInput, phone, email } from '@/assets/js/validate'
import { restoreInitialValue } from '@/assets/js/utils'// 常用方法
/* 组件 */
import organTreeDialog from '@/views/common/user/organizationTree/organTree-dialog.vue'// 新增用户-编辑用户

export default {
  components: {
    'organTree-dialog': organTreeDialog
  },
  data() {
    return {
      loading: false,
      title: '', // 标题 新增用户 编辑用户
      addUser: true, // 是否为编辑   true 编辑 false 新增
      dialogVisible: false, // 弹框状态
      // 用户信息
      fromData: {
        id: '',
        realName: '', // 真实姓名
        userName: '', // 用户名
        email: '', // 邮箱
        password: '', // 密码
        mobilePhone: '', // 手机号码
        departname: '', // 所属机构
        departid: '', // 所属机构id
        fixedPhone: '', // 办公电话
        rePassword: '', // 重复密码
        status: 1, // 用户状态 1激活 0冻结
        initDepartId: '' // 编辑时传的当前选择的用户机构id
      },
      rules: {
        userName: [], // 用户名
        departname: [{ required: true, message: '所属机构不能为空', trigger: 'blur' }], // 所属机构
        idCard: [{ required: true, validator: makeSureId, trigger: 'blur' }], // 身份证号
        realName: [{ required: true, validator: characters1_auto, trigger: 'blur' }, { validator: validateInput }], // 真实姓名
        email: [{ validator: email, trigger: 'blur' }], // 邮箱
        mobilePhone: [{ required: true, validator: phone, trigger: 'blur' }], // 手机号码
        password: [{ required: true, validator: passWord, trigger: 'blur' }], // 密码
        rePassword: [{ required: true, validator: this.rePwd, trigger: 'blur' }], // 确认新密码
        status: [{ required: true, message: '请选择', trigger: 'change' }] // 用户状态
      }
    }
  },
  watch: {
    dialogVisible(val) {
      if (!val) {
        // 初始化
        restoreInitialValue(this.fromData)
        this.fromData.status = 1// 用户状态 1激活 0冻结
      }
    }
  },
  methods: {
    // 打开弹框
    open(row) {
      this.dialogVisible = true
      // 判断是否有用户id
      if (row) {
        this.title = '编辑用户'
        this.addUser = true
      } else {
        this.title = '新增用户'
        this.addUser = false
        // 用户名校验方式
        this.rules.userName = [
          { required: true, validator: userName, trigger: 'blur' }, // 格式校验
          { required: true, validator: this.userNameApi, trigger: 'blur' }// 重复校验
        ]
      }
      this.loadData(row)
    },
    // 获取数据
    loadData(row) {
      if (!row) return
      findUserByUserId({ id: row.userId }).then(res => {
        const data = {
          ...res.data,
          departid: row.departId, // 机构id
          departname: row.departName, // 机构名称
          initDepartId: row.departId // 编辑时传的当前选择的用户机构id
        }
        this.fromData = data
      })
    },
    // 选择机构
    organSelect() {
      this.$refs.organTree.open({
        title: '选择机构', // 弹框标题
        dialog: true, // 弹窗状态
        selectCodes: this.fromData.departid && this.fromData.departid.split(',')// 当前选中的供货范围Code
      })
    },
    // 选择/清空机构
    organTree(data) {
      // 清空
      if (data === 'clear') {
        this.fromData.departname = ''
        this.fromData.departid = ''
      } else {
        // 选择
        this.fromData.departname = data.labels
        this.fromData.departid = data.keys
      }
    },
    // 确定
    saveData() {
      // 点击编辑的确定按钮
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          const data = {
            ...this.fromData
          }
          // 新增角色
          if (!this.addUser) {
            data.password = this.$Base64.encode(data.password)// 加密
            data.rePassword = this.$Base64.encode(data.rePassword)// 加密
          }
          this.loading = true
          if (this.addUser) {
            // 编辑
            updateUserNew(data).then(() => {
              this.dialogVisible = false
              this.$message({
                message: '更新成功',
                type: 'success'
              })
              this.$emit('call-back')
              this.loading = false
            })
          } else {
            // 新增
            addUser(data).then(() => {
              this.dialogVisible = false
              this.$message({
                message: '添加成功',
                type: 'success'
              })
              this.$emit('call-back')
              this.loading = false
            })
          }
        }
      })
    },
    // 确认新密码
    rePwd(rule, value, callback) {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.fromData.password) {
        callback(new Error('两次输入密码不一致'))
      } else {
        callback()
      }
    }
  }
}
</script>
<style lang="less" scoped>
</style>
