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

import { history } from 'umi';
import AuthConsumer from '@/components/Authority';
import CreateFormModal from './components/CreateFormModal';
import UpdateFormModal from './components/UpdateFormModal';

import services from '@/services/admin';

const { adminItems, adminitem, adminCreate, adminDelete, adminUpdate } = services.AdminController;
const { permissionTree } = services.PermissionController;

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

  const actionRef = useRef();

  const initRow = {
    id: '',
    nickname: '',
    username: '',
    email: '',
    avatar: '',
    status: 0,
    password: '',
    permission_ids: [],
    authority_note: undefined
  };

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

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

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

  const handleDelete = async (fields) => {

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

  const handleCreate = async (fields) => {
    setRow(fields);
    const { success } = await adminCreate({ ...fields });

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

  const handleUpdate = async (fields) => {

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

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

      setUpdateFormModal(false);
    }
  };

  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
    },
    {
      title: '头像',
      dataIndex: 'avatar',
      valueType: 'avatar',
      search: false,
    },
    {
      title: '手机号',
      dataIndex: 'mobile',
    },
    {
      title: '昵称',
      dataIndex: 'nickname',
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      search: false,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <Space>
          <AuthConsumer action={'admin/admin/update'} key="admin/admin/update">
            <Button
              type="link"
              onClick={() => {
                // history.push({
                //   pathname: "/manage/admin/menu",
                //   state: {
                //     data: 123456
                //   }
                // });
                // setRow(record);
                history.push(`admin/${record.id}/update`);
                // setUpdateFormModal(true)
              }}
            >
              编辑
            </Button>
          </AuthConsumer>
          <AuthConsumer action={'admin/admin/delete'} key="admin/admin/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={{
            defaultCollapsed: false,
          }}
          toolBarRender={() => [
            <AuthConsumer action={'admin/admin/create'} key="admin/admin/create">
              <Button
                type="primary"
                onClick={() => {
                  history.push('admin/0/create');
                  // setCreateFormModal(true)
                }}
              >
                添加
              </Button>
            </AuthConsumer>
          ]}
          request={async (params, sorter, filter) => {
            const { data, success } = await adminItems({
              ...params,
              sorter,
              filter,
            });
            return {
              data: data?.items || [],
              total: data?.total,
              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/admin/delete'} key="admin/admin/delete">
                  <Popconfirm
                    title="确认删除？"
                    onConfirm={() => {
                      handleDelete({ id: selectedRowKeys });
                    }}
                  >
                    <Button
                      type="link"
                      danger
                    >
                      批量删除
                    </Button>
                  </Popconfirm>
                </AuthConsumer>
              </Space>
            );
          }}
          pagination={{
            showSizeChanger: true,
          }}
        />
      </>
    </PageContainer>
  );
};
