import { Button, message } from 'antd';
import React, { useEffect } from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { useSingleState } from 'nice-hooks';
import ReactQuill from 'react-quill';
import 'react-quill/dist/quill.snow.css';
import { Memory } from './data.d';
import service from './service';

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<Memory>({
    id: null,
    userId: null,
    front: '',
    back: '',
    tag: '',
  });

  /**
   * 查询用户待提醒数量
   * @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) });
        return true;
      }
      return false;
    } catch (error) {
      hide();
      message.error('查询异常！');
      return false;
    }
  };
  useEffect(() => {
    countRemind();
  }, []);

  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();
  };

  const memorySuccess = async (factorInt: number) => {
    const res = await service.memorySuccess({ id: memory.id, factor: factorInt });
    if (res.success) {
      setMemory({ ...memory, ...res.data });
    } else {
      changStepMain();
    }
  };

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

  /**
   * 清空memory
   */
  const clearMemory = () => {
    setMemory({
      id: null,
      front: '',
      back: '',
    });
  };

  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>
          问题
          <hr />
          <div dangerouslySetInnerHTML={{ __html: memory.front }} />
          <hr />
          {state.showBack ? (
            <div>
              <div dangerouslySetInnerHTML={{ __html: memory.back }} />
              <hr />
              <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>
              <p />
              <div>
                <Button
                  type="primary"
                  onClick={async () => {
                    await service.restart(memory);
                    findNextLine();
                  }}
                >
                  重新开始复习
                </Button>
                <span> </span>
                <Button
                  type="primary"
                  onClick={async () => {
                    await service.noMemory(memory);
                    findNextLine();
                  }}
                >
                  不在复习
                </Button>
                <span> </span>
                <Button
                  type="primary"
                  onClick={async () => {
                    await service.delete(memory);
                    findNextLine();
                  }}
                >
                  删除
                </Button>
              </div>
              <p />
              <div>
                <Button
                  type="primary"
                  onClick={() => {
                    changStepAdd();
                  }}
                >
                  编辑
                </Button>
              </div>
            </div>
          ) : (
            <div>
              <Button
                type="primary"
                onClick={() => {
                  setState({ showBack: true });
                }}
              >
                显示答案
              </Button>
            </div>
          )}
        </div>
      ) : null}

      {state.step === Step.ADD ? (
        <div>
          <h4>正面</h4>
          <ReactQuill
            theme="snow"
            value={memory.front}
            onChange={(value) => {
              setMemory({ front: value });
            }}
          />
          <p />
          <h4>反面</h4>
          <ReactQuill
            theme="snow"
            value={memory.back}
            onChange={(value) => {
              setMemory({ back: value });
            }}
          />
          <p />
          <Button
            type="primary"
            onClick={async () => {
              let res;
              if (memory != null && memory.id != null) {
                res = await service.update(memory);
              } else {
                res = await service.insert(memory);
              }
              if (res.success) {
                message.info('操作成功');
                clearMemory();
              } else {
                message.info(`操作失败: ${res.message}`);
              }
            }}
          >
            确定
          </Button>
          <span> </span>
          <Button
            type="primary"
            onClick={() => {
              clearMemory();
              changStepMain();
            }}
          >
            关闭
          </Button>
        </div>
      ) : null}
    </PageHeaderWrapper>
  );
};

export default TableList;
