<!-- @format -->

<template>
  <div class="main">
    <div class="left">
      <div class="ns-table-title">部门管理</div>
      <a-row>
        <a-col :span="12" class="tree">
          <ns-button style="margin: 10px" type="primary" @click="pipe(addApartment)">
            新增部门
          </ns-button>
          <ns-button type="primary" @click="pipe(addApartmentSon, true)">新增子部门</ns-button>
          <ns-button style="margin: 10px" type="primary" @click="pipe(deleteDept, true)">
            删除
          </ns-button>
          <a-tree
            v-if="deptTreeData?.length"
            :tree-data="deptTreeData"
            :selectedKeys="deptTreeSelectedKeys"
            defaultExpandAll
            @select="SelectApartmentTree">
            <template #title="data">
              {{ data.deptInfo?.deptName }}
            </template>
          </a-tree>
        </a-col>
        <a-col :span="12" class="list">
          <a-tabs v-model:activeKey="activeKey">
            <a-tab-pane :key="1" tab="部门信息">
              <ns-form
                ref="formRef"
                :schemas="formSchema"
                :wrapperCol="{ span: 18 }"
                :model="formData"
                formLayout="vertical"
                class="form" />
            </a-tab-pane>
            <a-tab-pane :key="2" :disabled="selectRef?.hasOwnProperty('orgInfo')" tab="部门权限">
              <a-tree
                v-if="deptPermissionTreeData?.length"
                :tree-data="deptPermissionTreeData"
                :fieldNames="{ children: 'menus', title: 'label', key: 'permissionId' }"
                v-model:checkedKeys="deptcheckedKeys"
                checkable
                :selectable="false"
                defaultExpandAll
                @check="deptCheck">
                <template #title="data"> {{ data.label }}</template>
              </a-tree>
            </a-tab-pane>
          </a-tabs>
          <ns-button style="margin: 16px" type="primary" @click="CancelApartment">取消 </ns-button>
          <ns-button v-show="disabled" type="primary" @click="pipe(deptEdit, true, false)"
            >编辑</ns-button
          >
          <ns-button v-show="!disabled" type="primary" @click="deptSure">确定</ns-button>
        </a-col>
      </a-row>
    </div>
    <div class="right">
      <div class="ns-table-title">角色管理</div>
      <a-row>
        <a-col :span="12" class="tree">
          <ns-button style="margin: 10px" type="primary" @click="rolePipe(addUser, true)">
            新增角色
          </ns-button>
          <ns-button type="primary" @click="rolePipe(addUserSon)">新增子角色</ns-button>
          <ns-button style="margin: 10px" type="primary" @click="rolePipe(deleteUser)">
            删除
          </ns-button>
          <a-tree
            v-if="roleTreeData.length"
            :tree-data="roleTreeData"
            :selectedKeys="roleTreeSelectedKeys"
            defaultExpandAll
            @select="SelectUserTree">
            <template #title="data">
              {{ data.zhName }}
            </template>
          </a-tree>
        </a-col>
        <a-col :span="12" class="list">
          <a-tabs v-model:activeKey="roleActiveKey">
            <a-tab-pane :key="1" tab="角色信息">
              <ns-form
                ref="formRoleRef"
                :schemas="formSchema2"
                :model="roleFormData"
                :wrapperCol="{ span: 18 }"
                formLayout="vertical"
                class="form" />
            </a-tab-pane>
            <a-tab-pane :key="2" tab="角色权限">
              <a-tree
                v-if="rolePermissionTreeData?.length"
                :tree-data="rolePermissionTreeData"
                v-model:checkedKeys="roleCheckedKeys"
                defaultExpandAll
                :fieldNames="{ children: 'menus', title: 'label', key: 'permissionId' }"
                :selectable="false"
                checkable
                @check="roleCheck" />
            </a-tab-pane>
          </a-tabs>
          <ns-button style="margin: 16px" type="primary" @click="CancelUser">取消</ns-button>
          <ns-button v-show="roleDisabled" type="primary" @click="rolePipe(roleEdit, false, false)">
            编辑
          </ns-button>
          <ns-button v-show="!roleDisabled" type="primary" @click="roleSure"> 确定 </ns-button>
        </a-col>
      </a-row>
    </div>
  </div>
</template>
<script lang="ts" setup>
  import { createVNode, ref, watchEffect } from 'vue';
  import { Modal } from 'ant-design-vue';
  import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
  import { http } from '/nerv-lib/util/http';
  import { cloneDeep, get } from 'lodash-es';
  import { formConfig, formConfig2 } from './config';
  import { department } from '/@/api/origanizemanage';
  import { permission } from '/@/api/origanizemanage';
  import { NsMessage } from '/nerv-lib/component';

  defineOptions({
    name: 'AuthorityManageIndex',
  });

  const formRef = ref();
  const formRoleRef = ref();
  let formData = ref({});
  let roleFormData = ref({});
  const activeKey = ref(1);
  const roleActiveKey = ref(1);
  const disabled = ref(true);
  const roleDisabled = ref(true);
  const deptTreeSelectedKeys = ref([]);
  const roleTreeSelectedKeys = ref([]);
  const deptcheckedKeys = ref<string[]>([]);
  const roleCheckedKeys = ref<string[]>([]);
  const currentOrgRef = ref();
  const selectKey = ref();
  const selectRef = ref();
  const selectRoleKey = ref();
  const selectRoleRef = ref();
  const formSchema = formConfig(disabled as any);
  const formSchema2 = formConfig2(roleDisabled as any);
  const { orgName, projectId, orgId } = JSON.parse(sessionStorage.getItem('userInfo'));
  // const orgId = JSON.parse(sessionStorage.getItem('ORGID'));
  const roleTreeData = ref([]);
  const rolePermissionTreeData = ref([]);
  const deptTreeData = ref([]);
  const deptPermissionTreeData = ref([]);

  // 包含半选状态的权限数据
  const deptTotalCheckedKeys = ref([]);
  const roleTotalCheckedKeys = ref([]);

  // 禁用权限树
  const disabledTree = (data, disabled = true) => {
    data.map((item) => {
      item['disabled'] = disabled;
      if (item.menus) {
        disabledTree(item.menus, disabled);
      }
    });
  };

  watchEffect(() => {
    disabledTree(deptPermissionTreeData.value, disabled.value);
    disabledTree(rolePermissionTreeData.value, roleDisabled.value);
  });

  /**操作拦截 */
  const pipe = (func: Function, flag = false, toggle = true) => {
    console.log(selectRef.value);

    if (toggle) activeKey.value = 1;
    if (flag) {
      // 只有部门的操作
      if (selectRef.value?.hasOwnProperty('orgInfo') || !selectRef.value?.deptInfo) {
        NsMessage.error('请先选择相关部门');
        return;
      }
    } else {
      if (!selectRef.value?.hasOwnProperty('orgInfo')) {
        NsMessage.error('请先选择相关企业');
        return;
      }
    }

    func && func();
  };

  const rolePipe = (func: Function, linkDept = false, toggle = true) => {
    console.log(selectRoleRef.value);
    if (toggle) roleActiveKey.value = 1;
    // 需要先选择部门
    if ((linkDept && !selectRef.value?.deptInfo) || selectRef.value?.hasOwnProperty('own')) {
      NsMessage.error('请先选择相关部门');
      return;
    }
    if (!linkDept && !selectRoleRef.value) {
      NsMessage.error('请先选择相关角色');
      return;
    }
    func && func();
  };
  /**操作拦截 */

  // 部门权限树
  const getPermissionTree = (params) => {
    return http.post(permission.queryOrgPermission, params).then((res) => {
      deptPermissionTreeData.value = get(res, 'data');
    });
  };
  // 子级部门权限树
  const getDeptsonPermissionTree = (params) => {
    return http.post(permission.queryDeptPermissionFilter, params).then((res) => {
      deptPermissionTreeData.value = get(res, 'data');
    });
  };

  // 角色权限树
  const getRolePermissionTree = (params) => {
    return http.post(permission.queryFilterDeptPermission, params).then((res) => {
      rolePermissionTreeData.value = get(res, 'data');
    });
  };

  // 子级角色权限树
  const getRolesonPermissionTree = (params) => {
    return http.post(permission.queryRolePermissionFilter, params).then((res) => {
      rolePermissionTreeData.value = get(res, 'data');
    });
  };

  getPermissionTree({ projectId, orgId });

  // 部门树
  const getDepartList = (params) => {
    return http.post(department.queryDeptTree, params).then((res) => {
      const result = res.data.map((item, index) => {
        item['deptInfo'] = item.orgInfo;
        item['deptInfo'] = item.orgInfo;
        item['deptInfo']['deptName'] = item?.orgInfo?.orgName;
        item['own'] = !index;
        item['children'] = item.deptTrees;
        return item;
      });

      return result;
    });
  };
  getDepartList({ orgId }).then((res) => {
    deptTreeData.value = res;
  });

  // 获取部门树
  const getTree = () => {
    getDepartList({ orgId }).then((res) => {
      deptTreeData.value = res;
      NsMessage.success('操作成功');
    });
  };

  // 获取角色树
  const getUserTree = (params = { deptId: selectRef.value?.deptInfo?.deptId }) => {
    http.post(department.queryRoleTree, params).then((res) => {
      roleTreeData.value = res.data;
    });
  };
  // 根据依赖刷新角色树
  watchEffect(() => {
    if (selectRef.value) {
      getUserTree();
    }
  });

  const opMap: any = {
    type: 'add',
    fuc: () => {},
    record: {},
    callback: null,
  };

  const addApartment = () => {
    disabled.value = false;
    opMap.type = 'addDept';
    formData.value = {};
    let sourceOrgId = '';
    if (!currentOrgRef.value.own) {
      sourceOrgId = orgId;
    }
    opMap.fuc = (params) => {
      return formRef.value.triggerSubmit().then(() => {
        return http.post(department.deptSave, {
          ...params,
          orgId: selectRef.value.deptInfo?.orgId,
          sourceOrgId,
          projectId,
          orgName,
        });
      });
    };
    return;
  };

  const addApartmentSon = () => {
    disabled.value = false;
    opMap.type = 'addson';
    formData.value = {};
    let sourceOrgId = '';
    if (!currentOrgRef.value?.own && orgId !== selectRef.value.deptInfo?.orgId) {
      sourceOrgId = orgId;
    }
    opMap.fuc = (params) => {
      return formRef.value.triggerSubmit().then(() => {
        return http.post(department.deptSave, {
          ...params,
          orgId,
          projectId,
          pdeptId: selectRef.value.deptInfo.deptId,
          sourceOrgId,
          // deptName: selectRef.value.deptInfo.deptName,
        });
      });
    };
  };

  const addUser = () => {
    roleDisabled.value = false;
    opMap.type = 'addUser';
    roleFormData.value = {};
    opMap.fuc = (params) => {
      delete params.roleId;
      return formRoleRef.value.triggerSubmit().then(() => {
        return http.post(department.addRole, {
          ...params,
          orgId,
          projectId,
          deptId: selectRef.value.deptInfo.deptId,
          deptName: selectRef.value.deptInfo.deptName,
        });
      });
    };
  };

  const addUserSon = () => {
    roleDisabled.value = false;
    opMap.type = 'addUserSon';
    roleFormData.value = {};
    opMap.fuc = (params) => {
      delete params.roleId;
      return formRoleRef.value.triggerSubmit().then(() => {
        return http.post(department.addRole, {
          ...params,
          orgId,
          projectId,
          proleId: selectRoleRef.value.roleId,
          deptId: selectRef.value.deptInfo.deptId,
          deptName: selectRef.value.deptInfo.deptName,
        });
      });
    };
  };
  const deleteDept = () => {
    // 删除逻辑
    Modal.confirm({
      title: '是否确认删除',
      onOk() {
        http.post(department.deptDel, { deptId: selectRef.value.deptInfo.deptId }).then(() => {
          getTree();
          clearDeptData();
          // 清空select树
          deptTreeSelectedKeys.value = [];
          selectRef.value = '';
        });
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  };

  const deleteUser = () => {
    Modal.confirm({
      title: '是否确认删除',
      onOk() {
        http.post(department.delRole, { roleId: selectRoleRef.value.roleId }).then(() => {
          getUserTree({ deptId: selectRef.value.deptInfo.deptId });
          clearRoleData();
          // 清空select树
          roleTreeSelectedKeys.value = [];
          selectRoleRef.value = '';
          NsMessage.success('操作成功');
        });
      },
    });
  };
  watchEffect(() => {
    console.log(deptTreeSelectedKeys.value, 'deptTreeData.value');
  });

  const clearDeptData = () => {
    formData.value = {};
    opMap.type = '';
    opMap.fuc = '';
  };
  const clearRoleData = () => {
    roleFormData.value = {};
    opMap.type = '';
    opMap.fuc = '';
  };

  // 部门权限选择
  const deptCheck = (checked, { halfCheckedKeys }) => {
    console.log(checked, halfCheckedKeys);

    const result = checked.map((item) => {
      return {
        halfCheck: false,
        permissionId: item,
      };
    });
    const finalResult = halfCheckedKeys
      .map((item) => {
        return {
          halfCheck: true,
          permissionId: item,
        };
      })
      .concat(result);

    deptTotalCheckedKeys.value = finalResult;
  };

  // 角色权限选择
  const roleCheck = (checked, { halfCheckedKeys }) => {
    console.log(checked, halfCheckedKeys);

    const result = checked.map((item) => {
      return {
        halfCheck: false,
        permissionId: item,
      };
    });
    const finalResult = halfCheckedKeys
      .map((item) => {
        return {
          halfCheck: true,
          permissionId: item,
        };
      })
      .concat(result);
    roleTotalCheckedKeys.value = finalResult;
  };

  // 保存部门权限
  const deptPermission = () => {
    return http
      .post(department.addPermission, {
        deptId: selectRef.value?.deptInfo.deptId,
        projectId,
        permissionVoList: deptTotalCheckedKeys.value,
      })
      .then(() => {
        NsMessage.success('保存成功');
      });
  };
  // 保存角色权限
  const rolePermission = () => {
    http
      .post(department.addRolePermission, {
        // deptId: selectRef.value?.deptInfo.deptId,
        roleId: selectRoleRef.value?.roleId,
        projectId,
        permissionVoList: roleTotalCheckedKeys.value,
      })
      .then(() => {
        NsMessage.success('保存成功');
      });
  };

  // 获取部门拥有的权限
  const getDeptPermission = () => {
    http
      .post(permission.queryDeptPermission, { deptId: selectRef.value?.deptInfo.deptId })
      .then((res) => {
        deptcheckedKeys.value = res.data
          ?.filter((item) => !item.halfCheck)
          .map((item) => {
            return item.permissionId;
          });
        deptTotalCheckedKeys.value = res.data;
      });
  };

  // 获取角色拥有的权限
  const getRolePermission = () => {
    http
      .post(permission.queryRolePermission, { roleId: selectRoleRef.value?.roleId })
      .then((res) => {
        roleCheckedKeys.value = res.data
          ?.filter((item) => !item.halfCheck)
          .map((item) => {
            return item.permissionId;
          });
        roleTotalCheckedKeys.value = res.data;
      });
  };

  /**
   * 默认选中视为编辑部门
   * type editDpet
   */
  const apartmentChoose = () => {
    opMap.type = 'editDpet';
    opMap.fuc = (params) => {
      return http.post(department.deptEdit, params);
    };
  };

  // 部门编辑
  const deptEdit = () => {
    disabled.value = false;
    apartmentChoose();
  };

  // 部门选择
  const SelectApartmentTree = (selectedKeys: any, info: any) => {
    console.log(info);

    // 部门切换需要调整角色tab
    roleActiveKey.value = 1;

    const { selected } = info;
    if (!selectedKeys?.length) return;

    deptTreeSelectedKeys.value = [info.node.key];
    selectRef.value = info.node.dataRef;

    // 确定是否是企业
    if (!selectRef.value.hasOwnProperty('own') && !selectRef.value.hasOwnProperty('orgInfo')) {
      // 部门
      formData.value = cloneDeep(info.node.dataRef.deptInfo);
    } else {
      activeKey.value = 1;
      currentOrgRef.value = selectRef.value;
      formData.value = {};
    }
    if (selectRef.value.deptInfo?.pdeptId) {
      // 查询子部门
      getDeptsonPermissionTree({ deptId: selectRef.value.deptInfo?.pdeptId });
    } else {
      getPermissionTree({ projectId, orgId });
    }
    getDeptPermission();
    // 切换部门重置逻辑
    deptcheckedKeys.value = [];
    rolePermissionTreeData.value = [];
    roleCheckedKeys.value = [];
    roleTreeSelectedKeys.value = [];
  };

  /**
   * 默认选中视为编辑角色
   * type editDpet
   */
  const roleChoose = () => {
    opMap.type = 'editRole';
    opMap.fuc = (params) => {
      return http.post(department.editRole, params);
    };
  };
  const roleEdit = () => {
    roleDisabled.value = false;
    roleChoose();
  };
  // 角色选择
  const SelectUserTree = (selectedKeys: any, info: any) => {
    const { selected } = info;
    // roleDisabled.value = !selected;

    if (!selectedKeys?.length) return;
    roleTreeSelectedKeys.value = [info.node.key];
    selectRoleRef.value = info.node.dataRef;
    roleFormData.value = cloneDeep(info.node.dataRef);
    roleCheckedKeys.value = [];
    if (selectRoleRef.value?.proleId) {
      // 查询子部门
      getRolesonPermissionTree({ roleId: selectRoleRef.value?.proleId });
    } else {
      getRolePermissionTree({ deptId: selectRef.value.deptInfo.deptId });
    }
    getRolePermission();
  };

  const CancelApartment = () => {
    disabled.value = true;
    // 清楚校验错误信息
    formRef.value.formElRef.clearValidate();
  };

  const CancelUser = () => {
    roleDisabled.value = true;
    // 清楚校验错误信息
    formRoleRef.value.formElRef.clearValidate();
  };

  // 部门确定
  const deptSure = () => {
    const opArr = ['addDept', 'editDpet', 'addson'];
    if (activeKey.value === 1) {
      if (opArr.includes(opMap.type)) {
        console.log(formRef.value, formData);
        opMap.fuc &&
          opMap.fuc(formData.value).then(() => {
            getTree();
            opMap.type !== 'editDpet' && clearDeptData();
            disabled.value = true;
          });
      }
    } else {
      deptPermission().then(() => {
        clearDeptData();
        disabled.value = true;
      });
    }
  };

  // 角色确定
  const roleSure = () => {
    const typeArr = ['addUserSon', 'addUser', 'editRole'];
    if (roleActiveKey.value === 1) {
      if (typeArr.includes(opMap.type)) {
        opMap.fuc &&
          opMap.fuc(roleFormData.value).then(() => {
            getUserTree();
            opMap.type !== 'editRole' && clearRoleData();
            roleDisabled.value = !roleDisabled.value;
            NsMessage.success('操作成功');
          });
      }
    } else {
      rolePermission();
    }
  };
</script>
<style lang="less" scoped>
  :deep(.ant-tabs-tabpane) {
    padding: 20px;
    .form {
      margin: 0 !important;
    }
  }

  .main {
    display: flex;
    flex: 1;
  }

  .left {
    width: 50%;
    height: calc(100vh-50px);
    border-right: 5px solid rgb(229, 235, 240);
  }

  .tree {
    width: 400px;
    height: 89vh;
    border-right: 2px solid rgb(229, 235, 240);
  }

  .right {
    width: 50%;
  }

  .top {
    height: 50vh;
    border-bottom: 5px solid rgb(229, 235, 240);
  }

  .ns-table-title {
    text-align: left;
    height: 46px;
    line-height: 46px;
    font-size: 18px;
    font-weight: bold;
    user-select: text;
    padding-left: 16px;
    width: 100%;
    border-bottom: 2px solid rgb(229, 235, 240);
  }

  .table {
    width: 2000px;
  }

  .admin {
    text-align: left;
    height: 42px;
    line-height: 42px;
    font-size: 16px;
    font-weight: bold;
    user-select: text;
    padding-left: 16px;
    width: calc(100% + 32px);
  }

  .form {
    margin: 20px;
  }
</style>
