<template>
  <div>
    <van-nav-bar title="添加员工" left-text="返回" @click-left="$route_back" left-arrow>

    </van-nav-bar>
    <div class="body_com">
      <scroller>
        <van-cell-group style="margin-top: 0;" >
          <van-field required label="姓名" v-model="employee_info.name" name="姓名" v-validate="'required'" placeholder="请输入姓名" />
          <van-field required label="手机" v-model="employee_info.tel" type="Number" name="手机"  v-validate="'required|phone'" placeholder="请输入手机号码" />
          <DeptSelectorCell title="选择部门" v-model="depts" :max="0" :multi="false"></DeptSelectorCell>
        </van-cell-group>
        <div style="padding: 0.32rem;">
          <van-button type="info" block @click="save_btn">保存并发送邀请</van-button>
        </div>
      </scroller>
    </div>
  </div>
</template>

<script>
import request from '@/utils/request'
import DeptSelectorCell from '@/components/common/DeptSelectorCell'
import Vue from 'vue'
export default {
  name: 'employee_edit',
  data () {
    return {
      submit_loading: false,
      employee_info: {},
      depts: []
    }
  },
  components: {DeptSelectorCell},
  created () {
  },
  methods: {
    invite (id) {
      this.$toast.loading({
        message: '正在处理'
      })
      request('POST','/api/invite/create',{id: id}).then(res => {
        this.$toast.clear()
        if (res.data.code == 1) {
          this.$toast('已发送邀请，员工收到邀请并确认后将自动进入企业')
          this.$store.dispatch('get_employee_map', true).then(res => {})
          setTimeout(() => {
            this.$route_back()
          }, 1500)
        } else {
          this.$toast(res.data.msg)
        }
      }).catch(e => { })
    },
    // 创建人员
    employee_create () {
      let self = this
      self.submit_loading = true
      self.$toast.loading({
        mask: true,
        message: '正在处理'
      })
      self.depts.forEach(element => {
        delete element.avatar
      })
      self.employee_info.dept_list = self.depts
      request('POST','/api/employee/create', self.employee_info).then((res) => {
        self.submit_loading = false
        if (res.data.code == 1) {
          self.$toast.clear()
          self.invite(res.data.data.id)
          self.$keep_alive_update('add_employee', res.data)
        } else {
          self.$toast(res.data.msg)
        }
      }).catch((e) => {
        // self.$toast(e)
      })
    },
    // 保存
    save_btn () {
      let self = this
      self.$validator.validateAll().then(result => {
        if (!result) {
          self.$notify({ type: 'danger', message: self.$validator.errors.items[0].msg })
        } else {
          self.employee_create()
        }
      })
    }
  }
}
</script>

<style scoped>
  .submit_btn_box{padding:0.32rem;}
  .body_com{height: calc(100% - 0.92rem); position: relative;}
  /deep/ .van-field__label{padding-left:0.05rem;}
</style>
