<template>
  <div class="app-container">
    <!-- 搜索工作栏 -->
    <el-row :gutter="20">
      <!--部门数据-->
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input v-model="deptName" placeholder="请输入部门名称" clearable size="small" prefix-icon="el-icon-search"
            style="margin-bottom: 20px" />
        </div>
        <div class="head-container">
          <el-tree :data="deptOptions" :props="defaultProps" :expand-on-click-node="false"
            :filter-node-method="filterNode" ref="tree" default-expand-all highlight-current
            @node-click="handleNodeClick" />
        </div>
      </el-col>
      <!--数据-->
      <el-col :span="20" :xs="24">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
          label-width="68px">
          <el-form-item label="姓名" prop="name">
            <el-input v-model="queryParams.name" placeholder="请输入姓名" clearable style="width: 240px"
              @keyup.enter.native="handleQuery" />
          </el-form-item>
          <el-form-item label="手机号码" prop="phone">
            <el-input v-model="queryParams.phone" placeholder="请输入手机号码" clearable style="width: 240px"
              @keyup.enter.native="handleQuery" />
          </el-form-item>
          <el-form-item label="创建时间" prop="createTime">
            <el-date-picker v-model="queryParams.createTime" style="width: 240px" value-format="yyyy-MM-dd HH:mm:ss"
              type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"
              :default-time="['00:00:00', '23:59:59']" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="warning" icon="el-icon-download" size="mini" @click="handleExport" :loading="exportLoading"
              v-hasPermi="['system:user:export']">导出</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" size="mini" @click="dialogVisible = true"
              v-hasPermi="['system:user:invite']">邀请成员</el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="userList">
          <el-table-column label="序号" type="index" width="50"align="center"/>
          <el-table-column label="姓名" align="center" prop="name"/>
          <el-table-column label="部门" align="center" prop="deptName"/>
            <el-table-column label="职位" align="center" prop="position"/>
          <el-table-column label="手机号码" align="center" prop="phone"/>
          <el-table-column label="邮箱" align="center" prop="email"/>
          <el-table-column label="性别" prop="gender" align="center">
            <template v-slot="scope">
              <dict-tag :type="DICT_TYPE.SYSTEM_USER_SEX" :value="scope.row.gender"/>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" align="center" prop="createTime" width="160">
            <template v-slot="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="160" class-name="small-padding fixed-width">
            <template v-slot="scope">
              <el-button size="mini" type="text" icon="el-icon-circle-check" @click="handleRole(scope.row)"
                v-hasPermi="['system:permission:assign-user-role']">分配角色</el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNo" :limit.sync="queryParams.pageSize"
          @pagination="getList" />
      </el-col>
    </el-row>
    <!-- 分配角色 -->
    <el-dialog title="分配角色" :visible.sync="openRole" width="500px" append-to-body>
      <el-form :model="form" label-width="80px">
        <el-form-item label="姓名">
          <el-input v-model="form.name" :disabled="true" />
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="form.roleIds" multiple placeholder="请选择" style="width: 100%;">
            <el-option v-for="item in roleOptions" :key="parseInt(item.id)" :label="item.name"
              :value="parseInt(item.id)"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitRole">确 定</el-button>
        <el-button @click="cancelRole">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="邀请成员" :visible.sync="dialogVisible" width="30%">
      <div class="content">
        <div class="public-link-operate">
          <div class="operate-title">
            邀请码
            <span class="link-tip">可通过下方邀请码加入你的企业。<span class="link-tip-mark">邀请码永久有效</span></span>
          </div>
        </div>
        <div class="public-link-address">
          邀请码
          <div class="link-input">
            <el-input v-model="corpId" readonly>
            <el-button slot="append" class="copy-btn">复制</el-button>
          </el-input>
          </div>

        </div>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import {exportUser,listUser} from "@/api/system/user";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { listSimpleDepts } from "@/api/system/dept";
import { assignUserRole, listUserRoles } from "@/api/system/permission";
import { listSimpleRoles } from "@/api/system/role";
import ClipboardJS from 'clipboard'
export default {
  name: "SystemUser",
  components: { Treeselect },
  data() {
    return {
      dialogVisible: false,
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      userList: null,
      // 弹出层标题
      title: "",
      // 部门树选项
      deptOptions: undefined,
      // 是否显示弹出层
      open: false,
      // 部门名称
      deptName: undefined,
      // 角色选项
      roleOptions: [],
      // 表单参数
      form: {},
      defaultProps: {
        children: "children",
        label: "name"
      },
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        name: undefined,
        phone: undefined,
        deptId: undefined,
        createTime: []
      },
      // 是否显示弹出层（角色权限）
      openRole: false,
    };
  },
  computed: {
    ...mapGetters([
      'corpId',
    ]),
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    }
  },
  created() {
    this.getList();
    this.getTreeselect();
  },
  mounted() {
    this.clipboard = new ClipboardJS('.copy-btn', {
      text: trigger => {
        this.$message({
          message: '复制成功',
          type: 'success'
        });
        return this.corpId;
      }
    })
    this.clipboard.on('error', e => {
      this.$message.error('复制失败')
    })
  },
  methods: {
    /** 查询列表 */
    getList() {
      this.loading = true;
      listUser(this.queryParams).then(response => {
        this.userList = response.data.list;
        this.total = response.data.total;
        this.loading = false;
      }
      );
    },
    /** 查询部门下拉树结构 + 职位下拉 */
    getTreeselect() {
      listSimpleDepts().then(response => {
        // 处理 deptOptions 参数
        this.deptOptions = [];
        this.deptOptions.push(...this.handleTree(response.data, "id"));
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.deptId = data.id;
      this.getList();
    },
    // 取消按钮（角色权限）
    cancelRole() {
      this.openRole = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        name: undefined,
        roleIds: []
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },


    /** 分配角色操作 */
    handleRole(row) {
      this.reset();
      const id = row.userId;
      if(id){
        // 处理了 form 的 name 和 name 的展示
        this.form.id = id;
        this.form.name = row.name;
        // 打开弹窗
        this.openRole = true;
        // 获得角色列表
        listSimpleRoles().then(response => {
          // 处理 roleOptions 参数
          this.roleOptions = [];
          this.roleOptions.push(...response.data);
        });
        // 获得角色拥有的菜单集合
        listUserRoles(id).then(response => {
          // 设置选中
          this.form.roleIds = response.data;
        })
      }else{
        this.$modal.msgWarning("该员工尚未注册账号,暂时无法分配角色!");
      }

    },

    /** 提交按钮（角色权限） */
    submitRole: function () {
      if (this.form.id !== undefined) {
        assignUserRole({
          userId: this.form.id,
          roleIds: this.form.roleIds,
        }).then(response => {
          this.$modal.msgSuccess("分配角色成功");
          this.openRole = false;
          this.getList();
        });
      }
    },
     /** 导出按钮操作 */
     handleExport() {
      const queryParams = this.queryParams;
      this.$modal.confirm('是否确认导出所有数据项?').then(() => {
          this.exportLoading = true;
          return exportUser(queryParams);
        }).then(response => {
          this.$download.excel(response, '员工数据.xls');
          this.exportLoading = false;
      }).catch(() => {});
    }
  },
  destroyed() {
    this.clipboard.destroy()
  }
};
</script>
<style lang="scss" scoped>
.public-link-operate {
    border-bottom: 1px solid #e1e3e5;
    padding: 20px 0;
    .operate-title {
        color: #141e31;
        font-size: 14px;
        font-weight: 500;
        margin-bottom: 12px;
.link-tip {
    color: #838892;
    font-weight: 400;
    margin-left: 10px;
.link-tip-mark {
    font-weight: 600;
}
}
    }
}
.public-link-address {
    color: #141e31;
    font-weight: 500;
    padding: 20px 0;
.link-input {
    font-weight: 400;
    margin-top: 10px;
    width: 100%;
}
}
</style>
