// 创建弹窗
import React, { useRef, useState } from 'react';

import { Form, FormItem, Input } from '@formily/antd';
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 routes from '@/routes';
import { getPermission } from '@/services/system/permission';

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

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

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

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

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

  const rowSelection: TableRowSelection<DataType> = {
    onChange: (selectedRowKeys, selectedRows) => {
      setSelectedKeys(selectedRowKeys);
      console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
    },
    onSelect: (record, selected, selectedRows) => {
      const path = getPath(record.name);
      const newArray = selectedKeys.concat(path);
      setPostSelectedKeys(newArray);
    },
    // onSelectAll: (selected, selectedRows, changeRows) => {
    //   console.log(selected, selectedRows, changeRows);
    // },
  };

  const handleOk = () => {
    if (postSelectedKeys.length == 0) {
      message.warning('请选择权限。');
      return;
    }
    onOk(postSelectedKeys);
  };

  const handleCancel = () => {
    onCancel();
  };

  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;
