import React, { useRef, useEffect, useState } from 'react';
import { Button, Space, message, Popconfirm } from 'antd';
import {
  PageContainer,
  ProTable,
} from '@ant-design/pro-components';

import AuthConsumer from '@/components/Authority';
import CreateFormModal from './components/CreateFormModal';
import UpdateFormModal from './components/UpdateFormModal';

import services from '@/services/admin';

const { permissionTree, permissionCreate, permissionUpdate, permissionDelete } = services.PermissionController;

export default () => {
  const [createFormModal, setCreateFormModal] = useState(false);
  const [updateFormModal, setUpdateFormModal] = useState(false);
  const [permissionTreeData, setPermissionTreeData] = useState([]);

  const actionRef = useRef();

  const initRow = {
    id: '',
    pid: 0,
    name: '',
    path: '',
    type: 1,
    sort: 50,
    permission_ids: [],
  };

  const [row, setRow] = useState(initRow);

  const [selectedRowsState, setSelectedRows] = useState([]);

  useEffect(() => {
    permissionTree().then(({ data }) => {
      setPermissionTreeData(data);
    });
  }, []);

  const handleDelete = async (fields) => {

    const { success } = await permissionDelete(fields);
    if (success) {
      actionRef.current.clearSelected();
      actionRef.current?.reload();
    }

  };

  const handleCreate = async (fields) => {
    setRow(fields);

    const { success } = await permissionCreate({ ...fields });

    if (success) {
      setRow(initRow);
      actionRef.current?.reload();
      setCreateFormModal(false);
    }
  };

  const handleUpdate = async (fields) => {

    const { success } = await permissionUpdate({ ...fields });

    if (success) {
      actionRef.current?.reload();

      setUpdateFormModal(false);
    }
  };

  const columns = [
    {
      title: '名称',
      dataIndex: 'name',
    },
    {
      title: '图标',
      dataIndex: 'icon',
    },
    {
      title: '排序',
      dataIndex: 'sort',
    },
    {
      title: '类型',
      dataIndex: 'type',
      render: (value) => {
        return value === 1 ? '菜单' : '权限';
      },
    },
    {
      title: '路径',
      dataIndex: 'path',
    },
    {
      title: '更新时间',
      dataIndex: 'updated_at',
      search: false,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <Space>
          <AuthConsumer action={'admin/permission/update'} key="admin/permission/update">
            <Button
              type="link"
              onClick={() => {
                setRow(record);
                setUpdateFormModal(true)
              }}
            >
              编辑
            </Button>
          </AuthConsumer>
          {
            record.type == 1 ? <AuthConsumer action={'admin/permission/create'} key="admin/permission/create">
              <Button
                type="link"
                onClick={() => {
                  setRow({ ...initRow, pid: record.id });
                  setCreateFormModal(true)
                }}
              >
                添加子菜单
              </Button>
            </AuthConsumer> : ''
          }

          <AuthConsumer action={'admin/permission/delete'} key="admin/permission/delete">
            <Popconfirm
              title="确认删除？"
              onConfirm={() => {
                handleDelete({ id: record.id });
              }}
            >
              <Button
                type="link"
                danger
              >
                删除
              </Button>
            </Popconfirm>
          </AuthConsumer>

        </Space>
      ),
    },
  ];

  return (
    <PageContainer
      ghost
    >
      <>
        <UpdateFormModal
          values={row}
          modalOpenState={updateFormModal}
          onModalOpenState={setUpdateFormModal}
          onSubmit={handleUpdate}
          permissionTreeData={permissionTreeData}
        />
        <CreateFormModal
          values={row}
          modalOpenState={createFormModal}
          onModalOpenState={setCreateFormModal}
          onSubmit={handleCreate}
          permissionTreeData={permissionTreeData}
        />
        <ProTable
          actionRef={actionRef}
          rowKey="id"
          search={false}
          toolBarRender={() => [
            <AuthConsumer action={'admin/permission/create'} key="admin/permission/create">
              <Button
                type="primary"
                onClick={() => {
                  setRow(initRow);
                  setCreateFormModal(true)
                }}
              >
                添加
              </Button>
            </AuthConsumer>
          ]}
          request={async (params, sorter, filter) => {
            const { data, success } = await permissionTree({
              ...params,
              sorter,
              filter,
            });
            setPermissionTreeData(data);
            return {
              data: data,
              success: success,
            };
          }}
          columns={columns}
          rowSelection={{
            onChange: (_, selectedRows) => {
              setSelectedRows(selectedRows)
            },
          }}
          tableAlertRender={({
            selectedRowKeys,
            selectedRows,
            onCleanSelected,
          }) => {
            return (
              <Space size={24}>
                <span>已选 {selectedRowKeys.length} 项</span>
                <span>
                  <a style={{ marginInlineStart: 8 }} onClick={onCleanSelected}>
                    取消选择
                  </a>
                </span>
              </Space>
            );
          }}
          tableAlertOptionRender={({ selectedRowKeys, selectedRows, onCleanSelected }) => {
            return (
              <Space size={16}>
                <AuthConsumer action={'admin/permission/delete'} key="admin/permission/delete">
                  <Popconfirm
                    title="确认删除？"
                    onConfirm={() => {
                      handleDelete({ id: selectedRowKeys });
                    }}
                  >
                    <Button
                      type="link"
                      danger
                    >
                      批量删除
                    </Button>
                  </Popconfirm>
                </AuthConsumer>
              </Space>
            );
          }}
          pagination={false}
        />
      </>
    </PageContainer>
  );
};
