<template>
  <div>
      <el-dialog
        v-dialogDrag
        :visible.sync="showModal"
        :close-on-click-modal="false"
        width="700px"
        :title="modalTitle"
      >
      <div>
        <Form id="edit-manager-form" ref="formObj" :model="formObj" :rules="ruleValidate" :label-width="80">
          <Form-item v-show="disabled" label="账号">
            <div>{{ formObj.username }}</div>
          </Form-item>
          <Form-item v-show="!disabled" label="账号" prop="username">
            <el-input v-model="formObj.username" name="username" placeholder="请输入登录账号" />
          </Form-item>
          <Form-item label="密码" prop="password">
            <el-input v-model="formObj.password" name="password" placeholder="请输入登录密码" :maxlength="20" show-word-limit/>
          </Form-item>
          <Form-item label="所属角色" prop="roleNameList">
            <el-input v-model="roleNameList" readonly @click.native="_selRole" />
          </Form-item>
        </Form>
      </div>
      <div slot="footer">
        <modal-footer ref="footerModal" :footer="footerList" @on-result-change="_footerResult" />
      </div>
      </el-dialog>
    <!-- 分配角色 -->
    <userRoleZtree ref="roleModal" @on-result-change="_roleData" />
  </div>
</template>
<script>
/**
 * 添加，编辑管理员
 */
import { sysUser } from '../../../api'
import userRoleZtree from './userRoleZtree'

export default {
  components: {
    userRoleZtree
  },
  data() {
    const validateName = (rule, value, callback) => {
      // 验证名称
      const reg = /^[0-9a-zA-Z]+$/
      if (value === '') {
        callback(new Error('账号不能为空！'))
      } else if (value.length > 20) {
        callback(new Error('长度不能超过20位'))
      } else if (!reg.test(value)) {
        callback(new Error('请输入0-20位数字或英文字符！'))
      } else {
        callback()
      }
    }
    const validatePsd = (rule, value, callback) => {
      // 验证密码，只能是数字和字母的结合
      const reg = /^[a-zA-Z0-9]+$/
      if (value === '') {
        callback(new Error('请输入您的密码'))
      } else if (value.length < 6) {
        callback(new Error('密码长度不能小于6位'))
      } else if (value === this.formObj.password.replace(/[^a-zA-Z]/g, '')) {
        // 只输入英文
        callback(new Error('请输入数字和字母结合的密码'))
      } else if (value === this.formObj.password.replace(/\D/g, '')) {
        // 只输入数字
        callback(new Error('请输入数字和字母结合的密码'))
      } else if (!reg.test(this.formObj.password)) {
        callback(new Error('请输入数字和字母结合的密码'))
      } else {
        callback()
      }
    }
    return {
      id: '',
      modalTitle: '',
      disabled: false,
      company: {},
      formObj: {
        username: '',
        password: ''
      },
      ruleValidate: {
        username: [
          { required: true, validator: validateName, trigger: 'blur' }
        ],
        password: [{ required: true, validator: validatePsd, trigger: 'blur' }]
      },
      showModal: false,
      roleNameList: '', // 所属角色
      roleIds: [],
      footerList: [
        { id: '', name: '取消', type: '' },
        { id: '', name: '保存', type: 'primary' }
      ]
    }
  },
  methods: {
    _footerResult(name) {
      switch (name) {
        case '取消':
          this._cancel()
          break
        case '保存':
          this._ok()
          break
      }
    },
    _resultChange(result, msg) {
      if (result) {
        this.showModal = false
        this.$message.success(msg)
        this.$emit('on-result-change')
      }
      this.$refs.footerModal._hideLoading()
    },
    _ok() {
      this.$refs.formObj.validate(valid => {
        if (valid) {
          const data = this.$serialize('edit-manager-form')
          data.companyId = this.company.id
          data.roleIds = this.roleIds.join()
          this._save(data)
        } else {
          this.$refs.footerModal._hideLoading()
          this.$message.error('表单验证失败!')
        }
      })
    },
    _save: async function(data) {
      if (this.$string(this.id).isEmpty()) {
        const result = await sysUser.addManager(data)
        this._resultChange(result, '添加成功!')
      } else {
        data.username = this.company.manager
        data.id = this.company.id
        const result = await sysUser.addManager(data)
        this._resultChange(result, '编辑成功!')
      }
    },
    _cancel() {
      this.$refs.footerModal._hideLoading()
      this.showModal = false
    },
    _open(company) {
      this.showModal = true
      this.$nextTick(() => {
        this.$refs.footerModal._hideLoading()
        this.$refs.formObj.resetFields()
        this.company = company
        if (company.manager) {
          this.id = company.id
          this.disabled = true
          this.formObj.username = company.manager
          this.modalTitle = '编辑管理员'
          this.$refs.roleModal._editRoleZtree(this.id) // 编辑回显角色名称
        } else {
          this.id = ''
          this.disabled = false
          this.roleNameList = ''
          this.modalTitle = '添加管理员'
        }
      })
    },
    _selRole() {
      // 选角色
      if (this.$string(this.id).isEmpty()) {
        // 添加
        this.$refs.roleModal._openRoleZtree()
      } else {
        // 编辑回显id
        this.$refs.roleModal._openRoleZtree(this.id)
      }
    },
    _roleData(result) {
      this.roleNameList = result.namesList.join(',')
      this.roleIds = result.idsList
    }
  }
}
</script>
