import { A1_APIGetDynamic } from '@/store/action/A1dataSta'
import { Button, Select, Table } from 'antd'
import dayjs from 'dayjs'
import { FC, useCallback, useEffect, useRef, useState } from 'react'
import style from './index.module.scss'
import { RelicModal } from '../RelicModal'
import { exportTempExcel } from '@/utils/exportExcelUtils'
import { getExcelColumnLetter } from '@/utils/exportWordUtils'

const QUARTER_MAP: Record<number, string> = {
  1: '第一季度',
  2: '第二季度',
  3: '第三季度',
  4: '第四季度'
}

export const A1Tab2: FC = () => {
  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 [quarter, setQuarter] = useState<number>(1)
  const [list, setList] = useState<any[]>([])
  const [sourceData, setSourceData] = useState<any>({})

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

  const getDetail = useCallback(async () => {
    const res = await A1_APIGetDynamic({
      quarter,
      year: curYear
    })
    setSourceData(res.data)
  }, [curYear, quarter])

  const handleColumnChange = useCallback(
    (v: any[]) => {
      const temp: any[] = []

      if (sourceData[0])
        temp.push({
          name: '全部',
          id: 0,
          ...sourceData[0]
        })
      v.forEach(relic => {
        const i = sourceData[relic.dataIndex]
        if (i) {
          temp.push({
            id: relic.dataIndex,
            ...i,
            name: relic.title
          })
        } else {
          temp.push({
            id: relic.dataIndex,
            name: relic.title,
            pcsTotal: '-',
            pcsZj: '-',
            pcsJz: '-',
            pcsYj: '-',
            pcsSj: '-',
            pcsDb: '-',
            pcsOther: '-',
            cl1: '-',
            cl2: '-',
            cl3: '-',
            clTotal: '-',
            jc1: '-',
            jc2: '-',
            jc3: '-',
            jcTotal: '-'
          })
        }
      })
      setList(temp)
    },
    [sourceData]
  )

  const handleExport = () => {
    exportTempExcel(
      curYear + '库存文物动态统计',
      worksheet => {
        const line2 = [
          '',
          '合计',
          '新收',
          '',
          '',
          '',
          '',
          '其他增加',
          '提陈',
          '在陈',
          '退陈',
          '合计',
          '借出',
          '在借',
          '退还',
          '合计'
        ]
        worksheet.addRow([
          '',
          `${curYear}年${QUARTER_MAP[quarter]}库存数`,
          `${curYear}年${QUARTER_MAP[quarter]}增加数`
        ])
        worksheet.addRow(line2)
        worksheet.addRow(['', '', '征购', '捐赠', '移交', '上交', '调拨'])
        worksheet.mergeCells('A1:A3')
        worksheet.getCell('A1').value = '项目/类目/类别'
        worksheet.mergeCells('C1:H1')
        worksheet.mergeCells('I1:L1')
        worksheet.getCell('I1').value = '陈列'
        worksheet.mergeCells('M1:P1')
        worksheet.getCell('M1').value = '借出'
        worksheet.mergeCells('B2:B3')
        worksheet.mergeCells('C2:G2')
        worksheet.mergeCells('H2:H3')
        worksheet.getRow(1).height = 60
        line2.forEach((_, index) => {
          if (index < 8) return
          console.log(getExcelColumnLetter(index))
          worksheet.mergeCells(`${getExcelColumnLetter(index)}2:${getExcelColumnLetter(index)}3`)
        })
        list.forEach(i => {
          worksheet.addRow([
            i.name,
            i.pcsTotal,
            i.pcsZj,
            i.pcsJz,
            i.pcsYj,
            i.pcsSj,
            i.pcsDb,
            i.pcsOther,
            i.cl1,
            i.cl2,
            i.cl3,
            i.clTotal,
            i.jc1,
            i.jc2,
            i.jc3,
            i.jcTotal
          ])
        })
        ;[20].forEach((width: number, index: number) => {
          worksheet.getColumn(index + 1).width = width
        })
      },
      [3 + list.length, 16]
    )
  }

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

  return (
    <div className={style.A1Tab2}>
      <div className='C1top'>
        <Button type='primary' onClick={() => setRelicModalOpen(true)}>
          设置统计分类
        </Button>
        <Select
          value={curYear}
          placeholder='请选择年份'
          style={{ width: 120 }}
          options={years.current.map(year => ({ label: year, value: year }))}
          onChange={v => setCurYear(v)}
        />
        <Select
          value={quarter}
          placeholder='请选择季度'
          style={{ width: 120 }}
          options={[
            {
              label: '第一季度',
              value: 1
            },
            {
              label: '第二季度',
              value: 2
            },
            {
              label: '第三季度',
              value: 3
            },
            {
              label: '第四季度',
              value: 4
            }
          ]}
          onChange={v => setQuarter(v)}
        />
        <Button onClick={handleExport}>导出表格</Button>
      </div>

      <Table
        rowKey='id'
        size='small'
        columns={[
          {
            title: '项目/类目/类别',
            dataIndex: 'name',
            rowScope: 'row'
          },
          {
            title: `${curYear}年${QUARTER_MAP[quarter]}库存数`,
            children: [
              {
                width: 70,
                title: '合计',
                dataIndex: 'pcsTotal'
              }
            ]
          },
          {
            title: `${curYear}年${QUARTER_MAP[quarter]}增加数`,
            children: [
              {
                title: '新收',
                children: [
                  {
                    title: '征购',
                    dataIndex: 'pcsZj'
                  },
                  {
                    title: '捐赠',
                    dataIndex: 'pcsJz'
                  },
                  {
                    title: '移交',
                    dataIndex: 'pcsYj'
                  },
                  {
                    title: '上交',
                    dataIndex: 'pcsSj'
                  },
                  {
                    title: '调拨',
                    dataIndex: 'pcsDb'
                  }
                ]
              },
              {
                title: '其他增加',
                dataIndex: 'pcsOther'
              }
              // {
              //   title: '调入',
              //   dataIndex: 'g'
              // }
            ]
          },
          // {
          //   title: `${curYear}年${QUARTER_MAP[quarter]}减少数`,
          //   children: [
          //     {
          //       title: '调出',
          //       dataIndex: 'a'
          //     },
          //     {
          //       title: '拨出',
          //       dataIndex: 'b'
          //     },
          //     {
          //       title: '其他减少',
          //       dataIndex: 'c'
          //     }
          //   ]
          // },
          // {
          //   title: `${curYear}年${QUARTER_MAP[quarter]}库存数`,
          //   children: [
          //     {
          //       title: '合计',
          //       dataIndex: 'a'
          //     }
          //   ]
          // },
          {
            title: '陈列',
            children: [
              {
                title: '提陈',
                dataIndex: 'cl1'
              },
              {
                title: '在陈',
                dataIndex: 'cl2'
              },
              {
                title: '退陈',
                dataIndex: 'cl3'
              },
              {
                title: '合计',
                dataIndex: 'clTotal'
              }
            ]
          },
          {
            title: '借出',
            children: [
              {
                title: '借出',
                dataIndex: 'jc1'
              },
              {
                title: '在借',
                dataIndex: 'jc2'
              },
              {
                title: '退还',
                dataIndex: 'jc3'
              },
              {
                title: '合计',
                dataIndex: 'jcTotal'
              }
            ]
          }
          // {
          //   title: '其他出库',
          //   children: [
          //     {
          //       title: '原出',
          //       dataIndex: 'a'
          //     },
          //     {
          //       title: '新出',
          //       dataIndex: 'b'
          //     },
          //     {
          //       title: '收回',
          //       dataIndex: 'c'
          //     },
          //     {
          //       title: '合计',
          //       dataIndex: 'c'
          //     }
          //   ]
          // },
          // {
          //   title: '备注',
          //   dataIndex: 'remark',
          //   align: 'center',
          //   onCell: (_, index) => {
          //     if (index === 0) return { rowSpan: 2 }
          //     if (index === 1) return { rowSpan: 0 }
          //     return {}
          //   }
          // }
        ]}
        bordered
        dataSource={list}
        pagination={false}
      />

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