<template>
  <div class="processPermission">
    <div class="processPermission_show_box" v-if="powers.some((i) => i == '001')">
      <ul class="role-list fl">
        <p class="role-list__title">角色列表</p>
        <p
          v-if="roleList.length == 0"
          style="line-height: 60px; text-align: center; color: #909399"
        >
          暂无数据
        </p>
        <li
          v-for="(item, index) in roleList"
          :key="'role' + index"
          class="role-list__item"
          :class="{ active: item.id == roleActive.id }"
          @click="!isBtnDisabled && switchRoleHandle(item)"
        >
          {{ item.role_name }}
          <i v-if="isBtnDisabled && item.id == roleActive.id" class="el-icon-loading" />
        </li>
      </ul>
      <div class="rule-view fr">
        <div class="rule-list">
          <el-row v-for="(item, index) in perActionList" :key="'menu' + item.id + index">
            <el-col class="title" :span="24">
              <span>{{ item.process_name }}</span>
            </el-col>
            <el-col class="main clear" :span="24">
              <div class="main-title fl">
                <el-checkbox
                  v-model="item.checkAll"
                  @change="handleCheckAllChange($event, index, item)"
                  :indeterminate="indeterminateCheck(item)"
                  :disabled="!powers.some((it) => it == '008')"
                  >全选</el-checkbox
                >
              </div>
              <div class="main-item fl">
                <el-checkbox-group
                  v-model="item.checkList"
                  @change="handleCheckedGroupChange($event, index, item)"
                  :disabled="!powers.some((it) => it == '008')"
                >
                  <el-checkbox
                    @change="handleCheckedChange($event, subitem.id, index, item)"
                    v-for="(subitem, subIndex) in item.child"
                    :key="'checkItem' + subitem.id"
                    :label="subitem.id"
                    >{{ subitem.status_name }}</el-checkbox
                  >
                </el-checkbox-group>
              </div>
            </el-col>
          </el-row>
        </div>
      </div>
      <div class="rule-bottom fr">
        <el-button
          size="small"
          type="primary"
          v-if="powers.some((i) => i == '008')"
          :disabled="isBtnDisabled"
          @click="save()"
          >提 交</el-button
        >
      </div>
    </div>
    <div v-else>
      <no-auth></no-auth>
    </div>
  </div>
</template>
<script>
import asyncRequest from "@/apis/service/interest/processPermission";
import resToken from "@/mixins/resToken";
export default {
  name: "processPermission",
  mixins: [resToken],
  data() {
    return {
      ruleForm: {},
      // 按钮是否可点击
      isBtnDisabled: false,
      // 当前角色
      roleActive: {},
      processPermissionChange: [],
      // 角色列表
      roleList: [],
      rules: [],
      // 功能权限列表
      perActionList: [],
      processPermission: [], // 功能数据
      private_data: [], //私有数据菜单ID
      private_field: [],
    };
  },
  computed: {
    powers() {
      const tran =
        this.$store.getters.btnList.find(
          (item) => item.menu_route === "processPermission"
        ) || {};
      const { action } = tran ?? {};
      return action ?? [];
    },
    indeterminateCheck() {
      return (item) => {
        // 选中子节点的数量
        const selectItemLength = item.child.filter(
          (filitem) =>
            item.checkList.findIndex((finditem) => finditem === filitem.id) > -1
        ).length;
        // 未选中子节点的数量
        const noSlectItemLength = item.child.filter(
          (filitem) =>
            item.checkList.findIndex((finditem) => finditem === filitem.id) == -1
        ).length;
        // // 当前节点的index
        // 存在选中子节点且存在未选中子节点为中间态
        return selectItemLength > 0 && noSlectItemLength > 0;
      };
    },
  },
  mounted() {
    this.initperActionList();
  },

  methods: {
    // 全选/全不选
    handleCheckAllChange(checkAll, index, item) {
      this.perActionList[index].checkAll = checkAll;
      this.$set(this.perActionList, index, item);
      this.perActionList[index].child.forEach((element) => {
        const findindex = this.perActionList[index].checkList.findIndex(
          (findItem) => findItem === element.id
        );
        if (checkAll && findindex == -1) {
          this.perActionList[index].checkList.push(element.id);
        } else if (!checkAll && findindex > -1) {
          this.perActionList[index].checkList.splice(findindex, 1);
        }
      });
    },

    // 复选框组内的选中/不选中
    handleCheckedGroupChange(event, index, item) {
      this.perActionList[index].checkAll = this.perActionList[index].child.every(
        (evitem) =>
          this.perActionList[index].checkList.findIndex(
            (finditem) => finditem === evitem.id
          ) > -1
      );
      this.$set(this.perActionList, index, item);
    },

    // 多选框选中/不选中
    handleCheckedChange(checked, id, index, item) {
      if (checked) {
        this.perActionList[index].checkList.indexOf(id) == -1 &&
          this.perActionList[index].checkList.push(id);
      } else {
        const find = this.perActionList[index].checkList.findIndex((e) => e == id);
        if (find > -1) {
          this.perActionList[index].checkList.splice(find, 1);
        }
        this.perActionList[index].checkAll = false;
      }
      this.$set(this.perActionList, index, item);
      // console.log(this.perActionList[index]);
    },

    // 切换角色
    switchRoleHandle(item) {
      this.roleActive = Object.assign({}, item);
      this.$nextTick(async () => {
        await this.refreshRoleDetail(item.id);
      });
    },
    // 保存
    async save() {
      let arr = [];
      this.perActionList.forEach((x) => {
        arr.push(...x.checkList);
      });

      if (arr.length === 0) {
        this.$message.warning("请选择节点!");
      } else {
        const model = {
          roleid: this.roleActive.id,
          action_data: arr,
        };

        const loadding = this.$loading();
        const { code, data, message } = await asyncRequest.update(model);
        if (code === 0) {
          this.$notify.success({
            title: "保存成功！",
            message: "",
          });
        } else if (code >= 100 && code <= 104) {
          await this.logout();
        } else {
          this.$message.warning(message);
        }
        loadding.close();
      }
    },
    // 刷新角色详情
    async refreshRoleDetail(roleid) {
      if (this.isBtnDisabled) return;
      this.isBtnDisabled = true;

      const { code, data, message } = await asyncRequest.detail({ roleid: roleid });

      if (code === 0) {
        const { action_data } = data ?? {};
        this.ruleForm = data;
        this.action_data_list = action_data ?? [];
        this.refreshRoleCheckAllStatus();
      } else if (code >= 100 && code <= 104) {
        await this.logout();
      } else {
        this.$message.warning(message);
      }
      this.isBtnDisabled = false;
    },
    // 初始化功能权限列表
    async initperActionList() {
      const { code, data, message } = await asyncRequest.actionList({});
      if (code === 0) {
        this.rules = data;
        await this.initRoleList();
      } else if (code >= 100 && code <= 104) {
        this.rules = [];
        await this.logout();
      } else {
        this.rules = [];
        this.$message.warning(message);
      }
    },
    // 初始化角色列表
    async initRoleList() {
      const res = await asyncRequest.getRole({});
      if (res && res.code === 0 && res.data) {
        this.roleList = [].concat(res.data);
        if (this.roleList.length > 0) {
          await this.switchRoleHandle(this.roleList[0]);
        } else if (res && res.code >= 100 && res.code <= 104) {
          await this.logout();
        } else {
          this.$message.warning(res.message);
        }
      }
    },
    // 刷新选择状态
    refreshRoleCheckAllStatus() {
      const list = JSON.parse(JSON.stringify(this.rules));
      let arr = list.filter((item) => item.child && item.child.length > 0);
      arr = arr.map((x) => {
        x.checkAll = false;
        x.checkList = [];
        x.child.map((y) => {
          y.id += "";
          return y;
        });
        return x;
      });
      this.perActionList = arr;
      console.log(this.perActionList);
      console.log(this.action_data_list);
      this.perActionList.forEach((x, xi) => {
        if (x.child && x.child.length > 0) {
          x.child.forEach((y, yi) => {
            const Aindex = this.action_data_list.findIndex((a) => a === y.id);
            if (Aindex !== -1) {
              x.checkList.push(this.action_data_list[Aindex]);
            }
            if (x.child.length === x.checkList.length) {
              x.checkAll = true;
            }
          });
        }
        this.$set(this.perActionList, xi, x);
      });
    },
  },
};
</script>
<style lang="scss" scoped>
@import "~@/styles/mixin.scss";
.processPermission {
  position: relative;
  width: 100%;
  height: 100%;
  overflow: hidden;

  .processPermission_show_box {
    // position: relative;
    // height: calc(100% - 50px);
    // min-height: calc(100% - 50px);

    display: relative;
    width: 100%;
    height: calc(100vh - 50px);
    overflow: hidden;
    text-align: left;
    //左侧
    .role-list {
      height: 100%;
      overflow-y: auto;
      width: 200px;
      padding: 8px 16px;
      min-height: 100%;
      flex-shrink: 0;
      border-right: 2px solid #dfe6ec;
      @include scrollBar();
      &::after {
        content: "";
        position: absolute;
        top: 0;
        right: 0;
        height: 100%;
        width: 2px;
        background-color: #e4e7ed;
        z-index: 1;
      }
      .role-list__title {
        color: #b4b6c0;
        line-height: 32px;
      }
      .role-list__item {
        position: relative;
        white-space: nowrap;
        text-overflow: ellipsis;
        overflow: hidden;
        height: 32px;
        line-height: 32px;
        padding-left: 8px;
        color: rgb(48, 49, 51);
        cursor: pointer;
        i {
          position: absolute;
          right: 0;
          line-height: 32px;
        }
      }
      .role-list__item.active {
        color: #6954f0;
        background: #f7f7f7;
      }
    }
    //右侧
    .rule-view {
      height: calc(100% - 50px);
      width: calc(100% - 200px);
      overflow-y: auto;
      @include scrollBar();
      .rule-list {
        border-right: 1px solid #dfe6ec;
        .title {
          padding: 18px 18px 12px 18px;
          border-bottom: 1px dashed #dfe6ec;
          font-size: 15px;
          color: #000;
        }
        .main {
          padding: 18px 18px 12px 18px;
          border-bottom: 1px solid #dfe6ec;
        }
        .main-title {
          width: 80px;
        }
        .main-item {
          width: calc(100% - 80px);
        }
      }
    }
    .rule-bottom {
      padding: 10px 18px 8px 0;
      background: #fff;
      width: calc(100% - 200px);
      position: absolute;
      text-align: right;
      bottom: 0;
      right: 0;
      &::before {
        content: "";
        position: absolute;
        top: 0;
        right: 0;
        height: 2px;
        width: 100%;
        background-color: #e4e7ed;
        z-index: 1;
      }
    }
  }
}
</style>
