import { A1_APIGetStorage } from '@/store/action/A1dataSta'
import { Button, Select, Table } from 'antd'
import dayjs from 'dayjs'
import { isNumber } from 'lodash'
import { FC, useCallback, useEffect, useMemo, useRef, useState } from 'react'
import style from '../Tab2/index.module.scss'
import { StorageModal } from './components/StorageModal'
import { D2_APIgetList } from '@/store/action/D2storSet'
import { useDispatch, useSelector } from 'react-redux'
import { RootState } from '@/store'
import { RelicModal } from '../RelicModal'
import { exportTempExcel } from '@/utils/exportExcelUtils'

const getYearList = () => {
  const currentYear = dayjs().year()
  const years = []

  for (let i = 0; i < 10; i++) {
    years.push(currentYear - i)
  }

  return years
}

export const A1Tab3: FC = () => {
  const dispatch = useDispatch()
  const years = useRef(getYearList())
  const [curYear, setCurYear] = useState(years.current[0])
  const [storageModalOpen, setStorageModalOpen] = useState(false)
  const [relicModalOpen, setRelicModalOpen] = useState(false)
  const [checkedRelicIds, setCheckedRelicIds] = useState<string[][]>([
    ['12501', '12502', '12503', '12504', '12505'],
    [],
    []
  ])
  const [checkedStorageIds, setCheckedStorageIds] = useState<number[]>([])
  const { list: storageIdArr } = useSelector((state: RootState) => state.D2storSet.tableInfo)
  const [list, setList] = useState<any[]>([])
  const [relicColumns, setRelicColumns] = useState<any[]>([])
  const columns = useMemo(
    () => [
      {
        width: 100,
        title: '级别/数量/类别',
        dataIndex: 'custom',
        colSpan: 2,
        onCell: (record: any, index: any) => {
          const obj = {
            rowSpan: 0,
            colSpan: 1
          }
          if (index === 0) {
            obj.rowSpan = 3
          } else if (isNumber(index) && index > 2) {
            obj.rowSpan = 1
            obj.colSpan = 2
          }
          return obj
        }
      },
      {
        width: 100,
        dataIndex: 'level',
        colSpan: 0,
        onCell: (record: any, index: any) => {
          const obj = {
            rowSpan: 0,
            colSpan: 1
          }
          if (isNumber(index) && index <= 2) obj.rowSpan = 1
          return obj
        }
      },
      ...relicColumns.map(i => ({
        ...i,
        render: (value?: number) => value ?? 0
      }))
    ],
    [relicColumns]
  )
  const dataSource = useRef<any[]>([])

  useEffect(() => {
    dispatch(D2_APIgetList({ pageNum: 1, pageSize: 99999 }))
  }, [dispatch])

  const getDetail = useCallback(async () => {
    if (!checkedStorageIds.length) {
      setList([])
      return
    }

    const res = await A1_APIGetStorage(curYear)
    const list = res.data.filter((item: any) => checkedStorageIds.includes(item.storageId))
    let temp = [
      {
        id: 1,
        custom: '珍贵文物',
        level: '一级'
      },
      {
        id: 2,
        level: '二级'
      },
      {
        id: 3,
        level: '三级'
      },
      {
        id: 4,
        custom: '未定级'
      },
      {
        id: 5,
        custom: '一般文物'
      }
    ]
    const countMap = list.reduce((acc: any, item: any) => {
      const key = `${item.dictLevel}_${item.dictType}`
      acc.set(key, (acc.get(key) || 0) + 1)
      return acc
    }, new Map<string, number>())

    temp = temp.map(item => {
      const matchedKey = [...countMap].find(([key, num]) => {
        const [dictLevel] = key.split('_')
        return dictLevel === item.level || dictLevel === item.custom
      })

      if (matchedKey) {
        const [key, num] = matchedKey
        const dictType = key.split('_')[1]
        return {
          ...item,
          [dictType]: num
        }
      }
      return item
    })

    setList(temp)
    dataSource.current = res.data
  }, [checkedStorageIds, curYear])

  const handleExport = async () => {
    const _columns = columns.filter(i => Boolean(i.title))

    exportTempExcel(
      curYear + '年度库房藏品',
      worksheet => {
        worksheet.addRow(['', ..._columns.map(i => i.title)])

        list.forEach(item => {
          worksheet.addRow([
            '',
            item.level || item.custom,
            ...checkedRelicIds.flat().map(id => item[id] || 0)
          ])
        })
        ;[10, ..._columns.map(i => 10)].forEach((width: number, index: number) => {
          worksheet.getColumn(index + 1).width = width
        })

        worksheet.mergeCells('A1:B1')
        worksheet.mergeCells('A2:A4')
        worksheet.mergeCells('A5:B5')
        worksheet.mergeCells('A6:B6')
        worksheet.getCell('A1').value = '级别/数量/类别'
        worksheet.getCell('A2').value = '珍贵文物'
        worksheet.getCell('A5').value = '未定级'
        worksheet.getCell('A6').value = '一般文物'
      },
      [list.length + 1, _columns.length + 1]
    )
  }

  useEffect(() => {
    getDetail()
  }, [getDetail])

  useEffect(() => {
    setCheckedStorageIds(storageIdArr.map(i => i.id))
  }, [storageIdArr])

  return (
    <div className={style.A1Tab2}>
      <div className='C1top'>
        <Select
          value={curYear}
          placeholder='请选择统计年度'
          style={{ width: 120 }}
          options={years.current.map(year => ({ label: year, value: year }))}
          onChange={v => setCurYear(v)}
        />
        <Button type='primary' onClick={() => setRelicModalOpen(true)}>
          设置统计分类
        </Button>
        <Button onClick={() => setStorageModalOpen(true)}>设置统计库房</Button>
        <Button onClick={handleExport}>导出表格</Button>
      </div>

      <Table
        size='small'
        columns={columns}
        rowKey='id'
        dataSource={list}
        pagination={false}
        bordered
      />

      <StorageModal
        list={storageIdArr}
        value={checkedStorageIds}
        isModalOpen={storageModalOpen}
        setIsModalOpen={setStorageModalOpen}
        onChange={setCheckedStorageIds}
      />
      <RelicModal
        checkedIds={checkedRelicIds}
        isModalOpen={relicModalOpen}
        setIsModalOpen={setRelicModalOpen}
        onChange={setCheckedRelicIds}
        onColumnChange={setRelicColumns}
      />
    </div>
  )
}
