<template>
  <div class="page">
    <LayoutTable :data="tableData" :config="tableConfig" notAdd notDel />
    <dialog-show ref="dialogform" @ok="getData" />

    <el-dialog title="用户已分配的角色" :visible.sync="role.visible">
      <el-form :model="role.form">
        <el-checkbox-group v-model="role.checkList" :min="500">
          <el-checkbox v-for="item in allRoles" :key="item.id" :label="item.id"
            >{{ item.name }}
          </el-checkbox>
        </el-checkbox-group>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="role.visible = false">关闭</el-button>
      </div>
    </el-dialog>

    <el-dialog
      :title="userRoleDialog.title"
      :visible.sync="userRoleDialog.open"
      width="60%"
      append-to-body
    >
      <el-form label-width="100px">
        <Field
          label="角色分配"
          :span="24"
          v-model="roles"
          type="checkbox"
          :enumData="tableData.dict.roleIds"
        />
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="userRoleConfirm">确 定</el-button>
        <el-button @click="userRoleDialog.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog
      :title="userDeptDialog.title"
      :visible.sync="userDeptDialog.open"
      width="60%"
      append-to-body
    >
      <div class="mytree">
        <el-tree
          ref="bomTree"
          :data="data"
          id="el-tree"
          indent="0"
          node-key="id"
          :props="treeProps"
          :load="loadNode"
          highlight-current
          lazy
          :render-content="renderContent"
          @node-click="handleNodeClick"
        >
        </el-tree>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="userDeptConfirm">确 定</el-button>
        <el-button @click="userDeptDialog.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog
      :title="userPasswordDialog.title"
      hei
      :visible.sync="userPasswordDialog.open"
      width="40%"
    >
      <el-form ref="form" label-width="110px" label-position="right">
        <el-row>
          <Field
            :span="20"
            label="登录名称"
            prop="loginName"
            disabled
            v-model="userPasswordDialog.data.loginName"
          />

          <Field
            :span="20"
            label="重置密码"
            prop="loginPwd"
            v-model="userPasswordDialog.data.loginPwd"
          />
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="updatePasswordConfirm"
          >确 定</el-button
        >
        <el-button @click="userPasswordDialog.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog
      :title="userLoginDialog.title"
      :visible.sync="userLoginDialog.open"
      width="40%"
    >
      <el-form ref="form" label-width="110px" label-position="right">
        <el-row>
          <Field
            :span="20"
            label="登录名称"
            prop="loginName"
            disabled
            v-model="userLoginDialog.data.sourceloginName"
          />
          <Field
            :span="20"
            label="修改登录名称"
            prop="loginName"
            v-model="userLoginDialog.data.loginName"
          />
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="updateLoginConfirm">确 定</el-button>
        <el-button @click="userLoginDialog.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import dialogShow from "./dialogshow";
import table from "@/assets/mixins/table";

export default {
  mixins: [table],
  components: { dialogShow },
  methods: {
    // 打开弹窗
    async findRole({ id }) {
      try {
        this.tableData.loading = true;
        this.allRoles = await this.getUserRoles(id);
        this.role.checkList = await this.getRoleUsers(id);
        this.role.visible = true;
      } catch (error) {
        this.$message.error(error.message);
      }

      this.tableData.loading = false;
    },

    renderContent: function (h, { node, data, store }) {
      return (
        <span>
          <i style="font-size:16px;color:#409EFF" class={data.icon}></i>
          <span style="padding-left: 2px;font-size:14px">{node.label}</span>
        </span>
      );
    },
    async loadNode(node, resolve) {
      if (node.level === 0) {
        return;
      }
      this.$get("/dept/getListByParentId", {
        parentId: node.data.id,
      }).then(({ data }) => {
        resolve(data.result);
      });
    },
    handleNodeClick(data, node, obj) {
      console.log("select node tree", data);
      this.node = data;
    },

    userDeptConfirm(row) {
      if (Object.keys(this.node).length === 0) {
        this.$message.error("请选择一个部门！");
        return;
      }
      this.userDeptDialog.data["deptId"] = this.node.id;
      this.userDeptDialog.data["deptName"] = this.node.label;
      this.$post("/user/save", this.userDeptDialog.data).then((res) => {
        if (res && res.code == 1) {
          this.userDeptDialog.data = {};
          this.node = null;
          this.$message.success("分配部门成功！");
          this.getData();
        }

        this.userDeptDialog.open = false;
      });
    },

    // 获取角色列表与当前用户角色列表
    userRoleConfirm(row) {
      let data = this.userRoleDialog.data;

      this.$post("/user/save", {
        "entity.id": data.id,
        "entity.mobile": data.mobile,
        "entity.roleIds": this.roles.join(","),
      }).then((res) => {
        if (res && res.code == 1) {
          this.userRoleDialog.data = {};
          this.$message.success("分配角色成功！");
          this.getData();
        }

        this.userRoleDialog.open = false;
      });
    },

    async distributeRole(row) {
      try {
        this.tableData.loading = true;
        this.roles = await this.getRoleUsers(row.id);

        this.userRoleDialog.data = row;
        this.userRoleDialog.open = true;
      } catch (error) {
        this.$message.error(error.message);
      }
      this.tableData.loading = false;
    },

    async distributeDept(row) {
      this.tableData.loading = true;
      this.userDeptDialog.data = row;
      this.$nextTick(() => {
        this.$get("/dept/getListByParentId", {
          parentId: 0,
        })
          .then(({ data }) => {
            this.data = data.result;
            console.log(this.data);

            this.node = {};
          })
          .catch((error) => {
            this.$message.error(error.message);
          });
        this.userDeptDialog.open = true;
      });

      this.tableData.loading = false;
    },

    updatePassword(row) {
      try {
        const dataCopy = Object.assign({}, row);
        this.userPasswordDialog.data = dataCopy;
        this.userPasswordDialog.data.loginPwd = "";
        this.userPasswordDialog.open = true;
      } catch (error) {
        this.$message.error(error.message);
      }
    },

    updatePasswordConfirm() {
      console.log("修改密码");

      this.tableData.loading = true;
      this.$post("/user/save", {
        id: this.userPasswordDialog.data.id,
        loginPwd: this.userPasswordDialog.data.loginPwd,
      })
        .then((res) => {
          if (res && res.code == 1) {
            this.userPasswordDialog.data = {};
            this.$message.success("修改密码成功！");
            this.getData();
            this.userPasswordDialog.open = false;
          } else {
            this.$message.error(res.msg);
          }
          this.tableData.loading = false;
        })
        .catch((error) => {
          this.$message.error(error.message);
        });
    },

    updateLoginName(row) {
      console.log("修改登录名");
      try {
        const dataCopy = Object.assign({}, row);
        this.userLoginDialog.data = dataCopy;
        this.userLoginDialog.data.sourceloginName = dataCopy.loginName;
        this.userLoginDialog.data.loginName = "";
        this.userLoginDialog.open = true;
      } catch (error) {
        this.$message.error(error.msg);
      }
    },

    updateLoginConfirm() {
      console.log("修改登录名");
      this.tableData.loading = true;
      this.$post("/login/reLoginName", {
        id: this.userLoginDialog.data.id,
        loginName: this.userLoginDialog.data.loginName,
        userType: this.userLoginDialog.data.userType,
      })
        .then((res) => {
          if (res && res.code == 1) {
            this.userLoginDialog.data = {};
            this.$message.success("修改登录名成功！");
            this.getData();
            this.userLoginDialog.open = false;
          } else {
            this.$message.error(res.msg);
          }
          this.tableData.loading = false;
        })
        .catch((error) => {
          this.$message.error(error.message);
        });
    },

    // 获取用户角色列表
    getUserRoles(id) {
      return new Promise((resolve, reject) => {
        this.$post("/role/roleNameByUserId", { userId: id })
          .then(({ data }) => {
            resolve(data);
          })
          .catch(reject);
      });
    },
    getRoleUsers(id) {
      return new Promise((resolve, reject) => {
        this.$post("/role/user/list", {
          userId: id,
          size: -1,
        })
          .then(({ data }) => {
            const result = data.data
              .filter((i) => i.roleId + "")
              .map((i) => i.roleId + "");
            resolve(result);
          })
          .catch(reject);
      });
    },
    /** 重写新增方法 */
    toAdd(row) {
      this.$refs.dialogform.add(row);
    },
    /** 重写编辑方法 */
    toEdit(row) {
      this.$refs.dialogform.edit(row);
    },
    /** 重写查看方法 */
    toView(row) {
      this.$refs.dialogform.view(row);
    },
  },
  data() {
    return {
      allRoles: {},
      nodeData: {},
      node: {},
      data: [],
      tree: [],
      roles: [],
      userRoleDialog: {
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        title: "选择角色",
        data: {},
      },
      userDeptDialog: {
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        title: "选择部门",
        data: {},
      },

      userPasswordDialog: {
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        title: "修改密码",
        data: {},
      },

      userLoginDialog: {
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        title: "修改登录名",
        data: {},
      },

      treeProps: {
        children: "children",
        label: "label",
        id: "id",
      },
      role: {
        checkList: [],
        visible: false,
      },
      config: {
        isshowTabPane: true,
        columns: [
          { type: "selection", reserveSelection: true, width: 60 },
          { type: "index", label: "序号", align: "center", width: 50 },
          {
            prop: "loginName",
            label: "登录名称",
            align: "center",
          },
          {
            prop: "realName",
            label: "用户名称",
            align: "center",
          },
          {
            prop: "mobile",
            label: "手机号码",
            align: "center",
          },
          {
            prop: "deptId",
            label: "所属部门",
            formatter: this.formatter,
            align: "center",
          },

          {
            prop: "customerId",
            label: "所属员工",
            formatter: this.formatter,
            align: "center",
          },
          {
            prop: "roleIds",
            label: "所属角色",
            formatter: this.formatter,
            align: "center",
          },

          // {
          //   prop: "userType",
          //   label: "用户类型",
          //   width: 130,
          //   formatter: this.formatter,
          // },
          {
            prop: "status",
            label: "状态",
            width: 80,
            align: "center",
            formatter: this.formatter,
          },
          {
            label: "操作",
            width: 320,
            align: "center",
            formatter: (row) => {
              return (
                <div>
                  <table-buttons
                    noView
                    noDel
                    row={row}
                    onEdit={this.toEdit}
                    onDel={this.toDel}
                  />
                  {/*
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-share"
                    onClick={() => this.distributeRole(row)}
                  >
                    分配角色
                  </el-button>
                  */}
                  <span> </span>
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-share"
                    onClick={() => this.distributeDept(row)}
                  >
                    分配部门
                  </el-button>
                  <span> </span>
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-share"
                    onClick={() => this.updatePassword(row)}
                  >
                    修改密码
                  </el-button>

                  <span> </span>
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-share"
                    onClick={() => this.updateLoginName(row)}
                  >
                    修改登录名
                  </el-button>
                </div>
              );
            },
          },
        ],
        search: [
          {
            name: "loginName",
            type: "text",
            label: "登录名",
          },
          {
            name: "realName",
            type: "text",
            label: "用户名称",
          },
          {
            name: "mobile",
            type: "text",
            label: "手机号",
          },
        ],
      },
    };
  },
};
</script>

<style lang="scss" scoped>
.mytree ::v-deep {
  .el-tree--highlight-current
    ::v-deep
    .el-tree-node.is-checked
    > .el-tree-node__content {
    background-color: rgb(255, 255, 255);
    color: rgb(64, 158, 255);
  }

  .el-tree--highlight-current
    ::v-deep
    .el-tree-node.is-current
    > .el-tree-node__content {
    background-color: rgb(255, 255, 255);
    color: rgb(64, 158, 255);
  }

  .el-tree > .el-tree-node:after {
    border-top: none;
  }

  .el-tree-node {
    position: relative;
    padding-left: 16px;
  }

  //节点有间隙，隐藏掉展开按钮就好了,如果觉得空隙没事可以删掉
  .el-tree-node__expand-icon.is-leaf {
    display: none;
  }

  .el-tree-node__children {
    padding-left: 16px;
  }

  .el-tree-node :last-child:before {
    height: 38px;
  }

  .el-tree > .el-tree-node:before {
    border-left: none;
  }

  .el-tree > .el-tree-node:after {
    border-top: none;
  }

  .el-tree-node:before {
    content: "";
    left: -4px;
    position: absolute;
    right: auto;
    border-width: 1px;
  }

  .el-tree-node:after {
    content: "";
    left: -4px;
    position: absolute;
    right: auto;
    border-width: 1px;
  }

  .el-tree-node:before {
    border-left: 1px dashed #4386c6;
    bottom: 0px;
    height: 100%;
    top: -26px;
    width: 1px;
  }

  .el-tree-node:after {
    border-top: 1px dashed #4386c6;
    height: 20px;
    top: 12px;
    width: 24px;
  }
}
</style>
