import { PlusOutlined} from '@ant-design/icons';
import {ProTable} from '@ant-design/pro-components';
import {Button, Tour} from 'antd';
import {useCallback, 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} from '../../../utils/columnsFactory.jsx'
import {ProTableDefault, STATUS_TYPE} from '../../constants.js'
import {selectRoles} from "../MainPage/slice/selectors";
import {deleteRoles, getRoles, saveOrUpdateRole} from "../MainPage/slice/thunks";
import {appActions} from "../../slice";
import useI18NPrefix from "../../hooks/useI18NPrefix";

export const RoleManagePage = () => {
  const t = useI18NPrefix('global');
  const dispatch = useAppDispatch();
  const actionRef = useRef();
  const {pathname} = useLocation();
  const touring = useAppSelector(selectTouring);
  const tourName = useAppSelector(selectTourName);
  const roleList = useAppSelector(selectRoles);

  /** 导游逻辑 */
  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 columns = columnsFactory({
    onEditRow:true,
    dataSource:[
      {
        title: t("columns.role")+t("columns.name"),
        dataIndex: 'name',
      },
      {
        title: t("columns.status"),
        dataIndex: 'status',
        valueType: 'select',
        valueEnum: STATUS_TYPE
      }
    ]
  })

  // 保存行数据
  const onSave = useCallback(async (rowKey, params, row) => {
    const newObj = JSON.stringify(params)
    const oldObj = JSON.stringify(row)
    if (newObj !== oldObj) {
      await dispatch(
        saveOrUpdateRole({
          params,
          resolve: () => {
            actionRef.current?.reload()
          },
        })
      )
    }
  },[])

  // 删除行数据
  const onDelete = useCallback(async (rowKey, data) => {
    const {payload} = await dispatch(deleteRoles(data?.id))
    if (payload){
      actionRef.current?.reload()
    }
  },[])

  return (
    <>
      <Tour open={tourName === pathname && touring} onClose={closeTouring} steps={steps}/>
      <div ref={ref1}>
        <ProTable
          {...ProTableDefault}
          rowKey="key"
          headerTitle={t("title.roles")}
          actionRef={actionRef}
          columns={columns}
          dataSource={roleList}
          request={async (params) =>
            await dispatch(getRoles({params}))
          }
          editable={{
            type: 'multiple',
            onSave,
            onDelete
          }}
          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"
            >
              {t("button.create")}
            </Button>,
          ]}
        />
      </div>
    </>
  );
};
