<template>
  <div id="roleManagement">
    <!-- <search-box :formList="formList" @search="search" @init="init" /> -->
    <table-list
      :tableSets="tableSet"
      :tableData="tableData"
      :navText="navText"
      @addClick="addClick"
      :loading="loading"
    >
      <template slot="btn" slot-scope="props">
        <!-- <el-button type="text" @click="addClick(props.scope.row, 2)"
          >详情</el-button
        > -->
        <el-button type="text" @click="addClick(props.scope.row, 0)"
          >编辑</el-button
        >
        <el-button type="text" @click="del(props.scope.row)">删除</el-button>
      </template>
    </table-list>
    <pagination
      :total="total"
      :pageSize="pageSize"
      :currentPage="currentPage"
      @handleSizeChange="handleSizeChange"
      @handleCurrentChange="handleCurrentChange"
    />
    <el-dialog
      @closed="loadingClose"
      :visible.sync="dialogVisible"
      width="860px"
      :show-close="false"
      :close-on-click-modal="false"
    >
      <div slot="title" class="hearders">
        <div class="leftTitle">
          {{ statusPop === 1 ? "添加" : statusPop === 0 ? "修改" : "详情" }}
        </div>
        <div class="rightBoxs">
          <img src="@/assets/images/Close@2x.png" alt="" @click="close" />
        </div>
      </div>
      <div>
        <el-row :gutter="10">
          <el-form
            label-position="right"
            label-width="100px"
            :model="listData"
            :rules="rules"
            ref="listData"
            ><el-col
              :span="12"
              v-for="(items, indexs) in listitem"
              :key="indexs"
            >
              <el-form-item :label="items.label" :prop="items.prop">
                <el-radio-group
                  v-if="items.scope === 'status'"
                  v-model="listData[items.prop]"
                >
                  <el-radio
                    v-for="(item, index) in items.options"
                    :key="index"
                    :label="item.value"
                    :disabled="statusPop === 2"
                    >{{ item.label }}</el-radio
                  >
                </el-radio-group>
                <div v-else-if="items.scope === 'tree'">
                  <el-checkbox
                    v-model="menuExpand"
                    @change="handleCheckedTreeExpand($event, 'menu')"
                    >展开/折叠</el-checkbox
                  >
                  <el-checkbox
                    v-model="menuNodeAll"
                    @change="handleCheckedTreeNodeAll($event, 'menu')"
                    >全选/全不选</el-checkbox
                  >
                  <!-- <el-checkbox
                v-model="listData.menuCheckStrictly"
                @change="handleCheckedTreeConnect($event, 'menu')"
                >父子联动</el-checkbox
              > -->
                  <el-tree
                    class="tree-border"
                    :data="menuOptions"
                    show-checkbox
                    ref="menu"
                    node-key="id"
                    empty-text="加载中，请稍后"
                    :props="defaultProps"
                  ></el-tree>
                </div>
                <div v-else-if="items.scope === 'treeInfo'">
                  <el-checkbox
                    v-model="menuExpandInfo"
                    @change="handleCheckedTreeExpandInfo($event, 'info')"
                    >展开/折叠</el-checkbox
                  >
                  <el-checkbox
                    v-model="menuNodeAllInfo"
                    @change="handleCheckedTreeNodeAllInfo($event, 'info')"
                    >全选/全不选</el-checkbox
                  >
                  <!-- <el-checkbox
                v-model="listData.menuCheckStrictly"
                @change="handleCheckedTreeConnect($event, 'menu')"
                >父子联动</el-checkbox
              > -->
                  <!-- :check-strictly="!listData.menuCheckStrictly"👇 -->
                  <el-tree
                    class="tree-border"
                    :data="menuOptionsInfo"
                    show-checkbox
                    ref="info"
                    node-key="onlyId"
                    empty-text="加载中，请稍后"
                    :props="defaultProps"
                  ></el-tree>
                </div>
                <el-input
                  :disabled="statusPop === 2"
                  v-else-if="items.scope === 'textarea'"
                  type="textarea"
                  v-model="listData[items.prop]"
                ></el-input>
                <el-input-number
                  style="width: 100%"
                  :disabled="statusPop === 2"
                  v-else-if="items.scope === 'numberIndex'"
                  v-model="listData[items.prop]"
                  controls-position="right"
                  :min="0"
                  :max="99"
                ></el-input-number>
                <el-input
                  :disabled="statusPop === 2"
                  v-else
                  v-model="listData[items.prop]"
                ></el-input>
              </el-form-item> </el-col></el-form
        ></el-row>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="close">取 消</el-button>
        <el-button
          type="primary"
          :loading="disabledBtn"
          v-if="statusPop !== 2"
          @click="submit('listData')"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import searchBox from "@/components/searchBox";
import tableList from "@/components/tableList";
import pagination from "@/components/pagination";
export default {
  name: "RoleManagement",
  components: { searchBox, tableList, pagination },
  data() {
    return {
      disabledBtn: false,
      keys: [],
      loading: false, //当前表单加载是否加载动画
      navText: {
        title: "角色管理",
        index: 0,
        ch: "种",
        num: false,
        choice: false,
        addHide: false,
        backFatherBtn: {
          status: false,
          title: "未定义",
        },
      },
      //搜索
      formList: [
        {
          label: "角色名称",
          prop: "roleName",
          placeholder: "请输入角色名称",
        },
        {
          label: "权限字符",
          prop: "roleKey",
          placeholder: "请输入权限字符",
        },
        {
          label: "状态",
          prop: "status",
          placeholder: "请选择状态",
          scope: "select",
          options: [
            {
              label: "启用",
              value: "1",
            },
            {
              label: "停用",
              value: "0",
            },
          ],
        },
      ],
      // 表单
      tableSet: [
        {
          label: "角色编号",
          prop: "roleId",
          hidden: true,
        },
        {
          label: "角色名称",
          prop: "roleName",
          hidden: true,
        },
        {
          label: "权限字符",
          prop: "roleKey",
          hidden: true,
        },
        {
          label: "显示顺序",
          prop: "roleSort",
          hidden: true,
        },
        {
          label: "状态",
          prop: "status",
          hidden: true,
          scope: "status",
        },
        {
          label: "创建时间",
          prop: "createTime",
          hidden: true,
        },
      ],
      tableData: [], //表单数据
      total: 0, //一共多少条
      pageSize: 10, //每页多少条数据
      currentPage: 1, //当前页码
      menuExpand: false,
      menuNodeAll: false,
      menuExpandInfo: false,
      menuNodeAllInfo: false,
      defaultProps: {
        children: "children",
        label: "label",
      },
      menuOptions: [], //菜单列表
      menuOptionsInfo: [], //数据池列表
      // 弹窗字段
      listitem: [
        {
          label: "角色名称",
          prop: "roleName",
        },
        {
          label: "权限字符",
          prop: "roleKey",
        },
        {
          label: "角色顺序",
          prop: "roleSort",
          scope: "numberIndex",
        },
        {
          label: "状态",
          prop: "status",
          scope: "status",
          options: [
            {
              label: "启用",
              value: "1",
            },
            {
              label: "关闭",
              value: "0",
            },
          ],
        },
        {
          label: "菜单权限",
          prop: "menuIds",
          scope: "tree",
        },
        {
          label: "数据池权限",
          prop: "keys",
          scope: "treeInfo",
        },
        {
          label: "备注",
          prop: "remark",
          scope: "textarea",
        },
      ],
      //   弹窗数据
      listData: {},
      statusPop: -1,
      dialogVisible: false,
      //表单验证
      rules: {
        roleName: [
          { required: true, message: "请输入岗位名称", trigger: "blur" },
        ],
        roleKey: [
          { required: true, message: "请输入岗位编码", trigger: "blur" },
        ],
        roleSort: [
          { required: true, message: "请输入岗位顺序", trigger: "blur" },
        ],
        status: [{ required: true, message: "请选择状态", trigger: "change" }],
        // remark: [{ required: true, message: "请填写备注", trigger: "blur" }],
      },
    };
  },
  mounted() {
    this.search();
  },
  methods: {
    loadingClose() {
      this.disabledBtn = false;
    },
    search(v) {
      this.loading = true;
      if (v === undefined) {
        v = {
          statusArray: "0,1",
          pageSize: this.pageSize,
          pageNum: this.currentPage,
        };
      }
      var data = {
        roleKey: v.roleKey || "",
        roleName: v.roleName || "",
        statusArray: v.status === undefined ? "0,1" : v.status,
        pageSize: this.pageSize,
        pageNum: this.currentPage,
      };
      this.$api
        .obtainRoleList(data)
        .then((res) => {
          this.tableData = res.rows.sort(this.sortBy("postSort", true));
          this.total = res.total;
          this.navText.index = res.total;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    init() {
      this.search();
    },
    del(v) {
      this.$confirm("此操作将删除该岗位, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          var data = JSON.parse(JSON.stringify(v));
          data.menuIds = [];
          data.status = "-1";
          this.$api.editRole(data).then((res) => {
            if (res.code === 200) {
              this.$message.success("删除成功");
              this.search();
              this.$store.commit("EDICROLELIST");
              this.dialogVisible = false;
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    addClick(v, int) {
      var self = this;
      self.initData();
      if (v === undefined) {
        self.statusPop = 1;
        self.getMenuList();
        self.getMenuListInfo();
        self.dialogVisible = true;
        self.$nextTick(() => {
          self.$refs.listData.clearValidate();
        });
      } else {
        self.statusPop = int;
        var data = v.roleId;
        self.$api.obtainRoleId(data).then(async (res) => {
          if (res.code === 200) {
            const getCheckList = await self.getUserMenuList(v.roleId);
            self.menuOptions = getCheckList.menus;
            getCheckList.checkedKeys.forEach((v) => {
              self.$nextTick(() => {
                self.$refs.menu[0].setChecked(v, true, false);
              });
            });
            self.listData = res.data;
            self.dialogVisible = true;
            await self.getMenuListInfo();
            if (res.data.businessIds) {
              res.data.businessIds.forEach((v) => {
                self.$nextTick(() => {
                  self.$refs.info[0].setChecked("yw-" + v, true, false);
                });
              });
            }
            self.$nextTick(() => {
              self.$refs.listData.clearValidate();
            });
          }
        });
      }
    },
    getMenuList() {
      this.$api.enutreeselect().then((res) => {
        this.menuOptions = res.data;
      });
    },
    getMenuListInfo() {
      var self = this;
      return new Promise((resolve, reject) => {
        var ary1 = [];
        self.$api.inquireCourseEducationType({ status: 1 }).then((res) => {
          res.rows.forEach((item) => {
            item.label = item.educationName;
            item.onlyId = "jy-" + item.id;
            item.children = [];
          });
          ary1 = res.rows;
          self.$api.inquirebusinessList({ status: 1 }).then((result) => {
            result.rows.forEach((items) => {
              items.label = items.projectName + items.businessName;
              items.onlyId = "yw-" + items.id;
              ary1.forEach((ite) => {
                if (items.educationId === ite.id) {
                  ite.children.push(items);
                }
              });
            });
            self.menuOptionsInfo = ary1;
            resolve();
          });
        });
      });
    },
    getUserMenuList(v) {
      return new Promise((resolve, reject) => {
        this.$api.roleMenuTreeselect(v).then((result) => {
          resolve(result);
        });
      });
    },
    submit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.rulesTableSumbit();
        } else {
          return false;
        }
      });
    },
    rulesTableSumbit() {
      this.disabledBtn = true;
      this.listData.menuIds = this.getMenuAllCheckedKeys();
      this.listData.businessIds = this.getMenuAllCheckedKeysInfo();
      var data = this.listData;
      if (this.statusPop === 1) {
        this.$api
          .addRole(data)
          .then((res) => {
            if (res.code === 200) {
              this.$message.success("新增成功");
              this.search();
              this.$store.commit("EDICROLELIST");
              this.dialogVisible = false;
            }
          })
          .catch(() => {
            this.disabledBtn = false;
          });
      }
      if (this.statusPop === 0) {
        this.$api
          .editRole(data)
          .then((res) => {
            if (res.code === 200) {
              this.$message.success("修改成功");
              this.search();
              this.$store.commit("EDICROLELIST");
              this.dialogVisible = false;
            }
          })
          .catch(() => {
            this.disabledBtn = false;
          });
      }
    },
    close() {
      this.initData();
      this.dialogVisible = false;
    },
    initData() {
      this.menuExpand = false;
      this.menuNodeAll = false;
      this.listData = {
        roleId: undefined,
        roleName: undefined,
        roleKey: undefined,
        roleSort: 0,
        status: "",
        menuIds: [],
        deptIds: [],
        menuCheckStrictly: true,
        deptCheckStrictly: true,
        remark: undefined,
      };
    },
    sortBy(attr, rev) {
      //第二个参数没有传递 默认升序排列
      if (rev == undefined) {
        rev = 1;
      } else {
        rev = rev ? 1 : -1;
      }

      return function (a, b) {
        a = a[attr];
        b = b[attr];
        if (a < b) {
          return rev * -1;
        }
        if (a > b) {
          return rev * 1;
        }
        return 0;
      };
    },
    // 树权限（展开/折叠）
    handleCheckedTreeExpand(value, type) {
      if (type == "menu") {
        let treeList = this.menuOptions;
        for (let i = 0; i < treeList.length; i++) {
          this.$refs.menu[0].store.nodesMap[treeList[i].id].expanded = value;
        }
      }
    },
    // 树权限（全选/全不选）
    handleCheckedTreeNodeAll(value, type) {
      console.log(this.$refs.menu);
      if (type == "menu") {
        this.$refs.menu[0].setCheckedNodes(value ? this.menuOptions : []);
      }
    },
    // 数据池树权限（展开/折叠）
    handleCheckedTreeExpandInfo(value, type) {
      console.log(this.$refs.info);
      if (type == "info") {
        let treeList = this.menuOptionsInfo;
        for (let i = 0; i < treeList.length; i++) {
          this.$refs.info[0].store.nodesMap[treeList[i].onlyId].expanded =
            value;
        }
      }
    },
    // 数据池树权限（全选/全不选）
    handleCheckedTreeNodeAllInfo(value, type) {
      console.log(this.$refs.info);
      if (type == "info") {
        this.$refs.info[0].setCheckedNodes(value ? this.menuOptionsInfo : []);
      }
    },
    // 树权限（父子联动）
    handleCheckedTreeConnect(value, type) {
      if (type == "menu") {
        console.log(value);
        this.listData.menuCheckStrictly = value ? true : false;
      }
    },
    // 所有菜单节点数据
    getMenuAllCheckedKeys() {
      // 目前被选中的菜单节点
      let checkedKeys = this.$refs.menu[0].getCheckedKeys();
      // 半选中的菜单节点
      let halfCheckedKeys = this.$refs.menu[0].getHalfCheckedKeys();
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
      return checkedKeys;
    },
    getMenuAllCheckedKeysInfo() {
      // 目前被选中的菜单节点
      let checkedKeys = this.$refs.info[0].getCheckedKeys();
      // 半选中的菜单节点
      let halfCheckedKeys = this.$refs.info[0].getHalfCheckedKeys();
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
      let ary = [];
      checkedKeys.forEach((item) => {
        var ast = item.split("-");
        if (ast[0] === "yw") {
          ary.push(parseInt(ast[1]));
        }
      });
      return ary;
    },
    handleSizeChange(v) {
      this.pageSize = v;
      this.currentPage = 1;
      this.search();
    },
    handleCurrentChange(v) {
      this.currentPage = v;
      this.search();
    },
  },
};
</script>

<style lang="less" scoped>
/deep/.el-button {
  border-radius: 8px;
}
/deep/.el-dialog {
  border-radius: 8px;
  .el-dialog__header {
    padding: 0;
    .hearders {
      height: 40px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 0px 18px 0px 20px;
      border-bottom: 1px solid #e2e2e2;
      .leftTitle {
        font-size: 14px;
        font-weight: bold;
        color: #2f4378;
      }
      .rightBoxs {
        display: flex;
        align-items: center;
        img {
          width: 14px;
          height: 14px;
          margin-left: 13px;
          cursor: pointer;
        }
      }
    }
  }
  .el-dialog__footer {
    padding: 0;
    .dialog-footer {
      padding: 0px 40px;
      height: 70px;
      border-top: 1px solid #e2e2e2;
      display: flex;
      align-items: center;
      justify-content: flex-end;
    }
  }
}
.imgBox {
  width: 100%;
  // height: 210px;
  border: 1px solid #e2e2e2;
  border-radius: 8px;
  padding: 8px 8px 3px;
  display: flex;
  flex-direction: column;
  align-items: center;
  .imgLabel {
    flex: 1;
    width: 100%;
    border: 1px dotted #e2e2e2;
    color: #999;
    font-size: 14px;
    cursor: pointer;
    border-radius: 8px;
    .msPhoto {
      display: flex;
      justify-content: center;
      align-items: center;
      max-width: 100%;
      max-height: 270px;
      img {
        max-width: 100%;
        max-height: 270px;
      }
    }
    .imgbbx {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      width: 100%;
      height: 100%;
      i {
        font-weight: bold;
        margin: 14px 0;
        font-size: 24px;
      }
    }
  }
  p {
    margin: 5px 0px;
  }
}
.tree-border {
  max-height: 450px;
  overflow: auto;
  margin-top: 5px;
  border: 1px solid #e5e6e7;
  background: #ffffff none;
  border-radius: 4px;
}
</style>

