import { ExampleHeader } from './header'
import { exampleTitleColumn, exampleTimeColumn } from './columns'
import { Table, ActionsButton } from 'components'
import { useThunkPaging } from 'hook'
import { Dropdown, Menu, Button } from 'antd'
import { DownOutlined } from '@ant-design/icons'
import { useSelector, examplesSelector, fetchExamples } from 'store'
import { EditExampleTitle, InsertExample } from './edit'
import { setExample, repExampleScenes, deleteExample, getToken, getExampleScenes } from 'api'
import { ExampleScenes } from './scene/list'
import { useState } from 'react'
import { alert, confirm, getHref, onlyOpenWindow } from 'utils'
import { SceneType, SceneTypeDomain, SceneTypePaths } from 'constant'
import { RoutePath, fillRoutePath } from 'router'

import type { ColumnAction } from 'components'
import type { MenuProps } from 'antd'
import type { Example } from 'api'
import type { ExampleColumn } from './columns'

export type ExampleActionProps = {
  example: Example,
  deleteExample: () => void
  query: () => void,
  sceneManage?: (example: Example) => void
  fuse?: (example: Example) => void
  getView?: (example: Example) => void
  record?: (example: Example) => void
  file?: (example: Example) => void
}

export const ExampleAction = ({ example, query, deleteExample, ...actionCallback }: ExampleActionProps) => {
  const actions: ColumnAction[] = [
    { text: '查看', action: query },
    { text: '删除', action: deleteExample , bind: { danger: true } }
  ]
  const menus = [
    { key: 'sceneManage', label: '场景管理' },
    { key: 'fuse', label: '多元融合' },
    { key: 'getView', label: '视图提取' },
    { key: 'record', label: '屏幕录制' },
    { key: 'file', label: '卷宗管理' },
  ]
  const handleMenuClick: MenuProps['onClick']  = (menu) => {
    (actionCallback as any)[menu.key]();
  }

  for (let i = 0; i < menus.length; i++) {
    if (!(menus[i].key in actionCallback)) {
      menus.splice(i--, 1)
    }
  }

  const renderMenus = menus.length 
    ? (<Dropdown overlay={<Menu items={menus} onClick={handleMenuClick} />}>
          <Button type="link" >
            编辑<DownOutlined />
          </Button>
      </Dropdown>)
    : null

  return (
    <>
      {renderMenus}
      <ActionsButton actions={actions} />
    </>
  )
}

export const ExamplePage = () => {
  const examples = useSelector(examplesSelector)
  const states = useThunkPaging({ caseTitle: '' }, fetchExamples)
  const [[paging, setPaging], [params, setParams], refresh] = states
  const [scenesCaseId, setScenesCaseId] = useState<Example['caseId'] | null>(null)
  const [inInsert, setInInsert] = useState(false)
  const getFuseCodeLink = (caseId: Example['caseId'], query?: boolean) => {
    const params: { token?: string, caseId: string } = { 
      token: getToken() || undefined,
      caseId: caseId.toString()
    }
    if (query) {
      delete params.token
    }
    return getHref(SceneTypeDomain[SceneType.SWMX]!, SceneTypePaths[SceneType.SWMX][0], params)
  }
  const checkScenesOpen = async (caseId: Example['caseId'], url: URL | string) => {
    const scenes = await getExampleScenes({ caseId })
    console.log(url)
    if (!scenes.length) {
      alert('当前案件下无场景，请先添加场景。')
    } else {
      onlyOpenWindow(url)
    }
  }
  

  const columns: ExampleColumn[] = [
    {
      ...exampleTitleColumn,
      render: (_, record) => (
        <EditExampleTitle 
          example={record} 
          onChangeTitle={async (caseTitle) => {
            await setExample({ caseTitle, caseId: record.caseId })
            await refresh()
          }}
        />
      )
    }, 
    exampleTimeColumn,
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <ExampleAction
          deleteExample={async () => {
            if (await confirm('确定要删除此数据？')) {
              await deleteExample({ caseId: record.caseId })
              await refresh()
            }
          }}
          example={record}
          sceneManage={() => setScenesCaseId(record.caseId)}
          file={() => {
            const url = new URL(location.href);
            url.hash = fillRoutePath(RoutePath.files, { id: record.caseId.toString() })
            window.open(url)
            // navigate()
          }}
          query={() => checkScenesOpen(record.caseId, `${getFuseCodeLink(record.caseId, true)}&share=1#show/summary`)}
          fuse={() => checkScenesOpen(record.caseId, `${getFuseCodeLink(record.caseId)}#fuseEdit/merge`)}
          getView={() => checkScenesOpen(record.caseId, `${getFuseCodeLink(record.caseId)}#sceneEdit/view`)}
          record={() => checkScenesOpen(record.caseId, `${getFuseCodeLink(record.caseId)}#sceneEdit/record`)} 
        /> 
      )
    }
  ]
  const renderAddExample = inInsert 
    && <InsertExample 
        onClose={() => setInInsert(false)} 
        onChangeTitle={async (caseTitle) => {
          await setExample({ caseTitle })
          await refresh()
          setInInsert(false)
        }}
      />
  const renderEditScene = scenesCaseId 
    && <ExampleScenes
        caseId={scenesCaseId} 
        onClose={() => setScenesCaseId(null)} 
        onChangeScenes={(idents) => repExampleScenes({ sceneNumParam: idents, caseId: scenesCaseId })}
      />

  return (
    <div className='content-layout'>
      { renderAddExample }
      { renderEditScene }
      <ExampleHeader 
        onBeforeCreate={() => setInInsert(true)}
        onSearch={setParams}
      />
      <Table
        unDataMsg={params.caseTitle ? '未搜索到结果' : '暂无数据'} 
        rowKey={'caseId'}
        columns={columns} 
        data={examples}
        paging={paging}
        onChangePaging={setPaging}
      />
    </div>
  )
}

export default ExamplePage