<template>
  <div class="dialog">
    <el-dialog :width="dialogWidth" :close-on-click-modal="false" :title="title" :visible.sync="dialogVisible">

      <!--内部弹窗-->
      <el-dialog
        title="选择部门"
        :visible.sync="deptTreeVisible"
        append-to-body>
        <el-input
          placeholder="输入关键字进行过滤"
          v-model="filterText">
        </el-input>

        <el-tree
          class="filter-tree"
          :data="deptTreeData"
          :props="defaultProps"
          default-expand-all
          :filter-node-method="filterNode"
          @node-click="handleNodeClick"
          ref="tree">
        </el-tree>
        <p v-if="handleTree" class="tree-span">选中的部门：
          <span>{{ checkedDept }}</span>
        </p>
        <div slot="footer" class="dialog-footer">
          <el-button @click="deptTreeVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleCheck">确 定</el-button>
        </div>
      </el-dialog>
      <el-form
        :model="form"
        ref="form"
        :rules="rules"
      >
        <el-form-item label="登录名称" prop="loginName" :label-width="formLabelWidth">
          <el-input :disabled="dialogStatus == 'update'" :readonly="configType == 2" v-model="form.loginName"
                    autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="用户名称" prop="userName" :label-width="formLabelWidth">
          <el-input v-model="form.userName" autocomplete="off" :readonly="configType == 2"></el-input>
        </el-form-item>
        <el-form-item label="密码" v-show="dialogStatus==='add'" :label-width="formLabelWidth" v-if="configType == 1">
          <el-input v-model="form.password" type="password" autocomplete="off"></el-input>
        </el-form-item>
        <!--        <el-form-item label="部门名称" :label-width="formLabelWidth" v-if="configType == 1">-->
        <!--          &lt;!&ndash;          <el-input :readonly="true"  autocomplete="off"></el-input>&ndash;&gt;-->
        <!--          <el-button @click="deptTreeVisible = true">{{ innerText }}</el-button>-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="邮箱" :label-width="formLabelWidth" v-if="configType == 1">-->
        <!--          <el-input v-model="form.email" type="email" autocomplete="off"></el-input>-->
        <!--        </el-form-item>-->
        <el-form-item label="手机" :label-width="formLabelWidth" v-if="configType == 1">
          <el-input v-model="form.phoneNumber" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="性别" :label-width="formLabelWidth" v-if="configType == 1">
          <template>
            <el-radio v-model="form.sex" :label="0">男</el-radio>
            <el-radio v-model="form.sex" :label="1">女</el-radio>
          </template>
        </el-form-item>
        <!--        <el-form-item label="岗位" :label-width="formLabelWidth">-->
        <!--          <el-input v-model="form.userName" autocomplete="off"></el-input>-->
        <!--        </el-form-item>-->
        <el-form-item label="角色" :label-width="formLabelWidth" v-if="addType == 1 && editType == 1 || configType == 2">
          <!--          <el-checkbox-group v-model="roleList">-->
          <!--            <el-checkbox v-for="item in roleOptions" :key="item.id" :label="item.id">{{item.roleName}}</el-checkbox>-->
          <!--          </el-checkbox-group>-->
          <el-select v-model="roleList" multiple filterable placeholder="请选择">
            <el-option
              v-for="item in roleOptions"
              :key="item.id"
              :label="item.roleName"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <template v-if="configType == 1">
          <el-button v-if="addType == 1 && editType == 1" type="primary"
                     @click="dialogStatus==='add'?createData('form',1):updateData('form',1)">确 定
          </el-button>
          <el-button v-else type="primary" @click="dialogStatus==='add'?createData('form',2):updateData('form',2)">确 定
          </el-button>
        </template>
        <template v-else>
          <el-button type="primary" @click="configData('form',1)">确 定</el-button>
        </template>
      </div>
    </el-dialog>
  </div>
</template>

<script>

import {
  getDeptTreeData,
  getRoleList,
  addUseer,
  updateUser,
  getUserInfo,
  addOnlyLoginUserInfo,
  updateOnlyLoginUserInfo,
  configLoginUserRole
} from '@/api/system/user.js'
import {getMenuTree, getMenuIds} from '@/utils/getTable.js'

const form = {
  loginName: '',
  userName: '',
  email: '',
  phoneNumber: '',
  sex: '',
  password: '',
  roleIds: '',
  deptId: 1
}
export default {
  name: 'RoleDialog',
  data() {
    return {
      roleId: '',
      keys: [],
      data: [],
      // defaultProps: {
      //   children: 'children',
      //   label: 'title'
      // },
      dialogVisible: false,
      dialogStatus: '',
      title: '',
      formLabelWidth: '80px',
      dialogWidth: '600px',
      form: Object.assign({}, form),

      // 部门树
      deptTreeVisible: false,
      filterText: '',
      deptTreeData: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      treeData: {},
      handleTree: false,
      innerText: '选择部门',
      checkedDept: '全部',
      roleOptions: [],

      listData: {
        total: 0,
        page: 1,
        pageSize: 999
      },

      // 选择角色
      roleList: [],

      addType: 1,
      editType: 1,
      configType: 1, // 1为不配置角色 2为角色配置
      rules: {
        loginName: [
          {required: true, message: '请输入登录名', trigger: 'blur'}
        ],
        userName: [
          {required: true, message: '请输入用户名', trigger: 'blur'}
        ]
      }

    }
  },
  props: {},
  mounted() {
    this.getDeptTree()
    // this.getRole()
  },
  methods: {
    // 获取部门树
    getDeptTree() {
      var _that = this
      var data = {}
      getDeptTreeData(data).then(res => {
        // console.log(res);

        const deptData = _that.getDeptsData(res.data)
        _that.deptTreeData = deptData
      })
    },
    getDeptsData(data) {
      var deptData = data
      deptData.forEach((item, index) => {
        const parentId = item.pId
        if (parentId === 0) {
          // 是根元素的hua ,不做任何操作,如果是正常的for-i循环,可以直接continue.
        } else {
          // 如果ele是子元素的话 ,把ele扔到他的父亲的child数组中.
          deptData.forEach(d => {
            if (d.id === parentId) {
              let childArray = d.children
              if (!childArray) {
                childArray = []
              }
              childArray.push(item)
              d.children = childArray
              deptData.splice(index, 1)
            }
          })
        }
      })
      return deptData
    },
    // 关键字筛选部门树
    filterNode(value, data) {
      if (!value) return true
      return data.name.indexOf(value) !== -1
    },

    // 部门树选中
    handleNodeClick(data) {
      // (data)console.log
      var _that = this
      _that.treeData = data
      _that.handleTree = true
      _that.checkedDept = data.name
    },
    // 确定选中部门
    handleCheck() {
      var _that = this
      _that.innerText = _that.treeData.name
      _that.form.deptId = _that.treeData.id
      _that.deptTreeVisible = false
    },

    // 获取角色
    getRole() {
      var _that = this

      var page = {
        pageIndex: _that.listData.page,
        pageSize: _that.listData.pageSize
      }
      var data = {
        'params': JSON.stringify({status: 0}),
        'page': JSON.stringify(page)
      }
      getRoleList(data).then(res => {
        // console.log('获取角色',res);
        _that.roleOptions = res.data
      })
    },

    createData(formName, type) {
      // 增加事件确定
      const _that = this
      if (_that.treeData) {
        _that.form.deptId = _that.treeData.id;
      }
      this.$refs[formName].validate((valid) => {
        if (valid) {
          _that.form.roleIds = _that.roleList.join(',')
          // if (_that.form.deptId == 0 || _that.form.deptId == null || _that.form.deptId == '') {
          //   _that.$message.error('部门不可为空')
          //   return
          // }
          if (type == 1) {
            var data = {
              'info': JSON.stringify(_that.form)
            }
            addUseer(data).then(response => {
              _that.dialogVisible = false
              _that.$message({
                message: '增加成功',
                type: 'success'
              })
              _that.$emit('tableRefresh', '')
            })
          } else {
            let {roleIds, ...params} = _that.form

            var data = {
              'info': JSON.stringify(params)
            }
            addOnlyLoginUserInfo(data).then(response => {
              _that.dialogVisible = false
              _that.$message({
                message: '增加成功',
                type: 'success'
              })
              _that.$emit('tableRefresh', '')
            })
          }
        }
      })
    },
    updateData(formName, type) {
      // 修改事件确定
      const _that = this
      // console.log('form', _that.form)
      this.$refs[formName].validate((valid) => {
        if (valid) {
          _that.form.roleIds = _that.roleList.join(',')
          if (_that.form.deptId == 0 || _that.form.deptId == null || _that.form.deptId == '') {
            _that.$message.error('部门不可为空')
            return
          }
          // console.log('form',_that.form)
          // return;
          if (type == 1) {
            var data = {
              'info': JSON.stringify(_that.form)
            }
            updateUser(data).then(response => {
              _that.dialogVisible = false
              _that.$message({
                message: '修改成功',
                type: 'success'
              })
              _that.$emit('tableRefresh', '')
            })
          } else {
            let {roleIds, ...params} = _that.form
            var data = {
              'info': JSON.stringify(params)
            }
            updateOnlyLoginUserInfo(data).then(response => {
              _that.dialogVisible = false
              _that.$message({
                message: '修改成功',
                type: 'success'
              })
              _that.$emit('tableRefresh', '')
            })
          }
        }
      })
    },
    configData() {
      const _that = this
      _that.form.roleIds = _that.roleList.join(',')
      var info = {
        id: _that.form.id,
        roleIds: _that.form.roleIds
      }
      var data = {
        'info': JSON.stringify(info)
      }
      // console.log(data);
      // return
      configLoginUserRole(data).then(response => {
        _that.dialogVisible = false
        _that.$message({
          message: '配置成功',
          type: 'success'
        })
        _that.$emit('tableRefresh', '')
      })

    },
    handleCreateAdd(type) {
      //type 1 管理员增加 2人事增加
      // 增加
      const _that = this
      _that.title = '增加用户'
      _that.addType = type
      _that.editType = 1
      _that.configType = 1
      _that.dialogStatus = 'add'
      _that.roleList = []
      _that.form = Object.assign({}, form)
      _that.dialogVisible = true
    },
    handleUpdata(id, type) {
      console.log(type);
      // 修改
      const _that = this
      _that.title = '修改用户'
      _that.editType = type
      _that.addType = 1
      _that.configType = 1
      _that.dialogStatus = 'update'
      _that.dialogVisible = true
      _that.form = Object.assign({}, form)
      _that.roleList = []
      var data = {
        'id': id
      }
      getUserInfo(data).then(response => {
        _that.dialogVisible = true
        // console.log('getRoleInfo',response);
        var data = response.data
        _that.form = {
          id: data.id,
          loginName: data.loginName,
          userName: data.userName,
          email: data.email,
          phoneNumber: data.phoneNumber,
          sex: data.sex,
          password: data.password,
          roleIds: data.roleIds,
          deptId: 1
        }
        _that.roleList = data.roleIds.split(',')
        _that.roleList = _that.roleList.map(Number)
        // console.log(typeof _that.roleList[0]);
        _that.innerText = data.deptName
      })
    },
    handleConfig(id) {
      const _that = this
      _that.title = '角色配置'
      _that.configType = 2
      _that.dialogStatus = 'add'
      _that.roleList = []
      _that.form = Object.assign({}, form)
      _that.dialogVisible = true
      var data = {
        'id': id
      }
      getUserInfo(data).then(response => {
        _that.dialogVisible = true
        // console.log('getRoleInfo',response);
        var data = response.data
        _that.form = {
          id: data.id,
          loginName: data.loginName,
          userName: data.userName,
          email: data.email,
          phoneNumber: data.phoneNumber,
          sex: data.sex,
          password: data.password,
          roleIds: data.roleIds,
          deptId: 1
        }
        _that.roleList = data.roleIds.split(',')
        _that.roleList = _that.roleList.map(Number)
        // console.log(typeof _that.roleList[0]);
        _that.innerText = data.deptName
      })
    }
  },
  watch: {
    titleDialog() {
      this.title = this.titleDialog
    },
    filterText(val) {
      this.$refs.tree.filter(val)
    }
  }
}
</script>

<style scoped>
.dialog {

}

.tree-span {
  padding-left: 15px;
}

.tree-span span {
  color: #E6A23C;
}

</style>
