import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import styles from './index.module.scss'
import { Button, Cascader, Input, Select } from 'antd'
import { C1InputKeyArr1, C1InputKeyArr2, C1baseFormData, C1baseFormData2 } from './data'
import { C1InputKeyType } from './type'
import { openGoodsInfoFu, resJiLianFu } from '@/utils/history'
import MyTable from '@/components/MyTable'
import { C1tableC, statusCollectObj, statusStorageObj } from '@/utils/tableData'
import classNames from 'classnames'
import Y1cathet from '@/pages/Y_goodsDetails/Y1cathet'
import { useDispatch, useSelector } from 'react-redux'
import { C1_APIgetList } from '@/store/action/C1ledger'
import { RootState } from '@/store'
import dayjs from 'dayjs'
import { MessageFu } from '@/utils/message'
import ExportJsonExcel from 'js-export-excel'
import C8recycleBin from '../ComPage/C8recycleBin'
import C4import from '../ComPage/C4import'
import { selectObj } from '@/utils/select'
import { FourTableType } from '@/pages/B_enterTibet/B1collect/type'

function C1ledger() {
  // 是否是藏品查询的藏品信息
  const [antiqueSearch, setAntiqueSearch] = useState(window.location.href.includes('antiqueSearch'))

  useEffect(() => {
    if (1 + 1 !== 2) console.log(setAntiqueSearch)
  }, [])

  const dispatch = useDispatch()

  const [formData, setFormData] = useState(C1baseFormData)
  const formDataRef = useRef(C1baseFormData)
  const formDataOldRef = useRef(C1baseFormData)

  useEffect(() => {
    formDataRef.current = formData
  }, [formData])

  // 点击搜索的 时间戳
  const [timeKey, setTimeKey] = useState(0)

  // 点击搜索
  const clickSearch = useCallback(() => {
    setFormData({ ...formData, pageNum: 1 })
    setTimeout(() => {
      setTimeKey(Date.now())
    }, 50)
  }, [formData])

  // 封装发送请求的函数
  const getListFu = useCallback(() => {
    formDataOldRef.current = { ...formDataRef.current }
    dispatch(C1_APIgetList(formDataRef.current))
  }, [dispatch])

  useEffect(() => {
    getListFu()
  }, [getListFu, timeKey])

  // 输入框的改变
  const txtChangeFu = useCallback(
    (txt: string, key: C1InputKeyType) => {
      setFormData({
        ...formData,
        [key]: txt
      })
    },
    [formData]
  )

  // 点击重置
  const resetSelectFu = useCallback(() => {
    setFormData(C1baseFormData)
    setTimeout(() => {
      setTimeKey(Date.now())
    }, 50)
  }, [])

  // 页码变化
  const paginationChange = useCallback(
    (pageNum: number, pageSize: number) => {
      setFormData({ ...formData, pageNum, pageSize })
      setTimeout(() => {
        setTimeKey(Date.now())
      }, 50)
    },
    [formData]
  )

  const tableLastBtn = useMemo(() => {
    return [
      {
        title: '展览状态',
        render: (item: FourTableType) =>
          (selectObj['展览状态'].find(v => v.value === item.accountIndoor) || {}).label || '（空）'
      },
      {
        title: '创建日期',
        render: (item: FourTableType) => item.createTime
      },

      {
        title: '操作',
        render: (item: FourTableType) => {
          return (
            <Button size='small' type='text' onClick={() => openGoodsInfoFu(item.id)}>
              查看
            </Button>
          )
        }
      }
    ]
  }, [])

  // 从仓库拿数据
  const tableInfo = useSelector((state: RootState) => state.C1ledger.tableInfo)

  // 高级搜索的切换
  const [advanced, setAdvanced] = useState(false)

  // 点击收起高级搜索
  const advancedFu = useCallback(
    (flag: boolean) => {
      setAdvanced(flag)
      if (!flag) {
        setFormData({ ...formData, ...C1baseFormData2 })
      }
    },
    [formData]
  )

  // 打开侧边栏
  const [cathet, setCathet] = useState(0)

  const startBtn = useMemo(() => {
    return [
      {
        title: '藏品编号',
        render: (item: FourTableType) => {
          return (
            <span
              onClick={() => setCathet(item.id)}
              className={classNames('D1GtNum', item.id === cathet ? 'D1GtNumAc' : '')}
            >
              {item.num}
            </span>
          )
        }
      }
    ]
  }, [cathet])

  // 顶部筛选
  const searchDom = useCallback(
    (arr: any[]) => {
      return arr.map(item => {
        return (
          <div key={item.name}>
            <span>{item.name}：</span>
            {item.type === '输入框' ? (
              <Input
                placeholder='请输入'
                maxLength={30}
                value={formData[item.key as 'num']}
                onChange={e => txtChangeFu(e.target.value, item.key)}
              />
            ) : item.type === '下拉框' ? (
              <Select
                options={item.data}
                placeholder='全部'
                allowClear={true}
                value={formData[item.key as 'num'] ? formData[item.key as 'num'] : null}
                onChange={e => setFormData({ ...formData, [item.key]: e })}
              />
            ) : (
              <Cascader
                options={item.data}
                placeholder='全部'
                fieldNames={{ label: 'name', value: 'id', children: 'children' }}
                allowClear={true}
                value={
                  formData[item.key as 'num']
                    ? (formData[item.key as 'num'] as string).split(',')
                    : []
                }
                onChange={e => setFormData({ ...formData, [item.key]: e ? e.join(',') : '' })}
              />
            )}
          </div>
        )
      })
    },
    [formData, txtChangeFu]
  )

  // 点击导出
  const deriveFu = useCallback(async () => {
    const name = antiqueSearch
      ? '藏品信息'
      : '藏品总账' + dayjs(new Date()).format('YYYY-MM-DD HH:mm')

    const res = await C1_APIgetList(
      {
        ...formDataOldRef.current,
        pageNum: 1,
        pageSize: 99999
      },
      true
    )

    if (res.code === 0) {
      if (res.data.records.length <= 0) return MessageFu.warning('当前搜索条件没有数据!')

      const option = {
        fileName: name,
        datas: [
          {
            sheetData: res.data.records.map((v: FourTableType) => ({
              ...v,
              thumbPc: v.thumbPc ? window.location.origin + v.thumbPc : '（空）',
              dictType: resJiLianFu(v.dictType),
              dictAge: v.dictAge === '其他' ? '其他' : resJiLianFu(v.dictAge),
              dictTexture3: resJiLianFu(v.dictTexture3),
              dictTorn: resJiLianFu(v.dictTorn),
              source: resJiLianFu(v.source),
              statusCollect: Reflect.get(statusCollectObj, v.statusCollect) || '（空）',
              statusStorage: Reflect.get(statusStorageObj, v.statusStorage) || '（空）',
              accountIndoor:
                (selectObj['展览状态'].find(c => c.value === v.accountIndoor) || {}).label ||
                '（空）'
            })),
            sheetName: name,
            sheetFilter: [
              'num',
              'thumbPc',
              'numName',
              'name',
              'dictLevel',
              'dictType',
              'dictAge',
              'dictTexture3',
              'dictTorn',
              'source',
              'statusCollect',
              'statusStorage',
              'accountIndoor',
              'createTime'
            ],
            sheetHeader: [
              '藏品编号',
              '封面图地址',
              '编号类型',
              '藏品名称',
              '文物级别',
              '文物类别',
              '年代',
              '质地',
              '完残程度',
              '来源',
              '入藏状态',
              '库存状态',
              '展览状态',
              '创建日期'
            ],
            columnWidths: [10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10]
          }
        ]
      }

      const toExcel = new ExportJsonExcel(option) //new
      toExcel.saveExcel() //保存
    }
  }, [antiqueSearch])

  // 点击回收站
  const [recycleBin, setRecycleBin] = useState(false)

  // 点击数据导入
  const [importPage, setImportPage] = useState(false)

  return (
    <div className={styles.C1ledger}>
      <div className='pageTitle'>
        {antiqueSearch ? '藏品信息' : '藏品总账'}
        {recycleBin ? '-回收站' : ''}
        {importPage ? (
          <>
            -数据导入<span className='C4tit'>最多支持单次导入1000条</span>
          </>
        ) : (
          ''
        )}
      </div>
      {/* 第一行 */}
      <div className='C1top'>
        <div className='C1topll C1topllAll'>{searchDom(C1InputKeyArr1)}</div>
      </div>

      {/* 第二行 */}
      <div className='C1top C1top2'>
        {advanced ? (
          <div className='C1topll'>{searchDom(C1InputKeyArr2)}</div>
        ) : (
          <div className='C1topll'></div>
        )}

        <div className={classNames(advanced ? 'C1toprrKai' : 'C1toprrSuo')}>
          {/* <Button type='primary' onClick={() => setRecycleBin(true)} hidden={antiqueSearch}>
            回收站
          </Button>
          &emsp; */}
          <Button type='primary' onClick={() => setImportPage(true)} hidden={antiqueSearch}>
            数据导入
          </Button>
          &emsp;
          <Button type='primary' onClick={deriveFu} hidden={antiqueSearch}>
            批量导出
          </Button>
          &emsp;
          <Button danger={advanced} onClick={() => advancedFu(!advanced)}>
            {advanced ? '收起' : ''}高级搜索
          </Button>
          &emsp;
          <Button type='primary' onClick={clickSearch}>
            查询
          </Button>
          &emsp;
          <Button onClick={resetSelectFu}>重置</Button>
        </div>
      </div>

      {/* 表格 */}
      <MyTable
        yHeight={advanced ? 540 : 595}
        list={tableInfo.list}
        columnsTemp={C1tableC}
        lastBtn={tableLastBtn}
        startBtn={startBtn}
        pageNum={formData.pageNum}
        pageSize={formData.pageSize}
        total={tableInfo.total}
        onChange={(pageNum, pageSize) => paginationChange(pageNum, pageSize)}
      />

      {/* 打开侧边栏 */}
      <Y1cathet sId={cathet} closeFu={() => setCathet(0)} />

      {/* 回收站 */}
      {recycleBin ? (
        <C8recycleBin
          closeFu={flag => {
            if (flag) getListFu()
            setRecycleBin(false)
          }}
        />
      ) : null}

      {/* 数据导入 */}
      {importPage ? (
        <C4import
          colseFu={flag => {
            if (flag) resetSelectFu()
            setImportPage(false)
          }}
        />
      ) : null}
    </div>
  )
}

const MemoC1ledger = React.memo(C1ledger)

export default MemoC1ledger
