<!-- @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="addApartment">新增部门</ns-button>
          <ns-button :disabled="disabled" type="primary" @click="addApartmentSon"
            >新增子部门</ns-button
          >
          <ns-button
            :disabled="disabled"
            style="margin: 10px"
            type="primary"
            @click="deleteApartment"
            >删除</ns-button
          >
          <a-tree
            v-if="apartmentTreeData?.length"
            :tree-data="apartmentTreeData"
            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"
                :model="formData"
                formLayout="vertical"
                class="form" />
            </a-tab-pane>
            <a-tab-pane key="2" :disabled="disabled" tab="部门权限">
              <a-tree
                :tree-data="apartmentAdminTreeData"
                :fieldNames="{ children: 'menus', title: 'label', key: 'permissionId' }"
                v-model:checkedKeys="ApartcheckedKeys"
                checkable
                :selectable="false"
                defaultExpandAll
                @select="ApartmentSelect">
                <template #title="data"> {{ data.label }}</template>
              </a-tree>
            </a-tab-pane>
          </a-tabs>
          <div v-show="activeKey === '1'">
            <ns-button style="margin: 16px" type="primary" @click="CancelApartment">取消</ns-button>
            <ns-button type="primary" :disabled="disabled" @click="ApartmentSure">确定</ns-button>
          </div>
          <div v-show="activeKey === '2'">
            <ns-button style="margin-left: 16px" type="primary" @click="apartmentPermission"
              >确定</ns-button
            >
          </div>
        </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="addUser">新增角色</ns-button>
          <ns-button :disabled="disabled2" type="primary" @click="addUserSon">新增子角色</ns-button>
          <ns-button :disabled="disabled2" style="margin: 10px" type="primary" @click="deleteUser"
            >删除</ns-button
          >
          <a-tree
            v-if="userTreeData.length"
            :tree-data="userTreeData"
            defaultExpandAll
            @select="SelectUserTree">
            <template #title="data">
              {{ data.zhName }}
            </template>
          </a-tree>
        </a-col>
        <a-col :span="12" class="list">
          <a-tabs v-model:activeKey="activeKey2">
            <a-tab-pane key="1" tab="角色信息">
              <ns-form
                :schemas="formSchema2"
                :model="formData2"
                formLayout="vertical"
                class="form" />
            </a-tab-pane>
            <a-tab-pane key="2" :disabled="disabled2" tab="角色权限">
              <a-tree
                v-if="userAdminTreeData?.length"
                :tree-data="userAdminTreeData"
                v-model:checkedKeys="UsercheckedKeys"
                defaultExpandAll
                :fieldNames="{ children: 'menus', title: 'label', key: 'permissionId' }"
                :selectable="false"
                checkable
                @select="UserSelect" />
            </a-tab-pane>
          </a-tabs>
          <div v-show="activeKey2 === '1'">
            <ns-button style="margin: 16px" type="primary" @click="CancelUser">取消</ns-button>
            <ns-button type="primary" :disabled="disabled2" @click="UserSure"> 确定</ns-button>
          </div>
          <div v-show="activeKey2 === '2'">
            <ns-button style="margin: 16px" type="primary" @click="rolePermission"> 确定</ns-button>
          </div>
        </a-col>
      </a-row>
    </div>
  </div>
</template>
<script lang="ts">
  import { createVNode, defineComponent, reactive, ref, watch, 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';

  export default defineComponent({
    name: 'AuthorityManageIndex',
    setup() {
      const formRef = ref();
      let formData = ref({});
      let formData2 = ref({});
      const activeKey = ref('1');
      const activeKey2 = ref('1');
      const disabled = ref(true);
      const disabled2 = ref(true);
      const ApartcheckedKeys = ref<string[]>([]);
      const UsercheckedKeys = ref<string[]>([]);
      const selectKey = ref();
      const selectRef = ref();
      const selectKey2 = ref();
      const selectRef2 = ref();
      const formSchema = formConfig(disabled as any);
      const formSchema2 = formConfig2(disabled2 as any);
      const orgId = JSON.parse(sessionStorage.getItem('userInfo')).orgId;
      const projectId = JSON.parse(sessionStorage.getItem('userInfo')).projectId;
      const userAdminTreeData = ref([]);
      const apartmentTreeData = ref([]);
      const apartmentAdminTreeData = ref([]);

      const userTreeData = ref([]);
      const getPermissionTree = (params) => {
        return http.post(permission.permissionTree, params).then((res) => {
          apartmentAdminTreeData.value = get(res, 'data.data');
          userAdminTreeData.value = get(res, 'data.data');
        });
      };

      getPermissionTree({ projectId });

      watch(ApartcheckedKeys, () => {
        console.log('checkedKeys', ApartcheckedKeys.value);
      });
      watch(UsercheckedKeys, () => {
        console.log('checkedKeys', UsercheckedKeys.value);
      });

      // 部门树
      const getDepartList = (params) => {
        return http.post(department.dartList, params);
      };
      getDepartList({ orgId }).then((res) => {
        apartmentTreeData.value = res.data;
      });

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

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

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

      function fetch(api, params) {
        return http.post(api, params);
      }

      const addApartment = () => {
        disabled.value = false;
        opMap.type = 'addDept';
        formData.value = {};
        opMap.fuc = (params) => {
          return http.post(department.deptSave, {
            ...params,
            orgId,
            projectId,
          });
        };
        return;
      };

      const addApartmentSon = () => {
        disabled.value = false;
        opMap.type = 'addson';
        formData.value = {};
        opMap.fuc = (params) => {
          return http.post(department.deptSave, {
            ...params,
            orgId,
            projectId,
            pdeptId: selectRef.value.deptInfo.deptId,
          });
        };
      };

      const addUser = () => {
        disabled2.value = false;
        opMap.type = 'addUser';
        formData2.value = {};
        opMap.fuc = (params) => {
          delete params.roleId;
          return http.post(department.addRole, {
            ...params,
            orgId,
            projectId,
            deptId: selectRef.value.deptInfo.deptId,
          });
        };
      };

      const addUserSon = () => {
        disabled.value = false;
        opMap.type = 'addUserSon';
        formData2.value = {};
        opMap.fuc = (params) => {
          delete params.roleId;
          return http.post(department.addRole, {
            ...params,
            orgId,
            projectId,
            proleId: selectRef2.value.roleId,
            deptId: selectRef.value.deptInfo.deptId,
          });
        };
      };
      const deleteApartment = () => {
        // 删除逻辑
        // opMap.type = 'deptDelete';
        // opMap.fuc = (params) => {
        //   return http.post(department.deptDel, params).then(() => {
        //     NsMessage.success('删除成功');
        //   });
        // };
        Modal.confirm({
          title: '是否确认删除',
          icon: createVNode(ExclamationCircleOutlined),
          content: createVNode('div', { style: 'color:red;' }, ''),
          onOk() {
            http.post(department.deptDel, { deptId: selectRef.value.deptInfo.deptId }).then(() => {
              getTree();
              clearApartData();
            });
          },
          onCancel() {
            console.log('Cancel');
          },
        });
      };

      const deleteUser = () => {
        Modal.confirm({
          title: '是否确认删除',
          icon: createVNode(ExclamationCircleOutlined),
          content: createVNode('div', { style: 'color:red;' }, ''),
          onOk() {
            http.post(department.delRole, { roleId: selectRef2.value.roleId }).then(() => {
              getUserTree({ deptId: selectRef.value.deptInfo.deptId });
            });
          },

          class: 'test',
        });
      };

      const clearApartData = () => {
        selectRef.value = {};
        formData.value = {};
        opMap.type = '';
        opMap.fuc = '';
        selectKey.value = '';
      };

      // 保存部门权限
      const apartmentPermission = () => {
        http
          .post(department.addPermission, {
            deptId: selectRef.value?.deptInfo.deptId,
            projectId,
            permissionVoList: ApartcheckedKeys.value.map((item) => {
              return { permissionId: item };
            }),
          })
          .then(() => {
            NsMessage.success('保存成功');
          });
      };
      // 保存角色权限
      const rolePermission = () => {
        http
          .post(department.addRolePermission, {
            // deptId: selectRef.value?.deptInfo.deptId,
            roleId: selectRef2.value?.roleId,
            projectId,
            permissionVoList: UsercheckedKeys.value.map((item) => {
              return { permissionId: item };
            }),
          })
          .then(() => {
            NsMessage.success('保存成功');
          });
      };

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

      // 获取角色拥有的权限
      const getRolePermission = () => {
        http
          .post(department.queryRolePermission, { roleId: selectRef2.value?.roleId })
          .then((res) => {
            UsercheckedKeys.value = res.data.map((item) => {
              return item.permissionId;
            });
          });
      };

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

      // 部门选择
      const SelectApartmentTree = (selectedKeys: any, info: any) => {
        const { selected } = info;
        disabled.value = !selected;
        console.log(info, 'info');
        selectKey.value = selectedKeys[0];
        selectRef.value = info.node.dataRef;
        formData.value = cloneDeep(info.node.dataRef.deptInfo);
        apartmentChoose();
        ApartcheckedKeys.value.splice(0);
        getDeptPermission();
        // getUserTree({ deptId: selectRef.value.deptInfo.deptId });
      };

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

      // 角色选择
      const SelectUserTree = (selectedKeys: any, info: any) => {
        const { selected } = info;
        disabled2.value = !selected;
        console.log(selectedKeys, 'selectedKeys');
        console.log(info, 'info');
        selectKey2.value = selectedKeys[0];
        selectRef2.value = info.node.dataRef;
        formData2.value = cloneDeep(info.node.dataRef);
        roleChoose();
        UsercheckedKeys.value.splice(0);
        getRolePermission();
      };

      const CancelApartment = () => {
        disabled.value = true;
        // 取消视为转入编辑状态
        // clearApartData();
      };

      const CancelUser = () => {
        disabled2.value = true;
      };

      const ApartmentSelect = (selectedKeys: any, info: any) => {
        console.log(selectedKeys, 'selectedKeys');
        console.log(info, 'info');
      };

      const UserSelect = (selectedKeys: any, info: any) => {
        console.log(selectedKeys, 'selectedKeys');
        console.log(info, 'info');
      };

      const ApartmentSure = () => {
        // formRef.value?.triggerSubmit().then(() => {});

        // disabled.value = !disabled.value;
        // console.log(formData.value.name, 'formData');
        console.log(opMap.type, 'ApartmentSure');
        const opArr = ['addDept', 'editDpet'];
        if (opArr.includes(opMap.type)) {
          console.log(formRef.value, formData);
          opMap.fuc &&
            opMap.fuc(formData.value).then(() => {
              getTree();
            });
        } else if (selectRef.value && opMap.type === 'addson')
          opMap.fuc && opMap.fuc(formData.value);
        else if (opMap.type === 'deptDelete') {
          opMap.fuc && opMap.fuc({ ...formData.value, selectRef: selectRef.value });
        }
      };

      const UserSure = () => {
        disabled2.value = !disabled2.value;
        const typeArr = ['addUserSon', 'addUser', 'editRole'];
        if (typeArr.includes(opMap.type)) {
          opMap.fuc &&
            opMap.fuc(formData2.value).then(() => {
              getUserTree();
            });
        } else if (selectRef2.value && opMap.type === 'addson')
          selectRef2.value['children'] = [
            {
              key: '123',
              title: formData2.value.departname,
              info: { ...cloneDeep(formData2.value) },
            },
          ];
        else {
          console.log('ss');
        }
      };

      return {
        disabled,
        disabled2,
        formSchema,
        formSchema2,
        formData,
        formData2,
        apartmentTreeData,
        userTreeData,
        SelectApartmentTree,
        SelectUserTree,
        activeKey,
        activeKey2,
        ApartmentSure,
        UserSure,
        addApartment,
        addApartmentSon,
        deleteApartment,
        deleteUser,
        addUser,
        addUserSon,
        CancelApartment,
        CancelUser,
        apartmentAdminTreeData,
        ApartmentSelect,
        ApartcheckedKeys,
        userAdminTreeData,
        UsercheckedKeys,
        UserSelect,
        formRef,
        apartmentPermission,
        rolePermission,
      };
    },
  });
</script>
<style scoped>
  .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>
