<!--
@ 作者: 秦东
@ 时间: 2023-05-30 13:52:12
@ 备注: 配置权限
-->
<script lang="ts" setup>
import {
  setupPage,
  systemCont,
  systemMenusTypeTree,
  submintPostPower,
  custerAppInfo,
  custerAppTablePower,
} from "@/api/system/roleapi/types";
import {
  getSystemType,
  getSystemPoewrTreeForRole,
  getGrantRolePowers,
  grantSystemRolePoewr,
  gainAppList,
  gainAppTableList,
  setpAppTableForms,
} from "@/api/system/roleapi/postrole";

import { appTableBut, appListBut } from "@/utils/workflow/const";

import { orgInfo } from "@/api/hr/org/type";
import { getOrgTreeList } from "@/api/hr/org/index";

const props = defineProps({
  powerIsShow: {
    type: Boolean,
    default: false,
  },
  roleId: {
    type: String,
    default: "",
  },
  roleTitle: {
    type: String,
    default: "配置权限",
  },
});
/**
 * 树形组件
 */
const menuRef = ref(ElTree);
const powerLoading = ref(false);
const powerLoadingSub = ref(false);
const emits = defineEmits(["update:powerIsShow"]); //父级元素
const appList = ref<custerAppInfo[]>([]);
const activeAppId = ref<string>("");
const appTableList = ref<custerAppTablePower[]>([]);
/**
 * 系统选择标签
 */
const systemTabs = ref("");
/**
 * 系统列表
 */
const orgPostTreeContList = ref<systemCont[]>([]);
/**
 * 管理范围
 */
const manageScope = ref(0);
/**
 * 树形结构约束
 */
const systemMenuTreeProps = {
  children: "child",
  label: "name",
  value: "id",
};
/**
 * 分页参数
 */
const setupPageCont = reactive<setupPage>({
  page: 1,
  pagesize: 100000,
});
/**
 * 弹窗显示控制
 */
const power_is_Show = computed({
  get: () => props.powerIsShow,
  set: (val) => {
    emits("update:powerIsShow", val);
  },
});
/**
 * 关闭弹窗回调
 */
function handleClosePower() {
  emits("update:powerIsShow", false);
  initData();
}
/**
 * 初始化数据
 */
function initData() {
  powerLoading.value = false;
  powerLoadingSub.value = false;
  setupPageCont.page = 1;
  setupPageCont.pagesize = 100000;
  systemTabs.value = "";
  manageScope.value = 0;
  gainPowerAry.value = [];
}
/**
 * 监听数据
 */
watch(
  () => props.powerIsShow,
  () => {
    if (props.powerIsShow) {
      getSystemTypeList();
    } else {
      initData();
    }
  }
);

/**
 * 获取系统分类
 */
function getSystemTypeList() {
  getSystemType(setupPageCont).then((data) => {
    // console.log(data);
    orgPostTreeContList.value = data.data.list;
    if (data.data.list[0]) {
      systemTabs.value = data.data.list[0].coder;
    }
  });
}
/**
 * 权限菜单列表
 */
const systemPowerMenusTree = ref<systemMenusTypeTree[]>([]);
/**
 * 已授权的权限
 */
const gainPowerAry = ref<String[]>([]);
/**
 * 获取菜单
 */
function getSysMenuTree(sysKey: string) {
  powerLoading.value = true;
  systemPowerMenusTree.value = [];
  getSystemPoewrTreeForRole({ name: sysKey, roleid: props.roleId })
    .then(({ data }) => {
      systemPowerMenusTree.value = data;
      getGrantRolePowers({ name: sysKey, roleid: props.roleId })
        .then(({ data }) => {
          // console.log("获取菜单====>",data);
          manageScope.value = data.level;
          if (data != null) {
            gainPowerAry.value = data.powerList;
          }
        })
        .finally(() => {
          powerLoading.value = false;
          setCheckedKeys();
        });
    })
    .finally(() => {
      powerLoading.value = false;
    });
}
/**
 * 设置已经授权的权限
 */
function setCheckedKeys() {
  // console.log("设置已经授权的权限",gainPowerAry.value)
  gainPowerAry.value.forEach((menuId) => menuRef.value.setChecked(menuId, true, false));
}
watch(
  () => systemTabs.value,
  () => {
    powerLoading.value = true;
    if (systemTabs.value != "" && systemTabs.value != null) {
      if (systemTabs.value == "appdevel") {
        getAppList();
      } else {
        getSysMenuTree(systemTabs.value);
      }
    }
  }
);
/**
 * 授权
 */
function enterEmpowerClick() {
  console.log("确定授权", systemTabs.value);
  if (systemTabs.value == "appdevel") {
    console.log("确定授权--21-->", props.roleId);
    console.log("确定授权--1-->", activeAppId.value);
    console.log("确定授权---->", appTableList.value);
    if (appTableList.value.length < 1) {
      ElMessage.error("没有要授权的表单。");
    } else {
      let sendInfo = {
        id: activeAppId.value.toString(),
        roleId: props.roleId.toString(),
        appTablePwoer: appTableList.value,
      };
      console.log("确定授权------------->", sendInfo);
      setpAppTableForms(sendInfo)
        .then((data) => {
          // console.log("确定授权返回----》", data);
          ElMessage.success("授权成功");
          handleClosePower();
        })
        .finally(() => {
          powerLoadingSub.value = false;
        });
    }
  } else {
    powerLoadingSub.value = true;
    const checkedMenuTrue: systemMenusTypeTree[] = menuRef.value
      .getCheckedNodes(false, true)
      .map((node: any) => node);
    //   console.log("确定授权", checkedMenuTrue);
    checkedMenuTrue.forEach((item) => {
      item.child = [];
    });
    grantSystemRolePoewr({
      systemname: systemTabs.value,
      roleid: props.roleId,
      level: manageScope.value * 1,
      power: checkedMenuTrue,
    })
      .then((data) => {
        // console.log("确定授权返回----》", data);
        ElMessage.success("授权成功");
        handleClosePower();
      })
      .finally(() => {
        powerLoadingSub.value = false;
      });
  }
}
/**
@ 作者: 秦东
@ 时间: 2025-05-13 14:20:47
@ 功能: 获取自定义App
*/
const getAppList = () => {
  getList();
  gainAppList().then((data: any) => {
    console.log("获取自定义App", data);
    appList.value = data.data;
    if (data.data && data.data.length > 0) {
      if (data.data[0] && data.data[0].signCode) {
        activeAppId.value = data.data[0].signCode;
        getAppTableList();
      }
    }
    console.log("获取自定义App", activeAppId.value);
  });
};
/**
@ 作者: 秦东
@ 时间: 2025-05-13 16:00:19
@ 功能: 获取对应App下边的表单
*/
const getAppTableList = () => {
  gainAppTableList({ id: activeAppId.value, roleId: props.roleId.toString() }).then(
    (data: any) => {
      console.log("获取对应App下边的表单", data);
      if (Array.isArray(data.data)) {
        appTableList.value = data.data;
      } else {
        appTableList.value = [];
      }
    }
  );
};
watch(
  () => activeAppId.value,
  (val) => {
    getAppTableList();
  }
);
/**
@ 作者: 秦东
@ 时间: 2025-05-14 15:01:26
@ 功能: 选择App数据
*/
const pickAppList = (val: custerAppInfo) => {
  activeAppId.value = val.signCode;
};
/**
@ 作者: 秦东
@ 时间: 2025-05-16 08:37:50
@ 功能: app数据范围
*/
const orgListTree = ref<orgInfo[]>([]);
const openAppDataBox = ref(false);
const pickOrgId = ref<number[]>([]);
const pickAppDataPower = (val: any) => {
  if (val.types == 5) {
    // openAppDataBox.value = true;
    pickOrgId.value = val.attribute;
    // getList();
  } else {
    openAppDataBox.value = false;
  }
};
const defaultProps = {
  children: "child",
  label: "name",
};
const systemMenuTreePropsing = {
  children: "child",
  label: "name",
  value: "id",
};
/**
@ 作者: 秦东
@ 时间: 2025-05-16 10:18:49
@ 功能: 获取行政组织列表
*/
const getList = () => {
  getOrgTreeList({ orgid: 309, keywords: "", class: 0 }).then((data) => {
    console.log("获取行政组织列表", data);
    orgListTree.value = data.data;
  });
};
/**
@ 作者: 秦东
@ 时间: 2025-05-16 14:30:32
@ 功能: 确定选择
*/
const pickOrgIdClick = () => {
  console.log("确定选择", pickOrgId.value);
};
</script>
<template>
  <el-dialog
    v-model="power_is_Show"
    custom-class="dialog_box"
    :title="roleTitle"
    :before-close="handleClosePower"
    draggable
    width="70%"
    fullscreen
  >
    <el-container>
      <el-aside width="125px">
        <el-tabs v-model="systemTabs" tab-position="left" class="demo-tabs tabs_box">
          <el-tab-pane
            v-for="item in orgPostTreeContList"
            :key="item.key"
            :label="item.title"
            :name="item.coder"
          ></el-tab-pane>
        </el-tabs>
      </el-aside>
      <el-main v-if="systemTabs == 'appdevel'">
        <!-- <el-tabs v-model="activeAppId" class="demo-tabs">
          <el-tab-pane
            v-for="itemes in appList"
            :key="itemes.signCode"
            :label="itemes.name"
            :name="itemes.signCode"
          ></el-tab-pane>
        </el-tabs> -->
        <el-scrollbar class="tab_pane_box">
          <table class="table_body">
            <thead>
              <tr>
                <td align="center" width="20%">应用</td>
                <td align="center" width="20%">页面</td>
                <td align="center" width="20%">表单权限</td>
                <td align="center" width="20%">列表权限</td>
                <td align="center" width="20%">数据权限</td>
              </tr>
            </thead>

            <tbody>
              <tr v-if="appTableList && appTableList.length <= 0">
                <td valign="top">
                  <ul class="appListBox">
                    <li
                      v-for="itemes in appList"
                      :class="itemes.signCode == activeAppId ? 'active' : ''"
                      @click="pickAppList(itemes)"
                    >
                      {{ itemes.name }}
                    </li>
                  </ul>
                </td>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
              </tr>
              <tr v-else v-for="(item, index) in appTableList" :key="item.id">
                <td
                  :rowspan="appTableList.length"
                  v-if="index == 0 || index + 1 > appTableList.length"
                  valign="top"
                >
                  <ul class="appListBox">
                    <li
                      v-for="itemes in appList"
                      :class="itemes.signCode == activeAppId ? 'active' : ''"
                      @click="pickAppList(itemes)"
                    >
                      {{ itemes.name }}
                    </li>
                  </ul>
                </td>
                <td valign="top">{{ item.name }}</td>
                <td valign="top">
                  <!-- {{ item.tableIsAll }}
                  <el-checkbox v-model="item.tableIsAll"> 全选 </el-checkbox> -->
                  <el-checkbox-group v-model="item.tablePower">
                    <el-checkbox
                      v-for="city in appTableBut"
                      :key="city.key"
                      :label="city.label"
                      :value="city.value"
                    >
                      {{ city.label }}
                    </el-checkbox>
                  </el-checkbox-group>
                </td>
                <td valign="top">
                  <el-checkbox-group v-if="item.istIsTrue" v-model="item.listPower">
                    <el-checkbox
                      v-for="city in appListBut"
                      :key="city.key"
                      :label="city.label"
                      :value="city.value"
                    >
                      {{ city.label }}
                    </el-checkbox>
                  </el-checkbox-group>
                </td>
                <td valign="top">
                  <el-radio-group
                    v-model="item.datePower.types"
                    @change="pickAppDataPower(item.datePower)"
                  >
                    <el-row>
                      <el-col :span="24"><el-radio :value="1">本人</el-radio></el-col>
                      <el-col :span="24"><el-radio :value="2">本岗位</el-radio></el-col>
                      <el-col :span="24"><el-radio :value="3">本部门</el-radio></el-col>
                      <el-col :span="24"><el-radio :value="4">本分部</el-radio></el-col>
                      <el-col :span="24">
                        <el-radio :value="5">指定行政组织</el-radio>
                        <el-tree-select
                          v-if="item.datePower.types == 5"
                          v-model="item.datePower.attribute"
                          :data="orgListTree"
                          :render-after-expand="false"
                          show-checkbox
                          style="width: 240px"
                          node-key="id"
                          :props="systemMenuTreePropsing"
                          multiple
                          clearable
                          collapse-tags
                        />
                      </el-col>
                      <el-col :span="24"><el-radio :value="6">所有</el-radio></el-col>
                    </el-row>
                  </el-radio-group>
                </td>
              </tr>
            </tbody>
          </table>
        </el-scrollbar>
      </el-main>
      <el-main v-if="systemTabs != 'appdevel'">
        <el-radio-group v-model="manageScope" style="margin-bottom: 10px">
          <el-radio-button label="0">默认</el-radio-button>
          <el-radio-button label="1">本岗位</el-radio-button>
          <el-radio-button label="2">本部门</el-radio-button>
          <el-radio-button label="3">本分部</el-radio-button>
          <el-radio-button label="4" disabled>指定行政组织</el-radio-button>
          <el-radio-button label="5">所有</el-radio-button>
        </el-radio-group>
        <el-scrollbar v-loading="powerLoading" class="tab_pane_box">
          <el-tree
            ref="menuRef"
            node-key="menukey"
            :data="systemPowerMenusTree"
            show-checkbox
            :default-expand-all="true"
            :props="systemMenuTreeProps"
          >
            <template #default="{ node, data }">
              <span class="tree_sapn">{{ node.label }}</span>
              <el-tag v-if="data.attribute === 2" type="warning">目录</el-tag>
              <el-tag v-if="data.attribute === 1" type="success">菜单</el-tag>
              <el-tag v-if="data.attribute === 4" type="danger">按钮</el-tag>
              <el-tag v-if="data.attribute === 3" type="info">外链</el-tag>
            </template>
          </el-tree>
        </el-scrollbar>
      </el-main>
    </el-container>

    <el-dialog
      v-model="openAppDataBox"
      width="500"
      title="选择行政组织"
      draggable
      append-to-body
    >
      <el-tree
        style="max-width: 600px"
        :data="orgListTree"
        show-checkbox
        node-key="id"
        :default-checked-keys="pickOrgId"
        :props="defaultProps"
      />
      <template #footer>
        <span class="dialog-footer">
          <el-button type="danger" @click="openAppDataBox = false">取消</el-button>
          <el-button type="primary" :loading="powerLoadingSub" @click="pickOrgIdClick"
            >确定选择</el-button
          >
        </span>
      </template>
    </el-dialog>

    <template #footer>
      <span class="dialog-footer">
        <el-button type="danger" @click="handleClosePower">取消</el-button>
        <el-button type="primary" :loading="powerLoadingSub" @click="enterEmpowerClick"
          >授权</el-button
        >
      </span>
    </template>
  </el-dialog>
</template>
<style lang="scss" scoped>
.el-dialog__body {
  padding: 0;
}
.tabs_box {
  height: calc(100vh - 140px);
  .tab_pane_box {
    height: calc(100vh - 220px);
    overflow: hidden;
    overflow-y: auto;
  }
}
.tab_pane_box {
  height: calc(100vh - 230px);
  overflow: hidden;
  overflow-y: auto;
}
.tree_sapn {
  padding: 0 15px;
}
.table_body {
  background-color: #ffffff;
  width: 100%;
  border-collapse: collapse;
  /*
       * 设置边框
       */
  td,
  th {
    border: 1px solid #cccccc;
    padding: 5px;
    table {
      width: 100%;
      td,
      th {
        border: 0px solid #cccccc;
        padding: 0px;
      }
    }
  }
}
.appListBox {
  width: 100%;
  li {
    padding: 4px 2px;
    border-bottom: 1px solid #ececec;
    cursor: pointer;
  }
  li.active {
    background-color: #a0cfff;
  }
}
</style>
