import {PlusOutlined} from '@ant-design/icons';
import {ProTable} from '@ant-design/pro-components';
import {Button, Tour} from 'antd';
import {useCallback, useEffect, useMemo, useRef} from 'react';
import {useLocation} from 'react-router-dom';
import {useAppDispatch, useAppSelector} from '../../../redux/configureStore.js'
import {selectTouring, selectTourName} from '../../slice/selectors.js'
import {columnsFactory, optionFactory} from '../../../utils/columnsFactory.jsx'
import {ProTableDefault} from '../../constants.js'
import {selectRoles, selectUsers} from "../MainPage/slice/selectors";
import {createUser, getRoles, getUsers} from "../MainPage/slice/thunks";
import {appActions} from "../../slice";

export const UserManagePage = () => {
  const dispatch = useAppDispatch();
  const actionRef = useRef();
  const {pathname} = useLocation();
  const tourName = useAppSelector(selectTourName);
  const touring = useAppSelector(selectTouring);
  const userList = useAppSelector(selectUsers);
  const roleList = useAppSelector(selectRoles);

  useEffect(() => {
    dispatch(getRoles({params:{}}))
    // getColumns()
  }, [])

  /** 导游逻辑 */
  const ref1 = useRef(null);
  const ref2 = useRef(null);
  const closeTouring = useCallback(()=>{
    dispatch(appActions.startTour(false))
  },[])
  const steps = [
    {
      title: '查询面板',
      description: '这是一个用于用户管理的查询、编辑、新增组件',
      target: () => ref1.current,
    },
    {
      title: '创建用户',
      description: '点击创建按钮,会在表格中生产一行创建表单',
      target: () => ref2.current,
    },
  ];

  const getColumns = useMemo(()=>{
    return columnsFactory({
      onEditRow:true,
      dataSource: [
        {
          title: '用户名',
          dataIndex: 'userName',
        },
        {
          title: '超级管理员',
          dataIndex: 'superAdmin',
        },
        {
          title: '邮箱',
          dataIndex: 'email',
        },
        {
          title: '角色名称',
          dataIndex: 'roleName',
          valueType: 'select',
          fieldProps: {
            options: optionFactory(roleList)
          }
        },
        {
          title: '管理员',
          dataIndex: 'isAdmin',
        }
      ]
    })
  },[roleList])

  return (
    <>
      <Tour open={tourName === pathname && touring} onClose={closeTouring} steps={steps}/>
      <div ref={ref1}>
        <ProTable
          {...ProTableDefault}
          rowKey="key"
          headerTitle="用户列表"
          actionRef={actionRef}
          columns={getColumns}
          request={async (params) => {
            await dispatch(getUsers({params}))
          }}
          dataSource={userList}
          editable={{
            type: 'multiple',
            onSave: async (rowKey, params, row) => {
              const newObj = JSON.stringify(params)
              const oldObj = JSON.stringify(row)
              if (newObj !== oldObj) {
                await dispatch(createUser({ params }))
              }
            },
          }}
          pagination={{
            pageSize: 5,
            onChange: (page) => console.log(page),
          }}
          toolBarRender={() => [
            <Button
              ref={ref2}
              key="button"
              icon={<PlusOutlined/>}
              onClick={() => {
                actionRef.current?.addEditRecord?.({
                  key: (Math.random() * 1000000).toFixed(0)
                }, {position: "top"});
              }}
              type="primary"
            >
              新建
            </Button>
          ]}
        />
      </div>
    </>
  );
};
