import React, { useCallback, useEffect, useRef, useState } from 'react'
import styles from './index.module.scss'
import { Button, Cascader, Input, Select } from 'antd'
import dayjs from 'dayjs'
import { MessageFu } from '@/utils/message'
import { resJiLianFu } from '@/utils/history'
import { statusCollectObj, statusStorageObj } from '@/utils/tableData'
import ExportJsonExcel from 'js-export-excel'
import { useDispatch } from 'react-redux'
import { C1baseFormData, C1baseFormData2, C1InputKeyArr1, C1InputKeyArr2 } from '../C1ledger/data'
import { A32_APIgetList } from '@/store/action/A32Routing'
import { C1InputKeyType } from '../C1ledger/type'
import C8recycleBin from '../ComPage/C8recycleBin'
import C4import from '../ComPage/C4import'
import { A32treeData, A32treeDataType } from './data'
import { CaretDownOutlined } from '@ant-design/icons'
import classNames from 'classnames'
import { Z1_APIgetInfo } from '@/store/action/Z1dict'
import A32set from './A32set'
import store from '@/store'
import A32table from './A32table'
import { selectObj } from '@/utils/select'
import { FourTableType } from '@/pages/B_enterTibet/B1collect/type'

function A32Routing() {
  const dispatch = useDispatch()

  // -------------左侧树-----------------------
  const [value, setValue] = useState('')
  const [value2, setValue2] = useState('')

  const timeRef = useRef(-1)

  useEffect(() => {
    clearTimeout(timeRef.current)
    window.setTimeout(() => {
      setValue2(value)
    }, 500)
  }, [value])

  // 过滤的id
  const [filterId, setFilterId] = useState<string[]>([])

  const getFilterFu = useCallback(async () => {
    const res = await Z1_APIgetInfo('50000')
    if (res.code === 0) {
      const data = res.data
      if (data.rtf) {
        const val = JSON.parse(data.rtf)
        setFilterId([...val])
      }
    }
  }, [])

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

  const treeKey = useRef('')
  const [treeAc, setTreeAc] = useState<string | null>('')
  const treeAcRef = useRef('')
  useEffect(() => {
    if (treeAc) treeAcRef.current = treeAc
  }, [treeAc])

  const [treeArr, setTreeArr] = useState<A32treeDataType[]>([])

  useEffect(() => {
    let arr = A32treeData
    // 顶部过滤
    arr = arr.map(v => ({
      ...v,
      show: true,
      son: v.son.filter(c => c.name.includes(value2) && filterId.includes(c.id))
    }))

    const arrPu: { id: string; name: string; key: string }[] = []

    arr.forEach(v => {
      if (v.son && v.son.length) {
        v.son.forEach(c => {
          arrPu.push({ ...c, key: v.key })
        })
      }
    })

    if (flagRef.current) {
      if (arrPu && arrPu.length) {
        flagRef.current = false

        // 是不是原来选中了 后面取消了
        if (!filterId.includes(treeAcRef.current)) {
          setTreeAc(arrPu[0].id)
          treeKey.current = arrPu[0].key
        }
      } else {
        setTreeAc(null)
      }
    }

    setTreeArr(arr)
  }, [filterId, value2])

  const flagRef = useRef(true)

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

  // 点击展开的收起
  const showTreeArrFu = useCallback(
    (name: string) => {
      setTreeArr(
        treeArr.map(v => ({
          ...v,
          show: v.name === name ? !v.show : v.show
        }))
      )
    },
    [treeArr]
  )
  // -------------左侧树end-----------------------

  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 treeTimeRef = useRef(-1)

  const getListFu = useCallback(() => {
    clearTimeout(treeTimeRef.current)
    treeTimeRef.current = window.setTimeout(() => {
      if (treeAc) {
        formDataOldRef.current = { ...formDataRef.current }

        const obj = { ...formDataRef.current }
        obj[treeKey.current as 'name'] = treeAc

        dispatch(A32_APIgetList(obj))
      } else if (treeAc === null) {
        store.dispatch({ type: 'A32/getList', payload: { list: [], total: 0 } })
      }
    }, 100)
  }, [dispatch, treeAc])

  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 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 = '藏品分账' + dayjs(new Date()).format('YYYY-MM-DD HH:mm')

    const obj = {
      ...formDataOldRef.current,
      pageNum: 1,
      pageSize: 99999
    }
    obj[treeKey.current as 'name'] = treeAc!

    const res = await A32_APIgetList(obj, 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() //保存
    }
  }, [treeAc])

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

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

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

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

  // 点击分账设置
  const [setPage, setSetPage] = useState(false)

  return (
    <div className={styles.A32Routing}>
      <div className='pageTitle'>
        藏品分账{recycleBin ? '-回收站' : ''}
        {importPage ? (
          <>
            -数据导入<span className='C4tit'>最多支持单次导入1000条</span>
          </>
        ) : (
          ''
        )}
      </div>

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

      <div className='A32main'>
        <div className='A32left'>
          <Input
            placeholder='请输入分账名称'
            value={value}
            onChange={e => setValue(e.target.value.trim())}
            allowClear
          />
          <div>
            {treeArr.map(item1 => (
              <div className='A32llRow' key={item1.name}>
                <div className='A32llRow1' onClick={() => showTreeArrFu(item1.name)}>
                  <span
                    style={{
                      transform: `rotate(${item1.show ? 0 : -90}deg)`,
                      opacity: item1.son && item1.son.length ? '1' : '0'
                    }}
                  >
                    <CaretDownOutlined />
                  </span>
                  &nbsp;
                  {item1.name}
                </div>

                {/* 二级 */}
                <div className={classNames('A32llRow2', item1.show ? 'A32llRow2Show' : '')}>
                  {item1.son.map(item2 => (
                    <div className='A32llRow2Row' key={item2.id}>
                      <span
                        onClick={() => {
                          treeKey.current = item1.key
                          setTreeAc(item2.id)
                        }}
                        className={classNames(treeAc === item2.id ? 'A32llRow2RowAc' : '')}
                      >
                        {item2.name}
                      </span>
                    </div>
                  ))}
                </div>
              </div>
            ))}
          </div>
        </div>
        <div className='A32right'>
          <div className='A32rrTop'>
            {searchDom(C1InputKeyArr1.filter(v => v.name !== '文物类别'))}

            {advanced
              ? searchDom(C1InputKeyArr2.filter(v => !['入藏去向', '展览状态'].includes(v.name)))
              : null}
          </div>

          {/* 表格 */}
          <A32table
            advanced={advanced}
            pageNum={formData.pageNum}
            pageSize={formData.pageSize}
            pageChangeFu={(pageNum, pageSize) => paginationChange(pageNum, pageSize)}
          />
        </div>
      </div>

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

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

      {/* 设置分账 */}
      {setPage ? (
        <A32set
          filterId={filterId}
          succFu={() => {
            flagRef.current = true
            getFilterFu()
          }}
          closeFu={() => setSetPage(false)}
        />
      ) : null}
    </div>
  )
}

const MemoA32Routing = React.memo(A32Routing)

export default MemoA32Routing
