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

function C3focus() {
  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(C3_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 focusNoFu = useCallback(
    async (id: number) => {
      const res = await C3_APIfocusNo(id)
      if (res.code === 0) {
        MessageFu.success('取消关注成功')
        getListFu()
      }
    },
    [getListFu]
  )

  const tableLastBtn = useMemo(() => {
    return [
      {
        title: '操作',
        render: (item: FourTableType) => {
          return (
            <>
              <Button size='small' type='text' onClick={() => openGoodsInfoFu(item.id)}>
                查看
              </Button>
              <MyPopconfirm
                txtK='取消关注'
                onConfirm={() => focusNoFu(item.id)}
                Dom={
                  <Button size='small' type='text'>
                    取消关注
                  </Button>
                }
              />
            </>
          )
        }
      }
    ]
  }, [focusNoFu])

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

  // 打开侧边栏
  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 = '藏品关注' + dayjs(new Date()).format('YYYY-MM-DD HH:mm')

    const res = await C3_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) || '（空）'
            })),
            sheetName: name,
            sheetFilter: [
              'num',
              'thumbPc',
              'numName',
              'name',
              'dictLevel',
              'dictType',
              'dictAge',
              'dictTexture3',
              'dictTorn',
              'source',

              'statusCollect',
              'statusStorage'
            ],
            sheetHeader: [
              '藏品编号',
              '封面图地址',
              '编号类型',
              '藏品名称',
              '文物级别',
              '文物类别',
              '年代',
              '质地',
              '完残程度',
              '来源',
              '入藏状态',
              '库存状态'
            ],
            columnWidths: [10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10]
          }
        ]
      }

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

  return (
    <div className={styles.C3focus}>
      <div className='pageTitle'>藏品关注</div>
      <div className='C3top'>
        <div className='C3topll'>{searchDom(C1InputKeyArr1)}</div>
        <div className='C3toprr'>
          <Button type='primary' onClick={deriveFu}>
            批量导出
          </Button>
          <div>
            <Button type='primary' onClick={clickSearch}>
              查询
            </Button>
            <Button onClick={resetSelectFu}>重置</Button>
          </div>
        </div>
      </div>
      {/* 表格 */}
      <MyTable
        yHeight={596}
        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)} />
    </div>
  )
}

const MemoC3focus = React.memo(C3focus)

export default MemoC3focus
