// 创建弹窗
import React, { useEffect, useRef, useState } from 'react';
import { Button, Drawer, DrawerProps, message, Space } from 'antd';
import { ActionType, ProColumns } from '@ant-design/pro-table';
import Table from '@/components/Table';
import { TableRowSelection } from 'antd/lib/table/interface';
import { getPermission } from '@/services/system/permission';

interface AuthPermissionsDrawerPropsType extends DrawerProps {
  onCancel: () => void;
  onOk: (val: any) => void;
  rowData: any;
}

const columnsPermissions: ProColumns<any>[] = [
  {
    title: '路由名称',
    dataIndex: 'name',
  },
];

const valueMap = {};
const loops = (list, parent) => {
  return (list || []).map(({ children, name }) => {
    const node = (valueMap[name] = {
      parent,
      name,
    });
    node.children = loops(children, node);
    return node;
  });
};

const getPath = (name) => {
  const path = [];
  let current = valueMap[name];
  while (current) {
    path.unshift(current.name);
    current = current.parent;
  }
  return path;
};

const mergeArray = (arr1, arr2) => {
  const _arr = new Array();
  for (let i = 0; i < arr1.length; i++) {
    _arr.push(arr1[i]);
  }
  for (let i = 0; i < arr2.length; i++) {
    let flag = true;
    for (let j = 0; j < arr1.length; j++) {
      if (arr2[i] == arr1[j]) {
        flag = false;
        break;
      }
    }
    if (flag) {
      _arr.push(arr2[i]);
    }
  }
  return _arr;
};

const AuthPermissionsDrawer = ({
  onOk,
  onCancel,
  rowData,
  ...rest
}: AuthPermissionsDrawerPropsType) => {
  const tableRef = useRef<ActionType>();
  const [selectedKeys, setSelectedKeys] = useState(new Array());

  const rowSelection: TableRowSelection<DataType> = {
    onChange: (selectedRowKeys, selectedRows) => {
      setSelectedKeys(selectedRowKeys);
    },
  };

  const handleOk = () => {
    let postSelectedKeys = new Array();
    selectedKeys.forEach((element) => {
      const path = getPath(element);
      postSelectedKeys = mergeArray(postSelectedKeys, path);
    });
    if (postSelectedKeys.length == 0) {
      message.warning('请选择权限。');
      return;
    }
    onOk({ id: rowData.id, permission: postSelectedKeys });
  };

  const handleCancel = () => {
    onCancel();
  };
  useEffect(() => {
    const parentArray = new Array();
    let newPermission = new Array();
    for (const key in valueMap) {
      if (Object.prototype.hasOwnProperty.call(valueMap, key)) {
        const element = valueMap[key];
        if (element.children.length != 0) {
          parentArray.push(element.name);
        }
      }
    }
    if (rowData.permission != undefined && rowData.permission != [] && rowData.permission != null) {
      newPermission = rowData.permission.filter((item) => !parentArray.includes(item));
    }
    setSelectedKeys(newPermission);
  }, [rowData.permission]);

  return (
    <Drawer
      onClose={handleCancel}
      width={400}
      {...rest}
      extra={
        <Space>
          <Button onClick={handleCancel}>Cancel</Button>
          <Button type="primary" onClick={handleOk}>
            OK
          </Button>
        </Space>
      }
    >
      <Table
        columns={columnsPermissions}
        rowKey="name"
        search={false}
        pagination={false}
        rowSelection={{
          ...rowSelection,
          hideSelectAll: true,
          checkStrictly: false,
          selectedRowKeys: selectedKeys,
        }}
        actionRef={tableRef}
        request={async (params) => {
          const res = await getPermission({});
          const treeData = JSON.parse(res.items);
          loops(treeData, null);
          return { data: treeData };
        }}
      />
    </Drawer>
  );
};

export default AuthPermissionsDrawer;
