<template>
  <div>
    <el-dialog
      v-dialogDrag
      :visible.sync="showModal"
      :close-on-click-modal="false"
      :title="modalTitle"
    >
      <div>
        <Form
          id="edit-form"
          ref="formObj"
          :model="formObj"
          :rules="ruleValidate"
          :label-width="80"
          inline
        >
          <Form-item label="账号" prop="username" class="width-48">
            <el-tooltip content="长度为0-20" placement="bottom-start">
              <el-input v-model="formObj.username" name="username" placeholder="请输入账号" style="width: 100%" />
            </el-tooltip>
          </Form-item>
          <Form-item label="密码" prop="password" class="width-48">
            <el-input v-model="formObj.password" name="password" style="width: 100%" :maxlength="20" placeholder="请输入您的密码" />
          </Form-item>
          <Form-item label="确认密码" prop="passwordCheck" class="width-48">
            <el-input
              v-model="formObj.passwordCheck"
              name="passwordCheck"
              style="width: 100%"
              :maxlength="20"
              placeholder="请确认您密码"
            />
          </Form-item>
          <Form-item label="真实姓名" prop="realname" class="width-48">
            <el-input v-model="formObj.realname" name="realname" placeholder="请输入真实姓名" />
          </Form-item>
          <Form-item label="QQ" prop="qq" class="width-48">
            <el-input v-model="formObj.qq" name="qq" placeholder="请输入QQ号码" />
          </Form-item>
          <Form-item label="手机号码" prop="mobile" class="width-48">
            <el-input v-model="formObj.mobile" name="mobile" placeholder="请输入手机号码" :disabled="id?true:false" />
          </Form-item>
          <Form-item label="邮箱" prop="email" class="width-48">
            <el-input v-model="formObj.email" name="email" placeholder="请输入邮箱" :disabled="id?true:false" />
          </Form-item>
          <Form-item label="所属组织" style="width: 98.6%;">
            <el-input v-model="orgNameList" placeholder="请选择组织" readonly @click.native="_selOrg" />
          </Form-item>
          <Form-item label="所属角色" style="width: 98.6%;">
            <el-input v-model="roleNameList" placeholder="请选择角色" readonly @click.native="_selRole" />
          </Form-item>
          <Form-item label="通知微信" prop="notifyWechat" style="width: 45%">
            <el-radio-group v-model="formObj.notifyWechat" @change="_selectNotifyWechat">
              <el-radio v-for="item in notifyWechatList" :key="item.value" :label="item.value">
                {{ item.name }}
              </el-radio>
            </el-radio-group>
          </Form-item>
          <Form-item label="性别" prop="sex" style="width: 45%">
            <el-radio-group v-model="formObj.sex" @on-change="_selectSex">
              <el-radio v-for="item in sexList" :key="item.value" :label="item.value">
                {{ item.name }}
              </el-radio>
            </el-radio-group>
          </Form-item>
          <Form-item label="授权" prop="accredit" style="width: 100%">
            <el-radio-group v-model="formObj.accredit" @change="_selectAccredit">
              <el-radio v-for="item in accreditList" :key="item.value" :label="item.value">
                {{ item.label }}
              </el-radio>
            </el-radio-group>
          </Form-item>
          <Form-item label="状态" prop="status" style="width: 100%">
            <el-radio-group v-model="formObj.status" @change="_selectStatus">
              <el-radio v-for="item in statusList" :key="item.value" :label="item.value">
                {{ item.label }}
              </el-radio>
            </el-radio-group>
          </Form-item>
        </Form>
      </div>
      <div slot="footer">
        <modal-footer ref="footerModal" :footer="footerList" @on-result-change="_footerResult" />
      </div>
    </el-dialog>
    <!--分配组织-->
    <selOrgTree ref="orgModal" @on-result-change="_orgData" />
    <!--分配角色-->
    <selRoleTree ref="roleModal" @on-result-change="_roleData" />
  </div>
</template>
<script>
/**
 * 添加编辑
 */
import { sysUser } from '../../../api'
import global from '../../../api/config'
import selOrgTree from './tree/selOrgTree'
import selRoleTree from './tree/selRoleTree'

export default {
  components: { selOrgTree, selRoleTree },
  data() {
    const validateName = (rule, value, callback) => {
      // 验证名称
      if (value === '') {
        callback(new Error('账号不能为空！'))
      } else {
        callback()
      }
    }
    // const validatePass = (rule, value, callback) => {
    //   // // 验证密码，必须是数字和字母的结合
    //   // if (this.formObj.password === undefined) {
    //   //   // 编辑
    //   //   callback()
    //   // } else if (value === '' || undefined === 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 (this.formObj.passwordCheck !== '' && this.id !== '') {
    //   //     // 对第二个密码框单独验证
    //   //     this.$refs.formObj.validateField('passwordCheck')
    //   //   }
    //   //   callback()
    //   // }
    // }
    // const validatePassCheck = (rule, value, callback) => {
    //   if (this.formObj.password === '' && value === '') {
    //     callback(new Error('请再次输入您的密码'))
    //   } else if (value !== this.formObj.password) {
    //     callback(new Error('两次输入的密码不匹配'))
    //   } else {
    //     callback()
    //   }
    // }
    const validateMobile = (rule, value, callback) => {
      // 验证手机号
      const reg = /^((\+?86)|(\(\+86\)))?1\d{10}$/ // 支持+86格式的手机号
      if (this.formObj.mobile === '') {
        callback(new Error('请输入您的手机号'))
      } else if (!reg.test(this.formObj.mobile)) {
        callback(new Error('手机号格式不正确'))
      } else {
        callback()
      }
    }
    const validateQq = (rule, value, callback) => {
      // 验证qq
      const reg = /^[0-9]*$/
      if (value === undefined) {
        callback()
      } else if (!reg.test(value)) {
        callback(new Error('请输入数字!'))
      } else {
        callback()
      }
    }
    return {
      id: '',
      modalTitle: '添加',
      formObj: {
        username: '',
        password: '',
        passwordCheck: '',
        realname: '',
        qq: '',
        mobile: '',
        email: '',
        accredit: 'ALLOW',
        sex: 0,
        notifyWechat: 0,
        status: 'PENDING_ACTIVATION'
      },
      accreditList: [
        { value: 'NORMAL', label: '普通' },
        { value: 'ALLOW', label: '允许进入后台' }
      ],
      notifyWechatList: [{ value: 0, name: '否' }, { value: 1, name: '是' }],
      sexList: [{ value: 0, name: '男' }, { value: 1, name: '女' }],
      statusList: [
        { value: 'PENDING_ACTIVATION', label: '待激活' },
        { value: 'NORMAL', label: '正常' },
        { value: 'DISABLED', label: '禁用' }
      ],
      ruleValidate: {
        username: [
          { required: true, validator: validateName, trigger: 'blur' }
        ],
        mobile: [
          { required: true, validator: validateMobile, trigger: 'blur' }
        ],
        email: [{ type: 'email', message: '邮箱格式不正确', trigger: 'blur' }],
        qq: [{ validator: validateQq, trigger: 'blur' }],
        realname: [
          { required: true, message: '真实姓名不能为空', trigger: 'blur' }
        ]
      },
      orgNameList: '',
      roleNameList: '',
      orgIds: [],
      roleIds: [],
      imgUrl: '',
      action: global.baseURL + '/v1/file_signature/',
      showModal: false,
      showSign: false,
      footerList: [
        { id: '', name: '取消', type: '' },
        { id: '', name: '保存', type: 'primary' }
      ]
    }
  },
  methods: {
    // modal
    _footerResult(name) {
      switch (name) {
        case '取消':
          this._cancel()
          break
        case '保存':
          this._ok()
          break
      }
    },
    _hideLoading() {
      this.$refs.footerModal._hideLoading()
    },
    _resultChange(result, msg) {
      if (result) {
        this.showModal = false
        this.$message.success(msg)
        this.$emit('on-result-change')
      }
      this._hideLoading()
    },
    _ok() {
      this.$refs.formObj.validate(valid => {
        if (valid) {
          const data = this.$serialize('edit-form')
          this.$extend(data, {
            notifyWechat: this.formObj.notifyWechat,
            accredit: this.formObj.accredit,
            sex: this.formObj.sex,
            status: this.formObj.status,
            orgIds: this.orgIds.join(),
            roleIds: this.roleIds.join()
          })
          this._save(data)
        } else {
          this.$message.error('表单验证失败')
          this._hideLoading()
        }
      })
    },
    // 添加、编辑保存
    _save: async function(data) {
      // 添加
      if (this.$string(this.id).isEmpty()) {
        const result = await sysUser.add(data)
        this._resultChange(result, '添加成功')
      } else {
        // 编辑
        const result = await sysUser.edit({
          id: this.formObj.id,
          obj: data
        })
        this._resultChange(result, '编辑成功')
      }
    },
    _cancel() {
      this.showModal = false
    },
    _open(formObj, roleNames) {
      this.showModal = true
      this.$nextTick(() => {
        this.$refs.formObj.resetFields()
        this.orgNameList = ''
        this.roleNameList = ''
        this.orgIds = []
        this.roleIds = []
        this._hideLoading()
        if (this.$string(formObj).isEmpty()) {
          this.id = ''
          this.modalTitle = '添加用户'
          this.showSign = false
        } else {
          this.modalTitle = '编辑用户'
          this.id = formObj.id
          this.formObj = formObj
          this.formObj.sex = formObj.sex
          this.formObj.accredit = formObj.accredit.value
          this.formObj.notifyWechat = formObj.notifyWechat
          this.formObj.mobile = formObj.mobile ? formObj.mobile : ''
          this.formObj.status = formObj.status.value
          this.$refs.orgModal._editOrgZtee(this.id) // 编辑回显组织名称
          this.roleNameList = roleNames || ''
          this.imgUrl =
            global.baseURL + '/v1/file_signature/download/' + this.id
          this.showSign = true
        }
      })
    },
    _selOrg() {
      // 选组织
      if (this.$string(this.id).isEmpty()) {
        // 添加
        this.$refs.orgModal._openOrginZtree()
      } else {
        // 编辑回显id
        this.$refs.orgModal._openOrginZtree(this.id)
      }
    },
    _orgData(result) {
      if (result.idsList.length > 0) {
        this.orgNameList = result.namesList.join(',')
        this.orgIds = result.idsList
      } else {
        this.orgNameList = ''
        this.orgIds = []
      }
    },
    _selRole() {
      // 选角色
      if (this.$string(this.id).isEmpty()) {
        // 添加
        this.$refs.roleModal._openRoleZtree()
      } else {
        // 编辑回显id
        this.$refs.roleModal._openRoleZtree(this.id)
      }
    },
    _roleData(result) {
      if (result.idsList.length > 0) {
        this.roleNameList = result.namesList.join(',')
        this.roleIds = result.idsList
      } else {
        this.roleNameList = ''
        this.roleIds = []
      }
    },
    _selectAccredit(data) {
      this.formObj.accredit = data
    },
    _selectNotifyWechat(data) {
      this.formObj.notifyWechat = data
    },
    _selectSex(data) {
      this.formObj.sex = data
    },
    _selectStatus(data) {
      this.formObj.status = data
    }
  }
}
</script>
