import {PlusOutlined} from '@ant-design/icons';
import {ProTable} from '@ant-design/pro-components';
import {Button, Modal, Tour} from 'antd';
import {useCallback, useEffect, useRef, useState} from 'react';
import {request} from '../../../utils/request.js';
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 {TimeCycleForm} from './TimeCycleForm'
import {styled} from 'styled-components'
import {ProTableDefault, STATUS_TYPE} from '../../constants.js'
import {appActions} from "../../slice";
import {periodList} from "../MainPage/slice/thunks";
import {selectPeriods} from "../MainPage/slice/selectors";
import useI18NPrefix from "../../hooks/useI18NPrefix";

export const TimeCycleManage = () => {
  const t = useI18NPrefix('global');
  const ref1 = useRef(null);
  const ref2 = useRef(null);
  const ref3 = useRef(null);
  const actionRef = useRef();
  const {pathname} = useLocation();
  const dispatch = useAppDispatch();
  const touring = useAppSelector(selectTouring);
  const tourName = useAppSelector(selectTourName);
  const [columns, setColumns] = useState([]);
  const [record,setRecord]=useState({});
  const periods = useAppSelector(selectPeriods);

  const baseColumns = [
    {
      title: t("columns.name"),
      dataIndex: 'name',
    },
    {
      title: t("columns.description"),
      dataIndex: 'description',
    },
    {
      title: t("columns.expr"),
      dataIndex: 'expr',
    },
    {
      title: t("columns.status"),
      dataIndex: 'status',
      valueType: 'select',
      valueEnum: STATUS_TYPE
    }
  ]

  /** 表单对话框 */
  const [isModalOpen, setIsModalOpen] = useState(false);
  const handleCancel = () => {
    setIsModalOpen(false);
  };

  /** 初始渲染的钩子 */
  useEffect(() => {
    getColumns()
  }, [])

  /** 格式话表头 */
  const getColumns = () => {
    const columnInfo = columnsFactory({
      dataSource: baseColumns,
      onEdit:handleEdit,
      ref:ref3
    })
    setColumns(columnInfo)
  }

  /** 打开 新增、编辑 对话框 */
  const handleEdit=(row)=>{
    setRecord(row);
    setIsModalOpen(true);
  }

  /** 提交表单 */
  const onSubmit = useCallback(
    async (values)=> {
      await request({
        url: '/semantic/period',
        data: values,
        method: "POST",
      })
      setIsModalOpen(false);
      actionRef.current?.reload();
    },[]
  );

  /** 导游步骤 */
  const closeTouring = useCallback(()=>{
    //setIsModalOpen(false)
    dispatch(appActions.startTour(false))
  },[])
  const steps = [
    {
      title: '时间周期面板',
      description: '这里是时间周期面板',
      target: () => ref1.current,
    },
    {
      title: '创建时间周期',
      description: '点击此按钮创建时间周期',
      target: () => ref2.current,
    },
    {
      title: '编辑时间周期',
      description: '点击此按钮可以对行数据进行数据操作',
      target: () => ref3.current,
    },
  ];

  return (
    <>
      <Tour open={tourName === pathname && touring} onClose={closeTouring} steps={steps}/>
      <div ref={ref1}>
        <ProTable
          {...ProTableDefault}
          headerTitle={t("title.timeCycle")}
          actionRef={actionRef}
          dataSource={periods}
          columns={columns}
          request={async (params) =>
            await dispatch(periodList({params}))
          }
          pagination={{
            pageSize: 5,
            onChange: (page) => console.log(page)
          }}
          toolBarRender={() => [
            <Button
              ref={ref2}
              key="button"
              icon={<PlusOutlined/>}
              onClick={()=>{
                handleEdit(null)
              }}
              type="primary"
            >
              {t("button.save")}
            </Button>
          ]}
        />
      </div>
      <CustomModal
        width={1000}
        title={<Title children={t("button.save")}/>}
        open={isModalOpen}
        footer={null}
        maskClosable={false}
        destroyOnClose
        onCancel={handleCancel}
      >
        <TimeCycleForm data={record} onSubmit={onSubmit} ref={ref2}/>
      </CustomModal>
    </>
  )
};

const Title = styled.div`
  margin-left: 24px;
`
const CustomModal = styled(Modal)`
  .ant-modal-content{
    padding: 24px 0;
  }
`
