<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="deptId">
        <el-select v-model="form.deptId" style="width:100%" placeholder="请选择">
          <el-option
            v-for="item in departList"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="电话号码:">
        <el-input v-model="form.phone" />
      </el-form-item>
      <el-form-item label="邮箱:">
        <el-input v-model="form.email" />
      </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>
