import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import styles from './index.module.scss'
import { Button, Cascader, Checkbox, Input, Modal, Select } from 'antd'
import MyPopconfirm from '@/components/MyPopconfirm'
import MyTable from '@/components/MyTable'
import { B3eTableC } from '@/utils/tableData'
import { cascaderObjFu, openGoodsInfoFu } from '@/utils/history'
import { MessageFu } from '@/utils/message'
import { C1GoodType } from '@/pages/A3_ledger/C1ledger/type'
import { API_goodsNowAdd } from '@/store/action/C1ledger'
import { selectObj } from '@/utils/select'
import { B3nowSearchType } from './type'
import { B3baseFormData, B3nowArr1, B3nowArr2 } from './data'

type Props = {
  closeFu: () => void
  nowSta: { key: string; id: string }
  // key:1=入馆 2=入藏 3-登记 4-删除 5-入库 6-出库 7-藏品编辑
  dataResFu: (data: C1GoodType[]) => void
  isOne?: boolean //从藏品编辑进来 只能选择一个藏品
  oldCheckArr: C1GoodType[]
  canObj?: any //其他页面带过来的参数
  // 藏品登记-只选择一个
  register?: boolean
}

function ZGaddNow({
  nowSta,
  closeFu,
  isOne = false,
  dataResFu,
  oldCheckArr,
  canObj,
  register
}: Props) {
  // 入藏状态特别过滤
  const RuChangSelect = useMemo(() => {
    let arr = selectObj['入藏状态']
    if (nowSta.key === '1') arr = arr.filter(v => v.label === '已鉴定')
    else if (['2', '3'].includes(nowSta.key)) arr = arr.filter(v => v.value !== 3)
    return arr
  }, [nowSta.key])

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

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

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

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

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

  const [tableList, setTableList] = useState<C1GoodType[]>([])
  const [tableListAll, setTableListAll] = useState<C1GoodType[]>([])

  // 封装发送请求的函数
  const getList = useCallback(async () => {
    let canObjTemp = canObj || {}
    const obj = {
      ...formDataRef.current,
      ...canObjTemp
    }
    const res = await API_goodsNowAdd(nowSta.id, obj)
    if (res.code === 0) {
      const arr: any = res.data.map((v: any) => ({
        ...v,
        statusCollect: (selectObj['入藏状态'].find(c => c.value === v.statusCollect) || {}).label,
        statusStorage: (selectObj['库存状态'].find(c => c.value === v.statusStorage) || {}).label
      }))

      setTableList(arr)

      if (timeKey === 0) setTableListAll(arr)
    }
  }, [canObj, nowSta.id, timeKey])

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

  // 多选
  const [checkArr, setCheckArr] = useState<C1GoodType[]>([])

  // 显示条数的
  // const [checkNum, setCheckNum] = useState<C1GoodType[]>([])

  // 旧数组
  useEffect(() => {
    setCheckArr(oldCheckArr)
  }, [oldCheckArr])

  // 过滤掉 tableList 里面没有的id
  const resNum = useMemo(() => {
    const tableIds = tableListAll.map(v => v.id)
    const arr = checkArr.filter(v => tableIds.includes(v.id))
    return arr.length
  }, [checkArr, tableListAll])

  const checkFu = useCallback(
    (item: C1GoodType) => {
      // 藏品编辑只能单选
      if (isOne) {
        if (checkArr && checkArr.length && item.id === checkArr[0].id) {
          setCheckArr([])
        } else setCheckArr([item])
      } else {
        if (checkArr.map(v => v.id).includes(item.id))
          setCheckArr(checkArr.filter(v => v.id !== item.id))
        else setCheckArr([...checkArr, item])
      }
    },
    [checkArr, isOne]
  )

  const startBtn = useMemo(() => {
    return [
      {
        title: isOne ? '单选' : '选择',
        width: 50,
        render: (item: C1GoodType) => (
          <Checkbox
            checked={checkArr.map(v => v.id).includes(item.id)}
            onChange={() => checkFu(item)}
          />
        )
      },
      {
        title: '藏品编号',
        render: (item: C1GoodType) => item.num || '（空）'
      }
    ]
  }, [checkArr, checkFu, isOne])

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

  // 点击提交
  const btnOk = useCallback(() => {
    dataResFu(checkArr)
    if (!isOne) MessageFu.success('提交成功')
    if (register) MessageFu.success(checkArr.length ? '信息带入成功' : '信息清空成功')
    closeFu()
  }, [checkArr, closeFu, dataResFu, isOne, register])

  // 顶部筛选
  const searchDom = useCallback(
    (arr: B3nowSearchType) => {
      return arr.map(item => {
        return (
          <div key={item.name}>
            <span>{item.name}：</span>
            {item.type === '输入框' ? (
              <Input
                value={formData[item.key as 'num']}
                onChange={e => setFormData({ ...formData, [item.key]: e.target.value })}
                style={{ width: 195 }}
                placeholder={item.name}
                maxLength={30}
              />
            ) : item.type === '下拉框' ? (
              <Select
                options={
                  item.name === '入藏状态'
                    ? RuChangSelect
                    : selectObj[(item.nameKey || item.name) as '入藏状态']
                }
                placeholder='全部'
                allowClear={true}
                value={formData[item.key] || null}
                onChange={e => setFormData({ ...formData, [item.key]: e })}
              />
            ) : (
              <Cascader
                options={cascaderObjFu()[item.nameKey || item.name]}
                placeholder='全部'
                fieldNames={{ label: 'name', value: 'id', children: 'children' }}
                allowClear={true}
                value={formData[item.key] ? (formData[item.key] as string).split(',') : []}
                onChange={e => setFormData({ ...formData, [item.key]: e ? e.join(',') : '' })}
              />
            )}
          </div>
        )
      })
    },
    [RuChangSelect, formData]
  )

  return (
    <Modal
      wrapClassName={styles.ZGaddNow}
      open={true}
      title={
        <div className='B3Gtit'>
          <div>选择藏品</div> {register ? <div></div> : <div>已选中 {resNum} 条</div>}
        </div>
      }
      footer={
        [] // 设置footer为空，去掉 取消 确定默认按钮
      }
    >
      <div className='B3GaMain'>
        <div className='B3GaTop'>
          <div className='B3Gatopll'>{searchDom(B3nowArr1)}</div>
          <div>
            <Checkbox
              checked={formData.isFocus === 1}
              onChange={e => setFormData({ ...formData, isFocus: e.target.checked ? 1 : null })}
            >
              我关注的
            </Checkbox>
          </div>
        </div>

        <div className='B3GaTop'>
          <div className='B3Gatopll'>{searchDom(B3nowArr2)}</div>
          <div>
            <Button type='primary' onClick={clickSearch}>
              查询
            </Button>
            &emsp;
            <Button onClick={resetSelectFu}>重置</Button>
          </div>
        </div>

        {/* 表格 */}
        <MyTable
          yHeight={575}
          classKey='ZGaddNow'
          list={tableList}
          columnsTemp={[
            ...B3eTableC,
            ['txt', '入藏状态', 'statusCollect'],
            ['txt', '库存状态', 'statusStorage']
          ]}
          startBtn={startBtn}
          lastBtn={tableLastBtn}
          pagingInfo={false}
        />

        <div className='B3GaMainBtn'>
          <Button type='primary' disabled={resNum === 0 && isOne && !register} onClick={btnOk}>
            提交
          </Button>
          &emsp;
          <MyPopconfirm txtK='取消' onConfirm={closeFu} />
        </div>
      </div>
    </Modal>
  )
}

const MemoZGaddNow = React.memo(ZGaddNow)

export default MemoZGaddNow
