<!-- 职务权限模块 -->
<template>
  <div>
    <div class="org-box">
      <!--组织架构两个导航-->
      <div class="org-nav">
        <div class="org-title">
          <!--<router-link v-if="serviceType == 'board' || serviceType == 'both'" to="/organization">岸基成员管理</router-link>-->
          <!--<router-link v-if="serviceType == 'ship' || serviceType == 'both'" to="/organizationShip">船端成员管理</router-link>-->
          <!--<router-link v-if="serviceType == 'board' || serviceType == 'both'" to="/jobAuthority" class="activeLink">岸基权限管理</router-link>-->
          <!--<router-link v-if="serviceType == 'ship' || serviceType == 'both'" to="/jobAuthorityShip">船端权限管理</router-link>-->

          <router-link to="/organization">岸基成员管理</router-link>
          <router-link to="/organizationShip">船端成员管理</router-link>
          <router-link to="/jobAuthority" class="activeLink">岸基权限管理</router-link>
          <router-link to="/jobAuthorityShip">船端权限管理</router-link>

        </div>
      </div>
      <!--职责权限管理主体-->
      <div class="org-main">
        <div class="organization-container">
          <!--内容树结构-->
          <yh-tree ref="nodeClick" @treeClick="handleClickTree" @treeAdd="treeAdd" />
          <!--设置职责范围-->
          <div class="organization-box">
            <div class="label-box">
              <span class="label-title">{{ companyName }}</span>
            </div>
            <div class="show-box">
              <!--共通按钮-->
              <div class="button-common two-text">
                <el-button type="primary" @click="goSave">保存</el-button>
                <el-button @click="goRestore">恢复</el-button>
                <el-button @click="goBack">取消</el-button>
              </div>
              <!--职务全选多选-->
              <div class="job-scope">
                <div class="job-select">
                  <span class="select-title">所属部门：</span>
                  <el-select
                    v-model="deptId"
                    placeholder="请选择"
                    @change="handleJumpRoleDeptChange"
                  >
                    <el-option
                      v-for="item in departmentList"
                      :key="item.index"
                      :label="item.label"
                      :value="item.id"
                    />
                  </el-select>
                </div>

                <div class="job-select">
                  <span class="select-title">职务：</span>
                  <el-select
                    v-model="roleId"
                    placeholder="请选择"
                    @change="searchPosData"
                  >
                    <el-option
                      v-for="item in positionList"
                      :key="item.roleId"
                      :label="item.roleName"
                      :value="item.roleId"
                    />
                  </el-select>
                </div>

                <el-menu class="el-menu-vertical-demo" ref="jobScopeMenu">
                  <el-submenu
                    v-for="(item,val) in queryList"
                    :key="val"
                    :index="item.pluginId"
                    class="one-menu"
                  >
                    <template slot="title">
                      <i class="el-icon-caret-right"></i>
                      <span>{{ item.pluginName }}</span>
                    </template>
                    <el-submenu
                      v-for="service in item.activatedServices"
                      :key="service.serviceId"
                      :index="service.serviceId"
                      class="two-menu"
                    >
                      <template slot="title">
                        <i class="el-icon-caret-right-two-menu" />
                        {{ service.serviceName }}
                        <div class="select-all" @click.stop="selectAll(service)">反选</div>
                      </template>
                      <el-menu-item
                        v-for="feature in service.features"
                        :key="feature.featureId"
                        :index="feature.featureId"
                      >
                        <el-checkbox
                          v-model="feature.checked"
                        >{{ feature.featureName }}</el-checkbox>
                      </el-menu-item>
                    </el-submenu>
                  </el-submenu>
                </el-menu>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import { mapGetters } from 'vuex';
import yhTree from '../../layout/components/tree.vue';
import {
  getRoleInfo,
  getlist,
  bindResources
} from '../../api/jobAuthority/jobScope';
import { addCreate } from '../../api/organization/organization';
import {
  getTreeList,
} from '../../api/organization/tree';
import {
  findRoles
} from '../../api/jobAuthority/jobAuthority';

export default {
  name: 'JobScope',
  components: {
    yhTree
  },
  data() {
    return {
      compId: localStorage.getItem('enterprise-front-companyId'),
      centerDialogVisible: false,
      /* 添加部门弹窗 */
      addSection: {
        compId: localStorage.getItem('enterprise-front-companyId'),
        deptName: '',
        parentDeptId: ''
      },
      positionList: [], // 职务下拉
      departmentList: [], // 部门下拉
      queryList: [], // 获取插件列表
      headState: '/organization',
      jumpRole: {}, // 初始化根据跳转 获取角色详情
      treeData: [], // 展开成一维数组，并加父级属性标识
      roleId: '', // 跳转传过来的角色id
      deptId: '', // 跳转传过来的部门id
      companyName: localStorage.getItem('enterprise-front-companyName') // 获取公司名称
    };
  },
  computed: {
    ...mapGetters({
      serviceType: 'serviceType'
    })
  },
  created() {
    this.getDeptInfo();
    this.getJumpRoleInfo();
    this.getRoleList();
  },
  methods: {
    /* 点击左侧树 获得部门信息 */
    handleClickTree(treeClickData) {
      this.deptId = treeClickData.id;
      this.getJumpChangRoleList();
    },
    // 部门下拉选change
    handleJumpRoleDeptChange(id) {
      this.deptId = id;
      this.getJumpChangRoleList();
    },
    searchPosData(id) {
      this.roleId = id;
      this.getJumpRoleInfo();
    },
    /* 获取当前角色详情 */
    getJumpRoleInfo() {
      const data = {
        roleId: this.roleId ? this.roleId : localStorage.getItem('enterprise-front-roleId')
      };
      getRoleInfo(data).then((response) => {
        this.jumpRole = response;
        this.getPluginList();
      });
    },
    /* 获取插件列表 */
    getPluginList() {
      getlist({
        tenantId: localStorage.getItem('enterprise-front-tenantId')
      }).then((response) => {
        this.queryList = response;
        this.setDefaultChecked(this.queryList);
      });
    },
    setDefaultChecked(nodeList) {
      for (const item of nodeList) {
        if (!item.features) {
          this.setDefaultChecked(item.activatedServices);
        } else {
          item.features.forEach((feature) => {
            // 之所以这么写，是因为，feature 本没有checked属性
            this.$set(feature, 'checked', this.jumpRole.resources.some(resource => resource.resourceId === feature.featureId))
          });
        }
      }
    },
    // 全选
    selectAll(service) {
      service.features.forEach((item) => {
        item.checked = !item.checked;
      });
      this.$refs.jobScopeMenu.open(service.serviceId)
    },
    /* 取消按钮 */
    goBack() {
      this.$confirm('页面未保存，是否放弃提交', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$router.push({
          path: '/jobAuthority',
          name: 'jobAuthority'
        });
      }).catch(() => {});
    },
    /* 恢复按钮 */
    goRestore() {
      this.getPluginList();
    },
    /* 保存 为角色设置职责范围 */
    deepFind(node, checkedList) {
      if (!node.features) {
        node.activatedServices.forEach((item) => {
          this.deepFind(item, checkedList);
        })
      } else {
        node.features.forEach((item) => {
          if (item.checked) {
            checkedList.push({ resourceId: item.featureId })
          }
        })
      }
    },
    goSave() {
      const checkedList = []
      this.queryList.forEach((item) => {
        this.deepFind(item, checkedList);
      })
      const data = {
        roleId: this.roleId ? this.roleId : localStorage.getItem('enterprise-front-roleId'), // 角色ID
        resources: checkedList
      };
      bindResources(data).then(() => {
        this.$message({
          message: '保存成功',
          type: 'success',
          showClose: true,
        });
        this.$router.push({
          path: '/jobAuthority',
          name: 'jobAuthority'
        });
      });
    },
    /* 职责权限下的部门列表 */
    getDeptInfo() {
      getTreeList({
        compId: this.compId
      }).then((response) => {
        this.getDeptData(response);
      });
    },
    getDeptData(deptTree) {
      if (!deptTree || deptTree == null || deptTree.length === 0) {
        return;
      }
      for (let i = 0; i < deptTree.length; i++) {
        const item = deptTree[i];
        this.departmentList.push({
          id: item.id,
          label: item.label
        });
        this.getDeptData(item.children);
        if (item.parentId === '-1') {
          this.departmentList.splice(i, 1);
        }
      }
    },
    /* 初始化获取下拉的角色列表 */
    getRoleList() {
      const data = {
        deptId: this.deptId ? this.deptId : localStorage.getItem('enterprise-front-deptId')
      };
      findRoles(data).then((response) => {
        this.positionList = response.records;
      });
    },
    /* 点击下拉中的部门 获取角色列表 */
    getJumpChangRoleList() {
      const data = {
        deptId: this.deptId ? this.deptId : localStorage.getItem('enterprise-front-deptId')
      };
      findRoles(data).then((response) => {
        this.positionList = response.records;
        if (this.positionList.length === 0) {
          this.$message({
            message: '请先添加职务',
            type: 'error',
            showClose: true,
          });
          this.$router.push({
            path: '/jobAuthority',
            name: 'jobAuthority'
          });
        } else {
          this.roleId = this.positionList[0].roleId;
          this.getJumpRoleInfo();
        }
      });
    },
    /* 树添加子部门 */
    treeAdd(s, d,) {
      this.addSection.parentDeptId = d.parentId;
      this.centerDialogVisible = true;
    },
    /* 添加子部门 */
    addDeptName(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          addCreate(this.addSection).then(() => {
            this.$message({
              message: '保存成功',
              type: 'success',
              showClose: true,
            });
            this.centerDialogVisible = false;
            location.reload();
          }).catch(() => {
            this.$message({
              message: '保存失败',
              type: 'error',
              showClose: true,
            });
            this.centerDialogVisible = true;
          });
        } else {
          this.$message({
            message: '带星号为必填项！',
            type: 'warning',
            showClose: true,
          });
          this.centerDialogVisible = true;
          return false;
        }
      });
    }
  }
};

</script>
<style scoped lang="scss">
.organization-box {
  .job-scope {
    height: calc(86vh - 130px);
    overflow-y: auto;
    .select-title {
      font-size: 12px;
      color: #666;
    }
    .job-select {
      display: inline-block;
      margin: 10px 0;
    }
    .job-select:nth-child(1) {
      display: inline-block;
      padding-right: 100px;
    }
  }

  .select-all{
    color: blue;
    display: inline-block;
    font-size: 12px;
    margin-left: 10px;
  }
}
.org-nav {
  background: #fff;
  position: fixed;
  width: 100%;
  height: 50px;
  z-index: 990;

  .org-title {
    height: 50px;
    line-height: 50px;
    font-size: 14px;
    width: 550px !important;
    margin: 0 auto;

    a {
      color: #666 !important;
    }

    a:nth-child(1) {
      padding-right: 0px !important;
      border-right: none !important;
    }

    a:nth-child(2) {
      padding-left: 0 !important;
    }

    .activeLink {
      font-weight: bold;
      color: #1D6CED !important;
    }
  }
}
</style>
