<template>
  <el-dialog
    :title="editText"
    :visible.sync="visible"
    @close="cancel"
    width="700px"
    :close-on-click-modal="false"
  >
    <el-form ref="form" :model="form" label-width="100px" :rules="rules">
      <el-form-item label="用户名:" prop="userName">
        <el-input v-model="form.userName" />
      </el-form-item>
      <el-form-item label="真实姓名:" prop="realName">
        <el-input v-model="form.realName" />
      </el-form-item>
      <el-form-item label="电话号码:" prop="phone">
        <el-input v-model="form.phone" />
      </el-form-item>
      <el-form-item label="邮箱:">
        <el-input v-model="form.email" />
      </el-form-item>
      <el-form-item label="是否为管理员:">
        <el-switch
          v-model="form.isAdmin"
          active-color="#13ce66"
          inactive-color="#ccc"
          :active-value="1"
          :inactive-value="0"
        >
        </el-switch>
      </el-form-item>
      <el-form-item v-if="flag==1">注：新用户初始密码为123456</el-form-item>
    </el-form>
    <span slot="footer">
      <el-button @click="cancel">取消</el-button>
      <el-button type="primary" @click="confrim">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { formInit, rules } from '../../const';
import { updateInfo, create } from '../../api';
import { mapGetters } from 'vuex';

export default {
  name: 'edit',
  data() {
    return {
      rules,
      form: formInit(),
      visible: false
    }
  },
  props: {
    flag: {
      type: Number,
      default: 1
    },
    curInfo: {
      type: Object,
      default: () => { }
    }
  },
  watch: {
    flag: {
      immediate: true,
      handler(newV) {
        this.visible = !!newV;
        this.form = formInit(this.curInfo);
      },
    },
  },
  computed: {
    ...mapGetters('depart', ['departList']),
    editText() {
      return `${this.flag === 1 ? '新增' : '编辑'}基本信息`;
    }
  },
  methods: {
    cancel() {
      this.form = formInit();
      this.$emit('reset');
    },
    confrim() {
      let apiMap = {
        1: create,
        2: updateInfo,
      }
      let api = apiMap[this.flag];
      this.$refs['form'].validate(valid => {
        let params = {
          ...this.form
        }
        if (valid) {
          api(params).then(() => {
            this.$message.success('操作成功');
            this.$emit('reset', true);
          })
        }
      })
    }
  }
}
</script>
