import { Z1_APIgetDictZhi } from '@/store/action/Z1dict'
import { Checkbox, Collapse, CollapseProps, Modal, Tree } from 'antd'
import { FC, useEffect, useState } from 'react'

export interface RelicModalProps {
  isModalOpen: boolean
  checkedIds: string[][]
  setIsModalOpen: (v: boolean) => void
  onChange: (v: string[][]) => void
  onColumnChange?: (v: any[]) => void
}

const getMatchedItems = (res: any[], checkedIds: string[]) => {
  const result: { title: string; dataIndex: string }[] = []

  function traverse(nodes: any[]) {
    for (const node of nodes) {
      if (checkedIds.includes(node.id || node.value)) {
        result.push({ title: node.name || node.label, dataIndex: node.id || node.value })
      }
      if (node.children) {
        traverse(node.children)
      }
    }
  }

  traverse(res)
  return result
}

export const RelicModal: FC<RelicModalProps> = ({
  isModalOpen,
  checkedIds,
  setIsModalOpen,
  onChange,
  onColumnChange
}) => {
  const [cate1List, setCate1List] = useState<any[]>([])
  const [cate2List, setCate2List] = useState<any[]>([])
  const [cate3List, setCate3List] = useState<any[]>([])
  const [checked1Ids, setChecked1Ids] = useState<string[]>([])
  const [checked2Ids, setChecked2Ids] = useState<string[]>([])
  const [checked3Ids, setChecked3Ids] = useState<string[]>([])
  const categories: CollapseProps['items'] = [
    {
      label: '文物类别',
      key: 12001,
      children: (
        <Checkbox.Group value={checked1Ids} options={cate1List} onChange={v => setChecked1Ids(v)} />
      )
    },
    {
      label: '馆内分类1',
      key: 12015,
      children: (
        <Checkbox.Group value={checked2Ids} options={cate2List} onChange={v => setChecked2Ids(v)} />
      )
    },
    {
      label: '馆内分类2',
      key: 12016,
      children: (
        <Tree
          checkable
          checkedKeys={checked3Ids}
          treeData={cate3List}
          fieldNames={{ title: 'name', key: 'id' }}
          onCheck={v => setChecked3Ids(v as string[])}
        />
      )
    }
  ]

  const handleOk = () => {
    onChange([[...checked1Ids], [...checked2Ids], [...checked3Ids]])
    setIsModalOpen(false)
  }

  const handleCancel = () => {
    setIsModalOpen(false)
  }

  const getList = async (id: number) => {
    const res = await Z1_APIgetDictZhi(`${id}`)
    return res
  }

  const init = () => {
    Promise.all([
      getList(categories[0].key as number),
      getList(categories[1].key as number),
      getList(categories[2].key as number)
    ]).then(res => {
      setCate1List(res[0].data.map((i: any) => ({ label: i.name, value: i.id })))
      setCate2List(res[1].data.map((i: any) => ({ label: i.name, value: i.id })))
      setCate3List(res[2].data)
    })
  }

  useEffect(() => {
    init()
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  useEffect(() => {
    if (isModalOpen) {
      setChecked1Ids(checkedIds[0])
      setChecked2Ids(checkedIds[1])
      setChecked3Ids(checkedIds[2])
    }
  }, [checkedIds, isModalOpen])

  useEffect(() => {
    onColumnChange?.([
      ...getMatchedItems(cate1List, checkedIds[0]),
      ...getMatchedItems(cate2List, checkedIds[1]),
      ...getMatchedItems(cate3List, checkedIds[2])
    ])
  }, [cate1List, cate2List, cate3List, checkedIds, onColumnChange])

  return (
    <Modal
      title='统计分类'
      destroyOnClose
      width={800}
      open={isModalOpen}
      onOk={handleOk}
      onCancel={handleCancel}
    >
      <Collapse items={categories} defaultActiveKey={categories.map(i => i.key as number)} />
    </Modal>
  )
}
