import React, { useMemo, useState } from 'react'
import styles from './index.module.scss'
import { authorityFu } from '@/utils/authority'
import { selectObj, getDictFu, resJiLianFu } from '@/utils/dataChange'
import history, { openLink } from '@/utils/history'
import TableList from '@/pages/Zother/TableList'
import { useSelector } from 'react-redux'
import { RootState } from '@/store'
import { API_getGoodsList, API_getGoodsListAll } from '@/store/action/Cledger/C1ledger'
import { baseFormData } from '@/pages/Zother/data'
import { goodsSonTableC } from '@/utils/tableData'
import { Button, Dropdown, Modal, Radio, Checkbox } from 'antd'
import { exportExcelFile } from '@/utils/xlsxExport'
import { CaretDownOutlined } from '@ant-design/icons'
import C1Import from './C1Import'

const C1topSearch = [
  {
    type: 'input',
    key: 'searchKey',
    placeholder: '搜索藏品登记号、藏品名称'
  },
  {
    type: 'cascaderSS',
    key: 'artDictId',
    placeholder: `文创标签`
    // options: getDictFu('藏品标签')
  },
  {
    type: 'select',
    key: 'level',
    placeholder: '级别',
    options: selectObj['藏品级别']
  },
  // 待完善sg
  // {
  //   type: 'cascaderSS',
  //   key: 'tagDictId',
  //   placeholder: '藏品标签',
  //   options: getDictFu('藏品标签')
  // },
  {
    type: 'cascader',
    key: 'ageDictId',
    placeholder: '年代',
    options: getDictFu('藏品年代')
  },
  {
    type: 'cascader',
    key: 'textureDictId',
    placeholder: '质地',
    options: getDictFu('质地')
  },
  {
    type: 'select',
    key: 'tornLevel',
    placeholder: '完残程度',
    options: selectObj['完残程度']
  },
  // TODO
  {
    type: 'select',
    key: 'status',
    placeholder: '入藏状态',
    options: selectObj['藏品入藏状态']
  },
  {
    type: 'select',
    key: 'siteStatus',
    placeholder: '库存状态',
    options: selectObj['藏品库存状态']
  },
  {
    type: 'select',
    key: 'siteLoc',
    placeholder: `搜索库房位置`
  }
]

const C1baseFormData = {
  ...baseFormData,
  typeDictId: '',
  ageDictId: '',
  textureDictId: ''
}

const columnsTempAdd = [
  ...goodsSonTableC(false),
  ['select', '入藏状态', 'status', selectObj['藏品入藏状态']],
  ['txt', '库存状态', 'siteStatus'],
  ['txt', '库房位置', 'siteLoc']
]

const ExportModal = ({
  open,
  availableYears,
  onConfirm,
  onCancel
}: {
  open: boolean
  availableYears: number[] | string[]
  onConfirm: (exportType: number, years: number[]) => void
  onCancel: () => void
}) => {
  const [exportValue, setExportValue] = useState<number>(1)
  const [selectedYears, setSelectedYears] = useState<number[]>([])

  const onExportTypeChange = (e: any) => {
    setExportValue(e.target.value)
  }

  return (
    <Modal
      title='数据导出'
      open={open}
      onOk={() => onConfirm(exportValue, selectedYears)}
      onCancel={onCancel}
      okText='导出'
      cancelText='取消'
    >
      <span style={{ marginBottom: 16 }}>导出范围：</span>

      <Radio.Group
        onChange={onExportTypeChange}
        value={exportValue}
        options={[
          { value: 1, label: '所有年份' },
          { value: 2, label: '按年份' }
        ]}
      />

      {exportValue === 2 && (
        <div style={{ marginTop: 24 }}>
          <Checkbox.Group
            style={{ flexDirection: 'column', gap: '5px' }}
            options={availableYears.map(year => ({
              label: `${year}年`,
              value: year
            }))}
            value={selectedYears}
            onChange={checkedValues => setSelectedYears(checkedValues as number[])}
          />
          <div style={{ opacity: '0.5', marginTop: '10px' }}>上述年份为藏品制档日期所在年份</div>
        </div>
      )}
    </Modal>
  )
}

function C1ledger() {
  const tableInfo = useSelector((state: RootState) => state.C1ledger.tableInfo)

  const rightBtnOptions = useMemo(() => {
    return {
      dangan: [
        {
          key: '1',
          label: '登记',
          onClick: () => authorityFu(410, '藏品登记', () => history.push(`/register_edit/1/null`))
        },
        {
          key: '2',
          label: '注销',
          onClick: () => authorityFu(430, '藏品注销', () => history.push(`/writeOff_edit/1/null`))
        }
      ],
      kufang: [
        {
          key: '1',
          label: '入库',
          onClick: () => authorityFu(1010, '藏品入库', () => history.push(`/inStorage_edit/1/null`))
        },
        {
          key: '2',
          label: '移库',
          onClick: () =>
            authorityFu(1020, '藏品移库', () => history.push(`/moveStorage_edit/1/null`))
        },
        {
          key: '3',
          label: '出库',
          onClick: () =>
            authorityFu(1030, '藏品出库', () => history.push(`/outStorage_edit/1/null`))
        }
      ],
      weihu: [
        {
          key: '1',
          label: '鉴定登记',
          onClick: () => authorityFu(230, '藏品鉴定', () => history.push(`/auth_edit/1/null`))
        },
        {
          key: '2',
          label: '事故登记',
          onClick: () => authorityFu(510, '事故登记', () => history.push(`/accident_edit/1/null`))
        },
        {
          key: '3',
          label: '现状登记',
          onClick: () => authorityFu(540, '现状登记', () => history.push(`/actuality_edit/1/null`))
        },
        {
          key: '4',
          label: '修复登记',
          onClick: () => authorityFu(550, '修复登记', () => history.push(`/repair_edit/1/null`))
        }
      ]
    }
  }, [])

  const [allData, setAllData] = useState([])
  const [isModalOpen, setIsModalOpen] = useState(false)
  const [availableYears, setAvailableYears] = useState<any>([])
  const [isImportOpen, setIsImportOpen] = useState(false)
  const showModal = async () => {
    setIsModalOpen(true)
    const res = await API_getGoodsListAll()
    setAllData(res.data.records)
    //获取年份信息
    const years = Array.from(
      new Set(
        res.data.records
          .map((item: any) => item.createTime?.slice(0, 4))
          .filter(Boolean) as string[]
      )
    ).sort((a, b) => Number(b) - Number(a))
    setAvailableYears(years)
  }

  const dataExport = async (exportType: number = 1, years: number[] = []) => {
    // 根据导出范围筛选数据：
    // exportType === 1：所有年份，不做筛选
    // exportType === 2：按年份，只保留所选年份的数据
    const filteredData =
      exportType === 2 && years.length
        ? allData.filter((item: any) => {
            if (!item.createTime) return false
            const yearStr = item.createTime.slice(0, 4)
            const yearNum = yearStr
            return years.includes(yearNum)
          })
        : allData

    const listData = filteredData.map((item: any) => {
      return {
        藏品登记号: item.num,
        封面: item.thumb,
        藏品标签: item.tagDictId,
        藏品名称: item.name,
        级别: item.level,
        类别: resJiLianFu(item.typeDictId),
        年代: resJiLianFu(item.ageDictId),
        质地: resJiLianFu(item.textureDictId),
        完残程度: item.tornLevel,
        数量: item.pcs,
        入藏状态: item.status,
        库存状态: item.siteStatus,
        库房位置: item.siteLoc
      }
    })
    console.log(years)
    exportExcelFile(
      listData,
      [100, 100, 100, 100, 100, 200, 200, 200, 100, 100, 100, 100, 100],
      '藏品总账数据'
    )
    setIsModalOpen(false)
  }

  const authorityIds = useSelector((state: RootState) => state.A0Layout.authorityIds)
  // 故事管理/藏品总账定制右侧内容
  const storyTableListToprr = ({
    clickSearch,
    resetSelectFu
  }: {
    clickSearch: () => void
    resetSelectFu: () => void
  }) => {
    return (
      <>
        {authorityIds.includes(311) ? (
          <Dropdown menu={{ items: rightBtnOptions['dangan'] }} trigger={['click']}>
            <Button type='primary'>
              档案管理
              <CaretDownOutlined />
            </Button>
          </Dropdown>
        ) : null}
        {authorityIds.includes(312) ? (
          <Dropdown menu={{ items: rightBtnOptions['kufang'] }} trigger={['click']}>
            <Button type='primary'>
              库房管理
              <CaretDownOutlined />
            </Button>
          </Dropdown>
        ) : null}
        {authorityIds.includes(313) ? (
          <Dropdown menu={{ items: rightBtnOptions['weihu'] }} trigger={['click']}>
            <Button type='primary'>
              藏品维护
              <CaretDownOutlined />
            </Button>
          </Dropdown>
        ) : null}
        <Button type='primary' onClick={() => setIsImportOpen(true)}>
          数据导入
        </Button>
        <Button type='primary' onClick={showModal}>
          数据导出
        </Button>
        <ExportModal
          open={isModalOpen}
          availableYears={availableYears}
          onConfirm={dataExport}
          onCancel={() => setIsModalOpen(false)}
        />
        <Button type='primary' onClick={clickSearch}>
          查询
        </Button>
        <Button onClick={resetSelectFu}>重置</Button>
      </>
    )
  }

  // 故事管理/藏品总账定制右侧操作按钮
  const storyTableLastBtn = useMemo(() => {
    return [
      {
        title: '操作',
        render: (item: any) => (
          <Button size='small' type='text' onClick={() => openLink(`/goodsLook/${item.id}`)}>
            查看
          </Button>
        )
      }
    ]
  }, [])

  return (
    <div className={styles.C1ledger}>
      <div className='pageTitle'>藏品总账</div>
      {!isImportOpen ? (
        <TableList
          baseFormData={C1baseFormData}
          getListAPI={API_getGoodsList}
          pageKey='ledger'
          tableInfo={tableInfo}
          columnsTemp={columnsTempAdd}
          rightBtnWidth={360}
          leftRowWidth={'20%'}
          yHeight={592}
          searchDom={C1topSearch}
          storyTableListToprr={storyTableListToprr}
          storyTableLastBtn={storyTableLastBtn}
        />
      ) : (
        <C1Import onClose={() => setIsImportOpen(false)} />
      )}
    </div>
  )
}

const MemoC1ledger = React.memo(C1ledger)

export default MemoC1ledger
