import {PlusOutlined} from '@ant-design/icons';
import {ProTable} from '@ant-design/pro-components';
import {Button, message, 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, updateUser} from "../MainPage/slice/thunks";
import {appActions} from "../../slice";
import useI18NPrefix from "../../hooks/useI18NPrefix";
import {encryptPassword} from "../../../utils/auth";

export const UserManagePage = () => {
  const t = useI18NPrefix('global');
  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:{}}))
  }, [])

  /** 导游逻辑 */
  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(()=>
    columnsFactory({
      onEditRow:true,
      dataSource: [
        {
          title: t("columns.userName"),
          dataIndex: 'userName',
        },
        {
          title: t("columns.displayName"),
          dataIndex: 'displayName',
        },
        {
          title:  t("columns.role"),
          dataIndex: 'roleId',
          valueType: 'select',
          fieldProps: {
            options: optionFactory(roleList)
          }
        },
        {
          title: t("columns.mobile"),
          dataIndex: 'mobile',
        },
        {
          title: t("columns.password"),
          dataIndex: 'password',
          valueType: 'password',
        }
      ]
    })
  ,[roleList])

  // 保存行数据
  const onSave = useCallback(async (rowKey, value) => {
    let params = Object.assign({}, value);

    params.password = encryptPassword(value.password);

    if (params?.id){
      await dispatch(updateUser({ params }))
    }else {
      await dispatch(createUser({ params }))
    }

    actionRef.current?.reload()
  },[])

  // 删除用户
  const onDelete = useCallback(async ()=>{
    message.warning("此功能暂未开启")
  },[])

  const onAddRow = ()=>{
    actionRef.current?.addEditRecord?.({
      key: (Math.random() * 1000000).toFixed(0)
    }, {position: "top"});
  }

  return (
    <>
      <Tour open={tourName === pathname && touring} onClose={closeTouring} steps={steps}/>
      <div ref={ref1}>
        <ProTable
          {...ProTableDefault}
          rowKey="key"
          headerTitle={t("title.users")}
          actionRef={actionRef}
          columns={getColumns}
          request={async (params) => {
            await dispatch(getUsers({params}))
          }}
          dataSource={userList}
          editable={{
            type: 'multiple',
            onSave,
            onDelete
          }}
          pagination={{
            pageSize: 5,
            onChange: (page) => console.log(page),
          }}
          toolBarRender={() => [
            <Button
              ref={ref2}
              key="button"
              icon={<PlusOutlined/>}
              onClick={onAddRow}
              type="primary"
            >
              {t("button.create")}
            </Button>
          ]}
        />
      </div>
    </>
  );
};
