<template>
  <div class="box">
    <div class="box-content">
      <!-- input + button* 2 -->
      <div style="margin-bottom: 10px">
        <el-form :inline="true" label-width="80px">
          <el-form-item>
            <el-input v-model="keyword" placeholder="请输入职位名称"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button @click="search" type="success">搜索</el-button>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              v-if="hasPerm('auth:add')"
              @click="dialogVisible = true"
              >新增职位</el-button
            >
          </el-form-item>
        </el-form>
      </div>
      <div>
        <el-table :data="tableData" border :height="720 + 'px'">
          <el-table-column prop="id" label="职位id"> </el-table-column>
          <el-table-column prop="groupName" label="职位名称"> </el-table-column>
          <el-table-column prop="remark" label="备注"> </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="primary"
                v-if="hasPerm('auth:edit')"
                @click="handleEdit(scope.row)"
                >编辑</el-button
              >
              <el-button
                size="mini"
                type="warning"
                v-if="hasPerm('auth:Limits')"
                @click="handleLimits(scope.row)"
                >权限分配</el-button
              >
              <el-button
                size="mini"
                type="danger"
                v-if="hasPerm('auth:User')"
                @click="handleUser(scope.row)"
                >用户分配</el-button
              >
              <el-button
                size="mini"
                type="danger"
                v-if="hasPerm('auth:del')"
                @click="del(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <table-footer
          :totals="total"
          :size="size"
          @sizeChange="sizeChange"
          @pageChange="pageChange"
        ></table-footer>
      </div>
    </div>
    <!--    // 新增-->
    <el-dialog
      :title="showType ? '编辑职位' : '新增职位'"
      :visible.sync="dialogVisible"
      width="30%"
    >
      <div>
        <el-form ref="form" :model="form" label-width="100px">
          <el-form-item label="职位名称">
            <el-input v-model="form.groupName"></el-input>
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="form.remark"></el-input>
          </el-form-item>
        </el-form>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="reset">取 消</el-button>
        <el-button v-if="showType" type="primary" @click="setUpdate"
          >更 新</el-button
        >
        <el-button v-else type="primary" @click="onSubmit">新 增</el-button>
      </span>
    </el-dialog>
    <!-- 权限分配   -->
    <a-modal
      title="职位分配"
      :width="600"
      :visible="dialogLimits"
      @ok="limitSave"
      ok-text="确认"
      cancel-text="取消"
      @cancel="dialogLimits = false"
      :destroyOnClose="true"
    >
      <a-tree
        v-model="checkedKeys"
        multiple
        checkable
        :auto-expand-parent="autoExpandParent"
        :expanded-keys="expandedKeys"
        :tree-data="menuTreeData"
        :selected-keys="selectedKeys"
        :replaceFields="replaceFields"
        @expand="onExpand"
        @check="onCheck"
      />
    </a-modal>
    <el-dialog title="用户分配" :visible.sync="dialogUsers" width="50%">
      <div>
        <el-table
          :data="userList"
          ref="multipleTable"
          tooltip-effect="dark"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55"> </el-table-column>
          <el-table-column prop="id" label="用户ID"> </el-table-column>
          <el-table-column prop="account" label="用户姓名"> </el-table-column>
        </el-table>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogUsers = false">取 消</el-button>
        <el-button type="primary" @click="userSave">保存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { Tree } from "ant-design-vue";
import TableFooter from "../../components/TableFooter";
import {
  getUserMenu,
  getAuth,
  delAuth,
  addAuth,
  editAuth,
  getMenuByGroup,
  saveGroupMenu,
  getAcountByGroup,
  saveAccountGroup,
  getUserList,
} from "../../utils/api";
export default {
  name: "AuthAdmin",
  components: {
    TableFooter,
    ATree: Tree,
  },
  data() {
    return {
      tableData: [],
      showType: false,
      dialogVisible: false,
      form: {
        id: "",
        groupName: "",
        remark: "",
      },
      dialogLimits: false,
      // 权限分配list
      limitList: [],
      defaultProps: {
        children: "children",
        label: "title",
      },
      autoExpandParent: true,
      // 默认选择的参数
      defaultList: [],
      expandedKeys: [],
      checkedKeys: [],
      replaceFields: {
        key: "id",
      },
      keyword: "",
      total: 0,
      size: 20,
      pageNum: 1,
      selectId: "",
      // 用户列表
      userList: [],
      dialogUsers: false,
      userSelect: [],
      leastChilds: [],
      commitKeys: [],
      selectedKeys: [],
      menuTreeData: [],
      // 判断是否点击权限的复选框
      isKey: false,
    };
  },
  methods: {
    // 搜索
    search() {
      this.init();
    },
    // 修改size
    sizeChange(val) {
      this.size = val;
      this.init();
    },
    // 修改页数
    pageChange(val) {
      this.pageNum = val;
      this.init();
    },
    handleEdit(data) {
      this.showType = true;
      this.dialogVisible = true;
      this.form.remark = data.remark;
      this.form.groupName = data.groupName;
      this.form.id = data.id;
    },
    // 用户分配
    handleUser(data) {
      this.dialogUsers = true;
      this.selectId = data.id;
      getAcountByGroup({ groupId: data.id }).then((res) => {
        if (res.code === 10006) {
          this.userSelect = [];
          this.$nextTick(() => {
            this.$refs.multipleTable.clearSelection();
            this.$forceUpdate();
          });
        } else {
          let arr = res.data.split(",");
          console.log(arr);
          this.$nextTick(() => {
            this.$refs.multipleTable.clearSelection();
            for (let key in this.userList) {
              for (let i in arr) {
                if (this.userList[key]["id"] == arr[i]) {
                  this.$refs.multipleTable.toggleRowSelection(
                    this.userList[key],
                    true
                  );
                }
              }
            }
          });
        }
      });
    },
    // 用户分配选择
    handleSelectionChange(val) {
      this.userSelect = val;
    },
    // 用户分配保存
    userSave() {
      let users = [];
      this.userSelect.forEach((item) => {
        users.push(item.id);
      });
      let str = users.join(",");
      saveAccountGroup({ accountId: str, groupIds: this.selectId }).then(
        (res) => {
          if (res.code === 10001) {
            this.$message.success(res.message);
          } else {
            this.userSelect = [];
            this.selectId = "";
            this.$message(res.message);
          }
        }
      );
      this.dialogUsers = false;
    },
    // 新增角色
    onSubmit() {
      let params = {
        groupName: this.form.groupName,
        remark: this.form.remark,
      };
      addAuth(params).then((res) => {
        if (res.code === 10000) {
          this.init();
          this.$message.success(res.message);
        } else {
          this.$message.error(res.message);
        }
        this.dialogVisible = false;
        this.reset();
      });
    },
    // handleCheckChange() {
    //   // console.log(data, ls, lg)
    //   this.selectList = [];
    //   console.log(this.$refs.tree.getCheckedKeys());
    //   this.selectList = this.$refs.tree.getCheckedKeys().concat(this.$refs.tree.getHalfCheckedKeys());
    // },
    onExpand(expandedKeys) {
      this.expandedKeys = expandedKeys;
      this.autoExpandParent = false;
    },

    onCheck(checkedKeys, info) {
      this.isKey = true;
      this.checkedKeys = checkedKeys;
      this.commitKeys = checkedKeys.concat(info.halfCheckedKeys);
    },
    pickCheckedKeys(data) {
      for (let i = 0; i < data.length; i++) {
        if (this.leastChilds.includes(data[i])) {
          this.checkedKeys.push(data[i]);
        }
      }
    },
    onSelect(selectedKeys) {
      this.selectedKeys = selectedKeys;
    },
    // 权限分配
    handleLimits(data) {
      this.dialogLimits = true;
      this.selectId = data.id;
      this.defaultList = [];
      getMenuByGroup({ groupId: data.id }).then((res) => {
        let arr;
        if (res.code === 10000) {
          arr = res.data.split(",");
          this.defaultList = arr.map(Number);
          this.pickCheckedKeys(this.defaultList);
          this.selectList = this.defaultList;
        } else {
          arr = [];
          this.defaultList = [];
          this.selectList = [];
          this.selectedKeys = [];
          this.checkedKeys = [];
        }
      });
    },
    // 权限分配保存
    limitSave() {
      // this.selectList = this.$refs.tree.getCheckedKeys();
      let menuIds;
      if (this.commitKeys.length > 0) {
        menuIds = this.commitKeys.join(",");
      } else {
        menuIds = "";
      }
      saveGroupMenu({ groupId: this.selectId, menuIds: menuIds }).then(
        (res) => {
          if (res.code === 10001) {
            this.$message.success(res.message);
          }
          this.selectId = "";
          this.dialogLimits = false;
          this.selectList = [];
        }
      );
      if (this.isKey) {
        let menuIds;
        if (this.commitKeys.length > 0) {
          menuIds = this.commitKeys.join(",");
        } else {
          menuIds = "";
        }
        saveGroupMenu({ groupId: this.selectId, menuIds: menuIds }).then(
          (res) => {
            if (res.code === 10001) {
              this.$message.success(res.message);
            }
            this.selectId = "";
            this.dialogLimits = false;
            this.selectList = [];
          }
        );
      } else {
        this.dialogLimits = false;
      }
    },
    init() {
      // 后端分页
      let params = {
        pageNum: this.pageNum,
        pageSize: this.size,
        searchStr: this.keyword,
      };
      getAuth(params).then((res) => {
        this.tableData = res.records;
        this.total = res.total;
      });
    },
    // 重置
    reset() {
      this.form.id = "";
      this.form.groupName = "";
      this.form.remark = "";
      this.pageNum = 1;
      this.keyword = "";
      this.showType = false;
      this.dialogVisible = false;
    },
    // 更新
    setUpdate() {
      let params = {
        groupName: this.form.groupName,
        remark: this.form.remark,
        id: this.form.id,
      };
      editAuth(params).then((res) => {
        if (res.code === 10000) {
          this.init();
          this.$message.success(res.message);
        }
        this.dialogVisible = false;
        this.reset();
      });
    },
    // 删除
    del(data) {
      this.$confirm("此操作将永久删除批量删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          delAuth({ groupId: data.id }).then((res) => {
            if (res.code === 10000) {
              this.init();
              this.$message.success(res.message);
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 菜单列表
    authInit() {
      let params = {
        userId: localStorage.getItem("gold_UserId"),
      };
      getUserMenu(params).then((res) => {
        if (res.code === 10000) {
          this.menuTreeData = res.data;
          this.getLeastChilds(res.data);
          this.menuTreeData.forEach((item) => {
            this.expandedKeys.push(item.id);
          });
          // this.expandedMenuKeys(this.roleEntity)
        }
      });
    },
    getLeastChilds(data) {
      for (let i = 0; i < data.length; i++) {
        this.pushLeastChilds(data[i]);
      }
    },
    pushLeastChilds(e) {
      if (e.children.length > 0) {
        this.getLeastChilds(e.children);
        return;
      }
      this.leastChilds.push(e.id);
    },
    // 用户列表
    userInit() {
      let params = {
        pageNum: 1,
        pageSize: 200,
        searchStr: "",
      };
      getUserList(params).then((res) => {
        if (res.code === 10000) {
          this.userList = res.data.records;
        }
      });
    },
  },
  mounted() {
    this.init();
    this.authInit();
    this.userInit();
  },
};
</script>

<style scoped>
.box {
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  padding: 20px;
}
</style>
