<template>
  <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" append-to-body>
    <el-form ref="dataForm" :rules="rules" :model="userForm" label-position="right" label-width="80px">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="账号" prop="account">
            <el-input v-model.trim="userForm.account" :disabled="ifdisabled" type="text" placeholder="必填"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="姓名" prop="name">
            <el-input v-model.trim="userForm.name" type="text" placeholder="必填"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="性别" prop="sex">
            <el-select v-model="userForm.sex" placeholder="请选择">
              <el-option
                v-for="item in sexList"
                :key="item.value"
                :label="item.label"
                :value="item.value"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="出生日期" prop="birthday">
            <el-date-picker
              v-model="userForm.birthday"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="选择日期"
              style="width:100%"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-show="dialogStatus=='create'" :gutter="20">
        <el-col :span="12">
          <el-form-item label="密码" prop="password">
            <el-input v-model.trim="userForm.password" type="password" placeholder="必填"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="重复密码" prop="repassword">
            <el-input v-model.trim="userForm.repassword" type="password" placeholder="必填"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item v-if="!ifdisabled" label="角色" prop="roleid">
            <select-tree v-model="userForm.roleid" :options="roleTreeList" :props="roleProps"/>
          </el-form-item>
          <el-form-item v-else label="角色">
            <el-input v-model="roleName" :disabled="ifdisabled" type="text" placeholder="无"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="组织机构" prop="deptid">
            <dept-select v-model="userForm.deptid" dept-show="deptShow" placeholder="请选择组织机构" />
            <!--<select-tree v-model="userForm.deptid" :options="deptTreeList" :props="deptProps" />-->
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="邮箱" prop="email">
            <el-input v-model.trim="userForm.email" type="text" placeholder="必填"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="电话" prop="phone">
            <el-input v-model.trim="userForm.phone" type="text" placeholder="必填"/>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="saveData">保存</el-button>
      <el-button @click="cancel">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { toTreeList } from '@/utils/structure'
import SelectTree from '@/components/SelectTree/singleSelect'
import DeptSelect from '@/components/DeptSelect'
// import { getDeptTreeList } from '@/api/dept'
import { getRoleTreeList } from '@/api/role'
import { addUser, updateUser } from '@/api/user'
import { RSAencrypt } from '../../../utils/security'

export default {
  name: 'EditUser',
  components: { SelectTree, DeptSelect },
  data() {
    const validatePass = (rule, value, callback) => {
      console.log('验证密码')
      if (value === '') {
        callback(new Error('密码不能为空'))
      } else {
        if (this.userForm.repassword !== '') {
          this.$refs.dataForm.validateField('repassword')
        }
        callback()
      }
    }
    const validatePass2 = (rule, value, callback) => {
      console.log('验证重复密码')
      if (value === '') {
        callback(new Error('重复密码不能为空'))
      } else if (value !== this.userForm.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      dialogFormVisible: false, // 对话框是否显示
      dialogStatus: '', // 对话框类型：create,update
      userForm: {
        id: '', // 编号
        account: '', // 账号
        name: '', // 姓名
        email: '', // 邮箱，
        phone: '', // 手机号，
        deptid: '', // 组织机构编号
        roleid: '', // 角色
        password: '', // 密码
        repassword: '', // 重复密码
        birthday: ''
      }, // 表单
      deptProps: {
        parent: 'pid',
        value: 'id',
        label: 'name',
        children: 'children'
      },
      roleProps: {
        parent: 'pid',
        value: 'id',
        label: 'name',
        children: 'children'
      },
      deptTreeList: null, // 组织树列表数据
      roleTreeList: null, // 角色树列表数据
      sexList: [
        {
          label: '男',
          value: '0'
        },
        {
          label: '女',
          value: '1'
        }
      ],
      textMap: {
        update: '编辑',
        create: '新增'
      }, // 表头显示标题
      ifdisabled: true, // 是否可修改
      rules: {
        account: [{ required: true, message: '账户不能为空', trigger: ['blur', 'change'] }],
        name: [{ required: true, message: '姓名不能为空', trigger: ['blur', 'change'] }],
        password: [{ required: true, validator: validatePass, trigger: ['blur', 'change'] }],
        repassword: [{ required: true, validator: validatePass2, trigger: ['blur', 'change'] }],
        deptid: [{ required: true, message: '组织机构必选', trigger: ['blur', 'change'] }],
        roleid: [{ required: true, message: '角色必选', trigger: ['blur', 'change'] }],
        email: [{
          required: false, // 是否必填
          message: '请输入邮箱地址', // 错误提示信息
          trigger: 'blur'// 检验方式（blur为鼠标点击其他地方，）
        },
        {
          type: 'email', // 要检验的类型（number，email，date等）
          message: '请输入正确的邮箱地址',
          trigger: ['blur', 'change'] }],
        phone: [{
          required: false,
          pattern: /^1[34578]\d{9}$/, // 可以写正则表达式呦呦呦
          message: '请输入正确的手机号',
          trigger: ['blur', 'change'] }]
      }, // 前端校验规则
      roleName: '',
      deptShow: true
    }
  },
  computed: {
    userTree: function() {
      const tree = toTreeList(this.userTreeList)
      console.log(tree)
      return tree
    }
  },
  mounted: function() {
    this.fetchRoleTree()
  },
  methods: {
    // 初始化对话框
    initDialog: function(dialogStatus, dialogFormVisible, row = null) {
      this.dialogStatus = dialogStatus
      this.dialogFormVisible = dialogFormVisible
      this.fetchRoleTree()
      if (dialogStatus === 'create') { // 如果是新增，清除验证
        this.ifdisabled = false
        this.resetForm()
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      } else if (dialogStatus === 'update') { // 如果是修改，将row中数据填写到输入框中
        this.ifdisabled = true
        this.userForm = {
          id: row.id, // 编号
          account: row.account, // 账号
          name: row.name, // 姓名
          email: row.email, // 邮箱，
          phone: row.phone, // 手机号，
          deptid: row.deptid, // 组织机构编号
          roleid: row.roleid, // 角色
          birthday: row.birthday, // 生日
          sex: row.sex // 性别
        }
        this.roleName = row.roleName
        delete this.userForm['password']
        delete this.userForm['repassword']
      }
    },
    // 加载角色树形下拉菜单
    fetchRoleTree: function() {
      getRoleTreeList(this.listQuery).then(response => {
        console.log('fetchRoleTree:')
        console.log(response.data)
        if (response.data.list) {
          this.roleTreeList = toTreeList(response.data.list, '0', true)
          console.log(this.roleTreeList)
        }
      })
    },
    // 重置表单
    resetForm() {
      this.userForm = {
        id: '', // 编号
        account: '', // 账号
        name: '', // 姓名
        email: '', // 邮箱，
        phone: '', // 手机号，
        deptid: '', // 组织机构编号
        roleid: '', // 角色
        password: '', // 密码
        repassword: '' // 重复密码
      }
    },
    // 保存数据
    saveData: function() {
      if (this.dialogStatus === 'update') {
        this.updateData()
      } else if (this.dialogStatus === 'create') {
        this.createData()
      }
    },
    // 新增数据
    createData: function() {
      this.$refs['dataForm'].validate((valid) => {
        console.log(this.userForm)
        const userForm = JSON.parse(JSON.stringify(this.userForm))
        userForm.password = RSAencrypt(userForm.password)
        if (valid) {
          addUser(userForm).then(response => {
            if (response.code === 200) {
              this.$confirm('新增成功，是否继续新增?', '提示', {
                confirmButtonText: '是',
                cancelButtonText: '否',
                type: 'info'
              }).then(() => {
                this.resetForm()
                this.$nextTick(() => {
                  this.$refs['dataForm'].clearValidate()
                })
              }).catch(() => {
                this.$emit('watchChild')
                this.dialogFormVisible = false
              })
            }
          })
        }
      })
    },
    // 修改数据
    updateData: function() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          updateUser(this.userForm).then(response => {
            if (response.code === 200) {
              this.$message.success('修改成功')
              this.$emit('watchChild')
              this.dialogFormVisible = false
            }
          })
        }
      })
    },
    cancel: function() {
      this.dialogFormVisible = false
      this.$emit('watchChild')
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>

  .el-dialog{
    width:700px
  }
  .el-select{
    width: 100%;
  }
</style>
