import { FC, useCallback, useEffect, useRef, useState } from 'react'
import style from './index.module.scss'
import MyTable from '@/components/MyTable'
import { NUMBER_OF_COLLECTION_COLUMNS } from './constants'
import { Button, Select, Table } from 'antd'
import { A1_APIGetCheck } from '@/store/action/A1dataSta'
import dayjs from 'dayjs'
import { RelicModal } from '../RelicModal'
import { exportTempExcel } from '@/utils/exportExcelUtils'

export const A1Tab1: FC = () => {
  const [prevYearData, setPrevYearData] = useState<any[]>([])
  const [curYearData, setCurYearData] = useState<any[]>([])
  const [addData, setAddData] = useState<any[]>([])
  const [columns, setColumns] = useState<any[]>([])
  const [customData, setCustomData] = useState<any[]>([])

  const [relicModalOpen, setRelicModalOpen] = useState(false)
  const [checkedRelicIds, setCheckedRelicIds] = useState<string[][]>([
    ['12501', '12502', '12503', '12504', '12505'],
    [],
    []
  ])

  const getDetail = async (year: number) => {
    const res = await A1_APIGetCheck(year)
    return res.data && res.data.snap ? (JSON.parse(res.data.snap) as Record<string, number>) : null
  }

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

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

    return years
  }

  const years = useRef(getYearList())
  const [curYear, setCurYear] = useState(years.current[0])

  const initData = useCallback(async () => {
    const curRes = await getDetail(curYear)
    const prevRes = await getDetail(curYear - 1)
    const _addData = {
      id: 1,
      totalIncrease: 0,
      totalDecrease: 0,
      level0Increase: 0,
      level0Decrease: 0,
      level1Increase: 0,
      level1Decrease: 0,
      level2Increase: 0,
      level2Decrease: 0,
      level3Increase: 0,
      level3Decrease: 0,
      level4Increase: 0,
      level4Decrease: 0
    }

    const levels = ['total', 'level0', 'level1', 'level2', 'level3', 'level4']
    levels.forEach(level => {
      if (!curRes || !prevRes) return

      const curProp =
        level === 'total' ? 'total' : `pcs${level.charAt(0).toUpperCase()}${level.slice(1)}`
      const diff = curRes[curProp] - prevRes[curProp]
      if (diff) {
        // @ts-ignore
        _addData[`${level}${diff > 0 ? 'Increase' : 'Decrease'}`] = Math.abs(diff)
      }
    })

    setCurYearData(
      curRes
        ? [
            {
              ...curRes,
              id: 1
            }
          ]
        : []
    )

    setPrevYearData(
      prevRes
        ? [
            {
              ...prevRes,
              id: 1
            }
          ]
        : []
    )
    setAddData([_addData])
  }, [curYear])

  const handleColumnChange = useCallback(
    (v: any[]) => {
      const flat = v.flat().map(i => [i.title, i.dataIndex])
      if (!flat.length || !curYearData.length) return
      const tempColumns: any[] = []
      const tempData: Record<string, number> = {
        id: 1
      }
      flat.forEach(arr => {
        const keys = Object.keys(curYearData[0])
        tempData[`${arr[1]}Increase`] = 0
        tempData[`${arr[1]}Decrease`] = 0
        if (keys.includes(`${arr[1]}`)) {
          const diff = (curYearData[0]?.[arr[1]] || 0) - (prevYearData[0]?.[arr[1]] || 0)
          tempData[`${arr[1]}${diff > 0 ? 'Increase' : 'Decrease'}`] = Math.abs(diff)
        }

        tempColumns.push({
          title: arr[0],
          children: [
            {
              title: '增',
              dataIndex: arr[1] + 'Increase',
              align: 'center'
            },
            {
              title: '减',
              dataIndex: arr[1] + 'Decrease',
              align: 'center'
            }
          ]
        })
      })
      setColumns(tempColumns)
      setCustomData([tempData])
    },
    [curYearData, prevYearData]
  )

  const handleExport = () => {
    exportTempExcel(
      curYear + '年度核查统计',
      worksheet => {
        const levels = ['total', 'level1', 'level2', 'level3', 'level0', 'level4']

        worksheet.addRow(['', ...NUMBER_OF_COLLECTION_COLUMNS.map(i => i[1])])
        worksheet.addRow(['', ...NUMBER_OF_COLLECTION_COLUMNS.map(i => prevYearData[0][i[2]] || 0)])
        worksheet.addRow(['', ...NUMBER_OF_COLLECTION_COLUMNS.map(i => i[1])])
        worksheet.addRow(['', ...NUMBER_OF_COLLECTION_COLUMNS.map(i => curYearData[0][i[2]] || 0)])
        worksheet.addRow(['', ...NUMBER_OF_COLLECTION_COLUMNS.map(i => i[1])])
        worksheet.addRow([
          '',
          ...levels.map(level => {
            const curProp =
              level === 'total' ? 'total' : `pcs${level.charAt(0).toUpperCase()}${level.slice(1)}`
            const diff = curYearData[0][curProp] - prevYearData[0][curProp]
            return !isNaN(diff) ? diff : 0
          })
        ])
        worksheet.addRow(['', ...columns.map(i => i.title)])
        worksheet.addRow([
          '',
          ...columns.map(
            // @ts-ignore
            i => (customData[`${i.id}Increase`] || 0) - (customData[`${i.id}Decrease`] || 0)
          )
        ])
        worksheet.mergeCells('A1:A2')
        worksheet.mergeCells('A3:A4')
        worksheet.mergeCells('A5:A6')
        worksheet.mergeCells('A7:A8')
        worksheet.getCell('A1').value = '上一年度馆藏数量'
        worksheet.getCell('A3').value = '核查年度馆藏数量'
        worksheet.getCell('A5').value = '馆藏数量增减情况'
        worksheet.getCell('A7').value = '馆藏文物增加类别明细'
        ;[20, 10, 10, 10, 10, 10, 10].forEach((width: number, index: number) => {
          worksheet.getColumn(index + 1).width = width
        })
      },
      [8, Math.max(columns.length, NUMBER_OF_COLLECTION_COLUMNS.length + 1)]
    )
  }

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

  return (
    <>
      <div style={{ textAlign: 'right' }}>
        <Button onClick={handleExport}>导出表格</Button>
      </div>
      <div className={style.header}>
        <h3>上一年度馆藏数量</h3>
      </div>
      <MyTable
        size='small'
        bordered
        pagination={false}
        columnsTemp={NUMBER_OF_COLLECTION_COLUMNS}
        list={prevYearData}
      />

      <div className={style.header}>
        <h3>核查年度馆藏数量</h3>

        <Select
          value={curYear}
          placeholder='请选择核查年度'
          options={years.current.map(year => ({ label: year, value: year }))}
          onChange={v => setCurYear(v)}
        />
      </div>
      <MyTable
        size='small'
        bordered
        pagination={false}
        columnsTemp={NUMBER_OF_COLLECTION_COLUMNS}
        list={curYearData}
      />

      <div className={style.header}>
        <h3>馆藏数量增减情况</h3>
      </div>
      <Table
        size='small'
        rowKey='id'
        columns={[
          {
            title: '藏品总数',
            children: [
              {
                title: '增',
                dataIndex: 'totalIncrease',
                align: 'center'
              },
              {
                title: '减',
                dataIndex: 'totalDecrease',
                align: 'center'
              }
            ]
          },
          {
            title: '一级藏品',
            children: [
              {
                title: '增',
                dataIndex: 'level1Increase',
                align: 'center'
              },
              {
                title: '减',
                dataIndex: 'level1Decrease',
                align: 'center'
              }
            ]
          },
          {
            title: '二级藏品',
            children: [
              {
                title: '增',
                dataIndex: 'level2Increase',
                align: 'center'
              },
              {
                title: '减',
                dataIndex: 'level2Decrease',
                align: 'center'
              }
            ]
          },
          {
            title: '三级藏品',
            children: [
              {
                title: '增',
                dataIndex: 'level3Increase',
                align: 'center'
              },
              {
                title: '减',
                dataIndex: 'level3Decrease',
                align: 'center'
              }
            ]
          },
          {
            title: '未定级',
            children: [
              {
                title: '增',
                dataIndex: 'level0Increase',
                align: 'center'
              },
              {
                title: '减',
                dataIndex: 'level0Decrease',
                align: 'center'
              }
            ]
          },
          {
            title: '一般文物',
            children: [
              {
                title: '增',
                dataIndex: 'level4Increase',
                align: 'center'
              },
              {
                title: '减',
                dataIndex: 'level4Decrease',
                align: 'center'
              }
            ]
          }
        ]}
        dataSource={addData}
        bordered
        pagination={false}
      />

      <div className={style.header}>
        <h3>馆藏文物增加类别明细</h3>

        <Button type='primary' onClick={() => setRelicModalOpen(true)}>
          设置统计分类
        </Button>
      </div>
      {columns.length ? (
        <Table
          rowKey='id'
          size='small'
          columns={columns}
          dataSource={customData}
          bordered
          pagination={false}
        />
      ) : undefined}

      <RelicModal
        checkedIds={checkedRelicIds}
        isModalOpen={relicModalOpen}
        setIsModalOpen={setRelicModalOpen}
        onChange={setCheckedRelicIds}
        onColumnChange={handleColumnChange}
      />
    </>
  )
}
