<template>
  <el-dialog
    :title="modalType === 'add' ? '新增账号' : '账号详情'"
    width="30%"
    :visible.sync="modal"
    :close-on-click-modal="false"
    @close="$emit('cancel')"
  >
    <el-form v-if="modalType !== 'roleSelect'" ref="ruleForm" :model="form" :rules="rules" label-width="80px">
      <el-form-item label="手机号码" prop="mobile">
        <el-input
          v-model="form.mobile"
          autocomplete="off"
          :maxlength="11"
          placeholder="请输入手机号码"
          :disabled="modalType === 'edit'"
        />
      </el-form-item>
      <el-form-item label="登录密码" prop="pwd">
        <el-input
          v-model="form.pwd"
          show-password
          autocomplete="off"
          placeholder="请输入登录密码"
        />
      </el-form-item>
      <el-form-item label="账号昵称" prop="name">
        <el-input
          v-model="form.name"
          autocomplete="off"
          placeholder="请输入账号昵称"
        />
      </el-form-item>
    </el-form>

    <el-select v-else v-model="roleSelect" placeholder="请选择">
      <el-option
        v-for="item in roleOptions"
        :key="item.value"
        :label="item.label"
        :value="item.value"
      />
    </el-select>
    <div slot="footer" class="dialog-footer">
      <el-button v-if="modalType !== 'roleSelect'" type="primary" @click="handleSubmit('ruleForm')">确认</el-button>
      <el-button v-else type="primary" @click="saveRoleByAccoundId()">确认</el-button>
      <el-button @click="modal = false">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import EMITKEY from '@/const/emitNameKey'
import { getItem, saveItem, saveRole, getRole, getItemRole } from '@/model/account'
import { Base64 } from 'js-base64'

const constData = ({
  nameMaxLength: '7'
})

export default {
  name: 'ItemModal',

  props: {
    id: {
      type: String,
      default: ''
    },
    modalType: {
      type: String,
      default: 'add'
    }
  },

  data() {
    const validateMobile = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入手机号码'))
      } else if (!/^\d{11}$/.test(value)) {
        callback(new Error('请输入正确的手机号'))
      } else {
        callback()
      }
    }

    return {
      modal: true,
      ...constData,
      form: {
        mobile: null,
        pwd: null,
        name: null
      },
      rules: {
        mobile: [{ required: true, validator: validateMobile, trigger: 'blur' }],
        captcha: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
        pwd: [{ required: true, message: '请输入登录密码', trigger: 'blur' }],
        name: [{ required: true, message: '请输入昵称', trigger: 'blur' }]
      },
      info: {
        avatarUrl: '',
        gender: 0,
        realname: ''
      },
      roleSelect: null,
      roleOptions: []
    }
  },

  mounted() {
    this.loadRole()
    if (this.id) {
      if (this.modalType !== 'roleSelect') {
        this.loadInfo()
      } else {
        this.loadItem()
      }
    }
  },

  methods: {
    async loadInfo() {
      const { success, data, msg } = await getItem({
        accountId: this.id
      })
      if (success) {
        Object.assign(this.form, data)
        this.info = data.info
      } else {
        this.$message.error(msg)
      }
    },

    handleSubmit(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.saveData()
        }
      })
    },

    async saveData() {
      const { success, data, msg } = await saveItem({
        data: {
          id: this.id,
          avatarUrl: this.info.avatarUrl,
          gender: this.info.gender,
          realname: this.info.realname,
          nickname: this.form.name,
          identifier: this.form.mobile,
          credential: Base64.encode(this.form.pwd),
          signInType: 'MOBILE_NUMBER_PASSWORD'
        }
      })
      if (success) {
        if (data) {
          this.setRoleInFirstAccount(data.id)
        } else {
          this.$message.success('操作成功~')
          this.modal = false
          this.bus.$emit(EMITKEY.ACCOUNTRELOAD)
        }
      } else {
        this.$message.error(msg)
      }
    },

    async loadItem() {
      const { success, data, msg } = await getItemRole({
        accountId: this.id
      })
      if (success) {
        this.roleSelect = data
      } else {
        this.$message.error(msg)
      }
    },

    async loadRole() {
      const { success, data, msg } = await getRole()
      if (success) {
        this.roleOptions = data
      } else {
        this.$message.error(msg)
      }
    },

    async saveRoleByAccoundId() {
      if (!this.roleSelect || this.roleSelect.length === 0) {
        this.$message.error(`请先选择账号角色~`)
        return false
      }
      const { success, msg } = await saveRole({
        data: {
          accountId: this.id,
          roleIdList: [this.roleSelect]
        }
      })
      if (success) {
        this.$message.success('角色调整成功~')
        this.modal = false
        this.bus.$emit(EMITKEY.ACCOUNTRELOAD)
      } else {
        this.$message.error(msg)
      }
    },

    async setRoleInFirstAccount(id) {
      // 读取后端字段名
      const arr = this.roleOptions.filter(x => x.label === '普通管理员')
      if (arr.length === 0) {
        /*
        账号添加了，绑定角色失败，没有获取到角色列表
         */
        this.$message.error('新增账号绑定角色失败~')
        return false
      }
      const { success, msg } = await saveRole({
        data: {
          accountId: id,
          roleIdList: arr.map(x => x.value)
        }
      })
      if (success) {
        this.$message.success('操作成功~')
        this.modal = false
        this.bus.$emit(EMITKEY.ACCOUNTRELOAD)
      } else {
        this.$message.error(msg)
      }
    }
  }
}
</script>

<style scoped>
.btn-right {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}
.disable {
  cursor: not-allowed;
}
.hand {
  cursor:hand;
  cursor:pointer;
}
</style>
