<template>
  <div style="height: 100%;">
    <div class="qxfpManage d-flex">
      <div class="leftContent">
        <div class="flex-row">
          <div class="font-size-20">组织机构</div>
          <!-- <el-button type="success" size="medium" @click="handleDeptAdd(0)">新建</el-button> -->
        </div>
        <div class="treeContent">
          <el-scrollbar class="sidebar-wrapper" style="height: 100%;">
            <el-tree :data="treeData" node-key="id" :props="defaultProps" default-expand-all :expand-on-click-node="false" highlight-current @node-click="handleNodeClick">
              <template #default="{ node, data }">
                <span class="custom-tree-node">
                  <span style="flex: 1;">{{ node.label }}</span>
                  <span class="operateDiv">
                    <el-button icon="el-icon-plus" type="text" @click="handleDeptAdd(data.id)"></el-button>
                    <el-button icon="el-icon-edit" type="text" @click="handleDeptEdit(data.id)"></el-button>
                    <el-button icon="el-icon-delete" type="text" @click="handleRemove(data.id)"></el-button>
                  </span>
                </span>
              </template>
            </el-tree>
          </el-scrollbar>
        </div>
      </div>
      <div class="rightContent">
        <el-scrollbar class="sidebar-wrapper" style="height: 100%;">
          <div class="flex-auto">
            <el-tabs v-model="activeName">
              <el-tab-pane label="组织机构成员" name="first">
                <el-table key="member" :data="memberData" row-key="name" max-height="auto" @selection-change="handleSelectionChange">
                  <el-table-column type="selection" width="55" />
                  <el-table-column label="编号" prop="user_id" width="120">
                  </el-table-column>
                  <el-table-column label="成员姓名" prop="user_realname" width="auto">
                    <template #default="{ row }">
                      <div style="display: flex;">
                        <span style="display: inline-block;width: 80px;">{{row.user_realname}}</span>
                        <span v-if="row.is_user_org_master==1" style="color: #409eff; display: flex;align-items: center;">
                          <i class="el-icon-user-solid"></i>
                          管理员
                        </span>
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" fixed="right" width="200">
                    <template #default="{ row }">
                      <el-link v-if="row.user_group_id!=100" type="primary" :underline="false" class="mr-4" @click="setLeader(row.user_id, true)">设置项目负责人</el-link>
                      <el-link v-else type="primary" :underline="false" class="mr-4" @click="setLeader(row.user_id, false)">取消项目负责人</el-link>
                      <el-link @click="memberSet(4, row)" type="primary" :underline="false">删除</el-link>
                    </template>
                  </el-table-column>
                </el-table>
                <footer class="flex-item-none" style="display: flex; justify-content: flex-end; margin-top: 30px">
                  <el-pagination background layout="total,prev, pager, next" :page-size="limit" :total="total" :current-page.sync="cur_page" @current-change="handleCurrentChange"></el-pagination>
                </footer>
              </el-tab-pane>
              <el-tab-pane label="权限设置" name="second">
                <el-table key="setting" :data="settingData" row-key="cmu_name" max-height="auto" default-expand-all>
                  <el-table-column label="功能菜单" prop="label" width="200"> </el-table-column>
                  <el-table-column label="勾选权限">
                    <template #default="{ row }">
                      <el-checkbox :disabled="deptId==''?true:false" v-for="(item, index) in row.checkList" :key="index" v-model="row.permission[item.key]" :label="item.name" @change="handlePermissionChange(row)" />
                    </template>
                  </el-table-column>
                </el-table>
              </el-tab-pane>
            </el-tabs>

            <div class="memberBtn" v-show="activeName=='first'">
              <el-button size="medium" type="success" @click="memberAdd">添加</el-button>
              <el-button size="medium" type="primary" @click="memberSet(1)">取消管理员</el-button>
              <el-button size="medium" type="primary" @click="memberSet(2)">设为管理员</el-button>
              <el-button size="medium" type="danger" @click="memberSet(3)">删除</el-button>
            </div>
          </div>
        </el-scrollbar>
      </div>
    </div>

    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" :width="dialogType==1?'600px':'1000px'" @close="handleClose">
      <zzjg-add v-if="dialogType==1" ref="zzjgAdd" :operateType="operateType" :currentId="deptId" @close="handleClose"></zzjg-add>
      <zzjgcy-add v-if="dialogType==2" ref="zzjgcyAdd" :currentId="deptId" @close="handleClose"></zzjgcy-add>
      <div slot="footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="formSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { orgListTree, orgList, orgDelete, userList, userEdit, userRemove, userMasterAdd, userMasterRemove, settingList, menuAdd } from "./api";
import ZzjgAdd from "./components/ZzjgAdd.vue";
import ZzjgcyAdd from "./components/ZzjgcyAdd.vue";
import { allRoutes } from "@/router/index.js";
export default {
  data() {
    return {
      treeData: [],
      defaultProps: {
        children: "children",
        label: "label",
      },
      deptId: 0,
      currentLevel: 0,
      operateType: "",
      dialogVisible: false,
      dialogTitle: "",
      dialogType: "",
      activeName: "second",
      multipleSelection: [],
      memberData: [],
      limit: 10,
      total: 0,
      cur_page: 1,
      allRoutes: allRoutes.filter(item => item.path != "*"),
      settingData: [],
      cpm_id: "80011",
      checkListMap: {
        show: '查看界面',
        export: '导出',
        import: '导入',
        add: '添加',
        delete: '删除',
        edit: '编辑',
        detail: '详情',
        audit: '审核'
      }
    }
  },
  components: { ZzjgAdd, ZzjgcyAdd },
  methods: {
    async initPermissionData() {
      let obj = {
        cpm_id: this.cpm_id,
        dept_id: this.deptId,
        keyname: "cmu_name"
      }
      let data = await settingList(obj);
      let cmu_name = data.cmu_name;

      const menu_left = [...this.allRoutes];
      this.initAnaPermission(menu_left, cmu_name);
      this.settingData = menu_left.map((child) => this.handleItem(child));
    },
    initAnaPermission(arg, cmu_name) {
      if (arg instanceof Array) {
        for (let i = 0; i < arg.length; i++) {
          this.initAnaPermission(arg[i], cmu_name);
        }
      } else {
        arg.permission = {};
        arg.meta = arg.meta || {};
        arg.meta.checkList = arg.meta.checkList || [];
        if (arg.meta.checkList.indexOf("show") == -1) {
          arg.meta.checkList.push("show");
        }
        arg.meta.checkList.map((item) => {
          arg.permission[item] = false;
          if (cmu_name != null) {
            for (let key in cmu_name) {
              if (key == arg.name) {
                let arr = cmu_name[key].split(",");
                arr.map((value) => {
                  if (item == value) {
                    arg.permission[item] = true;
                  }
                })
              }
            }
          }
        })
        if (arg.children && arg.children.length != 0) {
          arg.meta.title = arg.meta.title || arg.children[0].meta.title;
          for (let i = 0; i < arg.children.length; i++) {
            arg.children[i].meta = arg.children[i].meta || {};
            arg.children[i].meta.title = arg.children[i].meta.title || arg.meta.title;
            this.initAnaPermission(arg.children[i], cmu_name);
          }
        }
      }
    },
    handleItem(item) {
      const returnObj = {
        // id: item.id,
        label: item.meta.title,
        cmu_name: item.name,
        checkList: [],
        permission: item.permission
      };
      item.meta.checkList.map(val => {
        for (let key in this.checkListMap) {
          if (val == key) {
            returnObj.checkList.push({
              name: this.checkListMap[key],
              key: key
            })
          }
        }
      })
      if (Array.isArray(item.children)) {
        returnObj.children = item.children.map((child) => this.handleItem(child));
      }
      return returnObj;
    },
    async handlePermissionChange(data) {
      if (this.deptId == "") {
        this.$message.error("请先选择机构！");
        return;
      }
      let arr = [];
      for (let key in data.permission) {
        if (data.permission[key]) {
          arr.push(key);
        }
      }
      let obj = {
        user_org_menu: {
          cpm_id: this.cpm_id,
          cmu_name: data.cmu_name,
          dept_id: this.deptId,
          cmu_permission: arr.join(",")
        }
      }
      await menuAdd(obj);
      this.initPermissionData();
    },
    async initData() {
      let data = await orgListTree();
      this.treeData = data.one_info;
    },
    handleNodeClick({ id }) {
      this.deptId = id;
      this.initMemberData();
      this.initPermissionData();
    },
    handleDeptAdd(id) {
      this.operateType = 1;
      this.deptId = id;
      this.dialogVisible = true;
      this.dialogTitle = "新建";
      this.dialogType = 1;
    },
    handleDeptEdit(id) {
      this.operateType = 2;
      this.deptId = id;
      this.dialogVisible = true;
      this.dialogTitle = "编辑";
      this.dialogType = 1;
    },
    handleRemove(uo_id) {
      this.$confirm("是否确定删除当前数据？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          let res = await orgDelete({ uo_id });
          if (res) {
            this.$message.success("删除成功！");
            this.initData();
          }
        })
        .catch(() => { });
    },
    handleClose(dialogType, type) {
      this.dialogVisible = false;
      this.dialogType = "";
      this.operateType = "";
      if (dialogType == 1) {
        this.deptId = 0;
        this.$refs.zzjgAdd && this.$refs.zzjgAdd.resetForm();
        if (type == 1) {
          this.initData();
        }
      } else if (dialogType == 2) {
        this.$refs.zzjgcyAdd && this.$refs.zzjgcyAdd.resetForm();
        if (type == 1) {
          this.initMemberData();
        }
      }
    },
    formSubmit() {
      if (this.dialogType == 1) {
        this.$refs.zzjgAdd.commitData();
      } else if (this.dialogType == 2) {
        this.$refs.zzjgcyAdd.commitData();
      }
    },
    async initMemberData() {
      let obj = {
        admin: 1,
        all: 1,
        dept_id: this.deptId,
        page: this.cur_page,
        limit: this.limit,
      }
      let data = await userList(obj);
      if (data) {
        this.memberData = data.page_data;
        this.cur_page = Number(data.page_now);
        this.total = Number(data.total_rows);
      }
    },
    handleCurrentChange(val) {
      this.cur_page = val;
      this.initMemberData();
    },
    handleSelectionChange(val) {
      this.multipleSelection = [...val];
    },
    memberAdd() {
      if (this.deptId == 0) {
        this.$message.error("请先选择机构！");
        return;
      }

      this.dialogVisible = true;
      this.dialogTitle = "添加成员";
      this.dialogType = 2;
    },
    async memberSet(type, row) {
      if (this.multipleSelection.length == 0 && type != 4) {
        this.$message.error("请先选择数据");
        return
      }
      let arr = [];
      this.multipleSelection.map((item) => {
        arr.push(item.user_id);
      })
      let obj = {
        uo_id: Number(this.deptId),
        issubmit: "1"
      }
      if (type == 1) {
        obj.uo_master_user_ids = arr;
        await userMasterRemove(obj);
        this.$message.success("取消管理员成功！");
        this.initMemberData();
      } else if (type == 2) {
        obj.uo_master_user_ids = arr;
        await userMasterAdd(obj);
        this.$message.success("设为管理员成功！");
        this.initMemberData();
      } else if (type == 3) {
        obj.uo_user_ids = arr;
        let data = await userRemove(obj);
        if (data) {
          this.$message.success("删除成功！");
          this.initMemberData();
        }
      } else if (type == 4) {
        obj.uo_user_ids = [row.user_id];
        let data = await userRemove(obj);
        if (data) {
          this.$message.success("删除成功！");
          this.initMemberData();
        }
      }
    },
    async setLeader(user_id, flag) {
      let obj = {
        user_id: user_id,
        user_main: {
          user_group_id: flag ? "100" : "1"
        }
      }
      await userEdit(obj);
      this.$message.success("设置成功");
      this.initMemberData();
    }
  },
  created() {
    this.initData();
    this.initMemberData();
    this.initPermissionData();
  }
}
</script>

<style lang="scss" scoped>
.qxfpManage {
  height: 100%;
  .sidebar-wrapper::v-deep {
    .el-scrollbar__wrap {
      overflow-x: hidden;
    }
  }
  .leftContent {
    width: 400px;
    height: 100%;
    padding-right: 10px;
    border-right: 1px solid rgba($color: #707070, $alpha: 0.2);
    .treeContent {
      margin-top: 10px;
      height: calc(100% - 50px);
      overflow: auto;
      .el-tree::v-deep {
        padding-right: 15px;
        .el-tree-node__content {
          .custom-tree-node {
            flex: 1;
            display: flex;
            align-items: center;
            justify-content: space-between;
            font-size: 14px;
            padding-right: 8px;
            .operateDiv {
              display: none;
            }
            &:hover {
              .operateDiv {
                display: block;
              }
            }
          }
        }
      }
    }
  }
  .rightContent {
    flex: 1;
    padding-left: 10px;
    height: 100%;
    overflow: auto;
    .flex-auto {
      position: relative;
      .memberBtn {
        position: absolute;
        top: -2px;
        right: 0;
      }
    }
  }
}
</style>