import { ArrowLeftOutlined } from "@ant-design/icons"
import { Button } from "antd"
import { useNavigate, fillRoutePath, RoutePath, usePathData } from "router"
import { saveAs } from 'utils'
import style from './style.module.scss'
import {
  BoardTypeDesc, 
  BoardType,
  saveBoard,
  TitleShapeData
} from 'api'

import { useEffect, useState } from "react"
import { Board, title } from "./board"
import type { SaveBoardProps } from 'api'

type HeaderProps = {
  board: Board
  type: BoardType
}
const Header = ({ board, type }: HeaderProps) => {
  const [backDisabled, setBackDisabled] = useState(true)
  const [forwardDisabled, setForwradDisabled] = useState(true)
  const path = usePathData()
  const caseId = path!.caseId
  const pathId = Number(path!.id)
  const pathType = path!.type as BoardType
  const navigate = useNavigate()
  const exportPng = async () => {
    const blob = await board.export()
    saveAs(blob, '现场图.png')
  }

  
  const save = async () => {
    const store = board.getStore()
    const titleShape = store.shapes.find(shape => shape.type === title) as TitleShapeData
    const blob = await board.export()
    const isNew = pathId === -1
    const body: SaveBoardProps = {
      caseId, 
      imgType: pathType,
      file: new File([blob], `${pathType}_${pathId}.png`),
      filesTitle: titleShape?.text || `${caseId}_${BoardTypeDesc[pathType]}`, 
      content: board.getStore()
    }
    if (!isNew) {
      body.filesId = pathId
    }
    const data = await saveBoard(body)

    if (isNew) {
      navigate(
        fillRoutePath(RoutePath.drawFile, { ...path as any, id: data.filesId.toString() }),
        { replace: true }
      )
    }
  }

  useEffect(() => {
    board.bus.on('backDisabled', setBackDisabled)
    board.bus.on('forwardDisabled', setForwradDisabled)

    return () => {
      board.bus.off('backDisabled', setBackDisabled)
      board.bus.off('forwardDisabled', setForwradDisabled)
    }
  }, [board])

  useEffect(() => {
    const keydownHandler = (ev: KeyboardEvent) => {
      if (ev.keyCode === 32) {
        board.viewInit()
      }
    }
    window.addEventListener('keydown', keydownHandler)
    return () => {
      window.removeEventListener('keydown', keydownHandler)
    }
  }, [board])

  return (
    <>
      <div className={style['df-header-left']}>
        <span className={`${style['df-header-back']} icon`} onClick={() => navigate(-1)}>
          <ArrowLeftOutlined />
          返回
        </span>
      </div>
      <h1 className={style['df-header-center']}>
        创建{ BoardTypeDesc[type] }
      </h1>
      <div className={style['df-header-right']}>
        <div className={style['df-header-action']}>
          <i className={`iconfont icon-repeal ${backDisabled ? 'disabled':  'icon'} `} 
            onClick={() => board.back()} 
          />
          <i className={`iconfont icon-recover ${forwardDisabled ? 'disabled':  'icon'} `} 
            onClick={() => board.forward()} 
          />
          <i className="iconfont icon-keyboard" />
        </div>
        <Button type="primary" size="middle" onClick={save}>保存</Button>
        <Button type="default" size="middle" onClick={exportPng}>导出</Button>
      </div>
    </>
  )
}

export default Header
