import {Button, message} from 'antd';
import React, {useEffect} from 'react';
import {PageHeaderWrapper} from '@ant-design/pro-layout';
import {useSingleState} from 'nice-hooks';
import Quill from "@/pages/Memory/components/Quill";
import {TableListItem} from '../MemoryList/data.d';
import service from './service';
import UpdateForm from "@/pages/Memory/components/UpdateForm";
import styles from './index.less'

enum Step {
  MAIN = 0,
  MEMORY = 1,
  ADD = 2,
}

interface State {
  remindCount: number;
  step: Step;
  showBack?: boolean;
}

const TableList: React.FC<{}> = () => {
  const [state, setState] = useSingleState<State>({
    remindCount: 0,
    step: Step.MAIN, // 0 主页，1 复习，2 添加
    showBack: false,
  });

  const [memory, setMemory] = useSingleState<TableListItem>({
    back: "",
    front: "",
    id: undefined,
    period: 0,
    remindTime: new Date(),
    tag: "",
    updateTime: "",
    userId: 0
  });


  /**
   * 查询用户待提醒数量
   * @param fields
   */
  const countRemind = async () => {
    const hide = message.loading('正在查询');
    try {
      const res = await service.countRemind({});
      hide();
      if (res.success) {
        setState({remindCount: parseInt(res.data, 10)});
      }
    } catch (error) {
      hide();
      message.error('查询异常！');
    }
  };
  useEffect(() => {
    countRemind();
    setTimeout(() => {
      countRemind();
    }, 1000 * 60 * 60)  // 每隔一个小时查询一次

    document.onkeydown = (ev)=> {
      if (ev.key === ' ' && state.step === Step.MEMORY) {
        ev.preventDefault(); // 关闭浏览器快捷键
        if (state.showBack == false) {
          setState({showBack: true});
        } else {
          memorySuccess(2);
        }

      }

    }
  }, []);

  /**
   * 清空memory
   */
  const clearMemory = () => {
    setMemory({
      id: undefined,
      front: '',
      back: '',
    });
  };
  /**
   * 每次修改step，都关闭背面
   */
  useEffect(() => {
    setState({showBack: false});
    clearMemory();
  }, [state.step]);

  useEffect(() => {
    // console.log(state)
    // console.log(memory)
  });
  /**
   * 进入统计页面
   */
  const changStepMain = () => {
    setState({step: Step.MAIN});
    countRemind();
  };

  const findNextLine = async () => {
    const res = await service.findNext({});
    if (res.success) {
      setMemory({...memory, ...res.data});
    } else {
      changStepMain();
    }
  };

  /**
   * 初次进入复习页面
   */
  const changStepMemory = async () => {
    if (state.remindCount <= 0) {
      message.info('已经复习完了哟！');
      return;
    }
    setState({step: Step.MEMORY});
    await findNextLine();
  };
  /**
   * 处理返回值
   * @param res
   */
  const memoryRes = (res: any) => {
    if (res.success) {
      setState({showBack: false});
      setMemory({...memory, ...res.data});
    } else {
      changStepMain();
    }

  }
  const memorySuccess = async (factorInt: number) => {
    memoryRes(await service.memorySuccess({id: memory.id, factor: factorInt}));

  };


  const changStepAdd = () => {
    setState({step: Step.ADD});
  };

  return (
    <PageHeaderWrapper title={false}>
      {state.step === Step.MAIN ? (
        <div>
          <div>待复习: {state.remindCount}</div>
          <p/>
          <Button type="primary" size="large" onClick={changStepMemory}>
            复习
          </Button>
          <p/>
          <Button type="primary" size="large" onClick={changStepAdd}>
            添加
          </Button>
        </div>
      ) : null}

      {state.step === Step.MEMORY ? (
        <div>
          问题:
          <p/>
          <Quill
            readonly
            onChange={() => {
            }}
            value={memory.front}/>
          <p/>
          {state.showBack ? (
            <div>
              <Quill
                readonly
                onChange={() => {
                }}
                value={memory.back}/>
              <p/>
              <div className={styles.divBottom}>
                <Button
                  type="primary"
                  onClick={() => {
                    memorySuccess(0.5);
                  }}
                >
                  生疏
                </Button>
                <span> </span>
                <Button
                  type="primary"
                  onClick={() => {
                    memorySuccess(2);
                  }}
                >
                  一般(空格）
                </Button>
                <span> </span>
                <Button
                  type="primary"
                  onClick={() => {
                    memorySuccess(3);
                  }}
                >
                  简单
                </Button>
                <span> </span>
                <Button
                  type="primary"
                  onClick={async () => {
                    memoryRes(await service.delay(memory));
                  }}
                >
                  搁置
                </Button>
                <p/>
                <div>
                  <Button
                    type="primary"
                    onClick={async () => {
                      memoryRes(await service.restart(memory));
                    }}
                  >
                    重新开始复习
                  </Button>
                  <span> </span>
                  <Button
                    type="primary"
                    onClick={async () => {
                      memoryRes(await service.noMemory(memory));
                    }}
                  >
                    不在复习
                  </Button>
                  <span> </span>
                  <Button
                    type="primary"
                    onClick={async () => {
                      memoryRes(await service.delete(memory));
                    }}
                  >
                    删除
                  </Button>
                </div>
                <p/>
                <div>
                  <Button
                    type="primary"
                    onClick={() => {
                      changStepAdd();
                    }}
                  >
                    编辑
                  </Button>
                  <span> </span>
                  <Button
                    type="primary"
                    onClick={() => {
                      changStepMain();
                    }}
                  >
                    关闭
                  </Button>
                </div>
              </div>

            </div>
          ) : (
            <div>
              <Button
                type="primary"
                onClick={() => {
                  setState({showBack: true});
                }}
              >
                显示答案（空格）
              </Button>
            </div>
          )}
        </div>
      ) : null}

      {state.step === Step.ADD ? (
        <UpdateForm
          onCancel={() => {
            changStepMain();
          }}
          modalVisible={state.step === Step.ADD}
          values={memory}>
        </UpdateForm>
      ) : null}

    </PageHeaderWrapper>
  );
};

export default TableList;
