<template>
  <div class="addeditUserDialog">
    <el-dialog 
      class="addParts"
      :visible.sync="dialogFormVisible" 
      :before-close="cancelRegister" 
      :top="top"
      :title="userTitle"
      width="570px">

      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" :inline="true">
        <el-form-item label="登录名称" prop="loginName">
          <el-input v-model="ruleForm.loginName"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="userPassword" v-if="!rowEditOnoff">
          <el-input type="password" v-model="ruleForm.userPassword" placeholder="至少含大小写字母、数字和特殊字符中的三种"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="rePassword" v-if="!rowEditOnoff">
          <el-input type="password" v-model="ruleForm.rePassword" placeholder="至少含大小写字母、数字和特殊字符中的三种"></el-input>
        </el-form-item>
        <el-form-item label="用户名称" prop="userName">
          <el-input v-model="ruleForm.userName"></el-input>
        </el-form-item>
        <el-form-item label="地址">
          <el-input v-model="ruleForm.address"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="ruleForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="ruleForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio class="status" v-model="ruleForm.status" label="enable">启用</el-radio>
          <el-radio class="status" v-model="ruleForm.status" label="disable">禁用</el-radio>
        </el-form-item>
        <el-form-item label="性别">
          <el-radio class="sex" v-model="ruleForm.userSex" label="男">男</el-radio>
          <el-radio class="sex" v-model="ruleForm.userSex" label="女">女</el-radio>
        </el-form-item>
        <el-form-item label="所属机构">
          <el-cascader
            :options="ruleForm.options"
            :props="defaultProps"
            v-model="ruleForm.selectedOptions"
            change-on-select
            @change="handleChange">
          </el-cascader>
        </el-form-item>
        <!-- <el-form-item label="用户类型">
          <el-select v-model="ruleForm.type" placeholder="请选择用户类型">
            <el-option label="超级管理员" value="0"></el-option>
            <el-option label="普通管理员" value="1"></el-option>
            <el-option label="普通用户" value="2"></el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="重置密码" v-if="rowEditOnoff" prop="resetPassword">
          <el-input type="password" v-model="ruleForm.resetPassword" placeholder="至少含大小写字母、数字和特殊字符中的三种">
            <el-button slot="append" @click="handleChangePassword">一键重置</el-button>
          </el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelRegister">取 消</el-button>
        <el-button type="primary" @click="dialogSure('ruleForm')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import Api from '@/api/index.js'

  export default { 
    name: 'AddeditUserDialog',

    props: { 
      dialogFormVisible: { 
        type: Boolean,
        default: false
      },
      rowEditOnoff: { 
        type: Boolean,
        default: false
      },
      formId: '',
      top: { 
        type: String,
        default: '4%'
      },
      userTitle: {
        type: String,
        default: '添加用户'
      }
    },
    data () {
      return {
        ruleForm: {
          loginName: '',
          userPassword: '',
          rePassword: '',
          userName: '',
          address: '',
          email: '',
          phone: '',
          status: 'enable',
          userSex: '男',
          // type: '2',
          options: [],
          selectedOptions: ['1001'],
          organguid: '1001',
          resetPassword: ''
        },
        rules: {
          loginName: [
            {required: true, message: '请输入登录名称', trigger: 'blur'},
            {validator: (rule, value, callback) => {
                if (value.length > 15 || value.length < 3) {
                  callback(new Error('长度必须为3~15个字符'))
                } else {
                  var reg = new RegExp("[`~!@#$^&*()=|{}':;',\\[\\].<>《》/?~！@#￥……&*（）——|{}【】‘；：”“'。，、？]")
                  if (reg.test(value)) {
                    callback(new Error('不能含有特殊字符'))
                  } else {
                    callback()
                  }
                }
              },
              trigger: 'change'
            }
          ],
          userPassword: [
            {required: true, message: '请输入密码', trigger: 'blur'},
            {validator: (rule, value, callback) => {
                var testLen = /[A-Za-z\d~!@#$%^&*()<>?_+{}|]{8,}/g.test(value)
                var test = /(?![A-Za-z]+$)(?![A-Z\d]+$)(?![A-Z~!@#$%^&*()<>?_+{}|]+$)(?![a-z\d]+$)(?![a-z~!@#$%^&*()<>?_+{}|]+$)(?![\d~!@#$%^&*()<>?_+{}|]+$)[A-Za-z\d~!@#$%^&*()<>?_+{}|]/g.test(value)
                if (!testLen) {
                  callback(new Error('密码最小长度为8个字符'))
                } else if (!test) {
                  callback(new Error('至少含有大小写字母、数字和特殊字符中的三种'))
                } else {
                  callback()
                }
              },
              trigger: 'change'
            }
          ],
          rePassword: [
            {required: true, message: '请确认密码', trigger: 'blur'},
            {validator: (rule, value, callback) => {
                if (this.ruleForm.userPassword !== value) {
                  callback(new Error('输入的密码不一致，请重新确认'))
                } else {
                  callback()
                }
              },
              trigger: 'blur'
            }
          ],
          resetPassword: [
            {validator: (rule, value, callback) => {
                var testLen = /[A-Za-z\d~!@#$%^&*()<>?_+{}|]{8,}/g.test(value)
                var test = /(?![A-Za-z]+$)(?![A-Z\d]+$)(?![A-Z~!@#$%^&*()<>?_+{}|]+$)(?![a-z\d]+$)(?![a-z~!@#$%^&*()<>?_+{}|]+$)(?![\d~!@#$%^&*()<>?_+{}|]+$)[A-Za-z\d~!@#$%^&*()<>?_+{}|]/g.test(value)
                if (value !== '') {
                  if (!testLen) {
                    callback(new Error('密码最小长度为8个字符'))
                  } else if (!test) {
                    callback(new Error('至少含有大小写字母、数字和特殊字符中的三种'))
                  } else {
                    callback()
                  }
                } else {
                  callback()
                }
              },
              trigger: 'change'
            }
          ],
          userName: [
            {required: true, message: '请输入用户名称', trigger: 'blur'},
            {validator: (rule, value, callback) => {
                if (value.length > 8 || value.length < 2) {
                  callback(new Error('长度必须为2~8个字符'))
                } else {
                  var reg = new RegExp("[`~!@#$^&*()=|{}':;',\\[\\].<>《》/?~！@#￥……&*（）——|{}【】‘；：”“'。，、？]")
                  if (reg.test(value)) {
                    callback(new Error('不能含有特殊字符'))
                  } else {
                    callback()
                  }
                }
              },
              trigger: 'change'
            }
          ],
          phone: [
            {required: true, message: '请输入手机号码', trigger: 'blur'},
            {validator: (rule, value, callback) => {
                let mobile = /^1[34578][0-9]{9}$/
                if (mobile.test(value)) {
                  callback()
                } else {
                  callback(new Error('请输入合理的手机号'))
                }
              },
              trigger: 'change'
            }
          ],
          email: [
            {required: true, message: '请输入邮箱地址', trigger: 'blur'},
            {type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur'}
          ]
        },
        defaultProps: {
          children: 'childOrganinfoinfos',
          label: 'organname',
          value: 'organguid'
        },
        treeData: []
      }
    },
    mounted () {
      this.initData()
      this.getOrganTree()
    },
    methods: { 
      // 初始化数据
      initData () { 
        // 判断是添加用户还是修改用户
        if (this.rowEditOnoff) { // 修改         
          this.showUserData() 
        } else { // 添加用户
          this.ruleForm.loginName = ''
          this.ruleForm.userPassword = ''
          this.ruleForm.rePassword = ''
          this.ruleForm.userName = ''
          this.ruleForm.address = ''
          this.ruleForm.email = ''
          this.ruleForm.phone = ''
          this.ruleForm.status = 'enable'
          this.ruleForm.userSex = '男'
          this.ruleForm.organguname = '研发部'
          this.ruleForm.type = '2'
        }
      },  
      // 获取机构树
      getOrganTree () {
        Api.getOrganTree()
          .then(data => {
            let datas = data.data
            if (data.status === 0) {
              this.ruleForm.options = this.getChilds(datas)
            } else {
              this.$message({
                type: 'warning',
                message: '请求数据失败'
              })
            }
          }).catch(res => { 
            console.log('error:', res)
          })
      },
      // 选择机构树
      handleChange (value) {
        this.ruleForm.organguid = value[value.length - 1]
      },
      // 一键重置密码
      handleChangePassword () {
        this.ruleForm.resetPassword = 'gd!123456'
      },
      // 展示数据
      showUserData () {
        Api.showUserData(this.formId)
        .then(data => {
          let datas = data.data
          if (data.status === 0) {
            this.ruleForm.loginName = datas.loginname
            this.ruleForm.userName = datas.username
            this.ruleForm.address = datas.address || ''
            this.ruleForm.email = datas.email
            this.ruleForm.phone = datas.phone || ''
            this.ruleForm.status = datas.status
            this.ruleForm.userSex = datas.usersex
            this.ruleForm.organguname = datas.organguname
            this.ruleForm.organguid = datas.organguid
            this.ruleForm.selectedOptions = []
            if (datas.organguid !== null) {
              let len = parseInt(datas.organguid.length / 4)
              for (let i = 1; i <= len; i++) {
                this.ruleForm.selectedOptions.push(datas.organguid.substring(0, i * 4))
              }
            }
          } else {
            this.$message({
              type: 'warning',
              message: '获取数据失败'
            })
          }
        }).catch(res => {
          this.$message({
            type: 'error',
            message: '获取数据失败'
          })
        })
      },
      // 确定
      dialogSure (ruleForm) {
        this.$refs[ruleForm].validate((valid) => {
          if (valid) {
            if (this.rowEditOnoff) { // 修改
              this.$emit('dialog-sure', [this.ruleForm, true])
            } else { // 新建
              if (this.ruleForm.userPassword === this.ruleForm.rePassword) { 
                this.$emit('dialog-sure', [this.ruleForm, false])
              } else { 
                this.$message({ 
                  type: 'error',
                  message: '两次输入的密码不相同'
                })
              }
            }
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },
      // 取消
      cancelRegister () { 
        this.$emit('dialog-cancel')
      },
      // 递归
      getChilds (data) {
        for (var i = 0; i < data.length; i++) {
           if (data[i].childOrganinfoinfos !== null) {
            this.getChilds(data[i].childOrganinfoinfos)
          } else {
            delete data[i]['childOrganinfoinfos']
          }
        }
        return data
      }
    } 
  }
</script>

<style lang="scss">
  .addeditUserDialog{ 
    .el-dialog--small{ 
      width: 40%;
    } 
    .el-dialog__header{ 
      padding: 20px 20px 0 20px;
      text-align: center;
      .el-dialog__title{ 
        color: #666;
      }
    }
    .el-dialog__body{ 
      padding: 20px 15px 10px 40px;
    }
    .el-form-item__label{ 
      width: 80px;
      float: left !important;
    }
    .el-form-item__content{ 
      float: left;
      width: 350px;
    }
    .el-form-item{ 
      margin-bottom: 18px;
    }
    .el-input-group__append {
      cursor: pointer;
    }
  }
</style>
