<template>
  <el-dialog :visible.sync="dialog" :title="isAdd ? '新增用户' : '编辑用户'" append-to-body width="500px" @close="close">
    <el-form ref="form" label-position="left" :model="form" size="small" label-width="100px">
      <el-form-item label="姓名" prop="name">
        {{ form.name }}
      </el-form-item>
      <el-form-item label="登录状态">
        <el-tooltip :content="status ? '启用' : '禁用' " placement="top">
          <el-switch v-model="status"></el-switch>
        </el-tooltip>
      </el-form-item>

      <el-form-item style="margin-bottom: 0px;" label="用户角色">
        <el-select v-model="roleIds" style="width: 185px;margin-bottom:20px" multiple placeholder="请选择" size="medium">
          <el-option
            v-for="(item, index) in roles"
            :key="item.name + index"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

       <el-form-item label="管理营业部">
        <treeselect v-model="deptId" disabled :normalizer="normalizer" :options="depts" :style="style" placeholder="选择部门" size="smll" />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="text" @click="cancel">取消</el-button>
      <el-button :loading="loading" type="primary" @click="doSubmit">确认</el-button>
    </div>
  </el-dialog>
</template>

<script>

import { add, edit } from '@/api/user'
import { getDepts } from '@/api/dept'
import { getAll, getLevel } from '@/api/role'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
export default {
  components: { Treeselect },
  props: {
    isAdd: {
      type: Boolean,
      required: true
    }
  },
  data() {
    const validPhone = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入电话号码'))
      } else if (!this.isvalidPhone(value)) {
        callback(new Error('请输入正确的11位手机号码'))
      } else {
        callback()
      }
    }
    return {
      normalizer(node) {
        return {
          id: node.id,
          label: node.name,
          children: node.children && node.children.length > 0 ? node.children : 0
        }
      },
      status: false,
      dialog: false, loading: false, form: { name: '', email: '', enabled: 'false', roles: [], job: { id: '' }, dept: { id: '' }, phone: null },
      roleIds: [], roles: [], depts: [], deptId: '1', jobId: null, jobs: [], style: 'width: 184px', level: 3
    }
  },
  created() {
    const explorer = navigator.userAgent
    if (explorer.indexOf('Chrome') >= 0) {
      this.style = 'width: 184px'
    } else {
      this.style = 'width: 172px'
    }
  },
  methods: {
    close() {
      this.resetForm()
    },
    cancel() {
      this.resetForm()
    },
    doSubmit() {
      // this.form.deptId = this.deptId
      this.loading = true
            // this.form.roles = []
            const _this = this
            _this.form.roleIds = this.roleIds
            // this.roleIds.forEach(function(data, index) {
            //   const role = { id: data }
            //   _this.form.roles.push(role)
            // })
            if (this.isAdd) {
              this.doAdd()
            } else this.doEdit()
    },
    doAdd() {
      add(this.form).then(res => {
        this.resetForm()
        this.$notify({
          title: '添加成功',
          message: '默认密码：123456',
          type: 'success',
          duration: 2500
        })
        this.loading = false
        this.$parent.init()
      }).catch(err => {
        this.loading = false
        console.log(err.response.data.message)
      })
    },
    doEdit() {
      const { userId, roleIds } = this.form
      const status = this.status ? 1 : 2
      edit({ userId, roleIds, status }).then(res => {
        if (res.code === 0) {
          this.$notify({
            title: '修改成功',
            type: 'success',
            duration: 2500
          })
          this.$parent.init()
          this.resetForm()
        } else {
          this.$notify({
            title: res.message,
            type: 'error',
            duration: 2500
          })
        }
        this.loading = false
      }).catch(err => {
        this.loading = false
        console.log(err.response.data.message)
      })
    },
    resetForm() {
      this.dialog = false
      this.$refs['form'].resetFields()
      this.deptId = '1'
      this.jobId = null
      this.roleIds = []
      this.form = { name: '', email: '', enabled: 'false', roles: [], job: { id: '' }, dept: { id: '' }, phone: null }
    },
    getRoles() {
      getAll({ current: 1, size: 10000 }).then(res => {
        this.roles = res.data.list
      }).catch(err => {
        console.log(err.response.data.message)
      })
    },
    getDepts() {
      getDepts({ enabled: true }).then(res => {
        this.depts = res.data
      })
    },
    isvalidPhone(str) {
      const reg = /^1[3|4|5|7|8][0-9]\d{8}$/
      return reg.test(str)
    },
    getRoleLevel() {
      getLevel().then(res => {
        this.level = res.level
      }).catch(err => {
        console.log(err.response.data.message)
      })
    }
  }
}
</script>

<style scoped>

</style>
