import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import styles from './index.module.scss'
import { Button, Checkbox, Input, Modal, Select } from 'antd'
import { B1fromDataBase, B1listType } from '../B1ledger/data'
import { API_selectGoods } from '@/store/action/B1ledger'
import { dictSelect } from '@/utils/select'
import MyTable from '@/components/MyTable'
import { selectGoodsAddTableC } from '@/utils/tableData'
import { openLink } from '@/utils/history'
import MyPopconfirm from '@/components/MyPopconfirm'

type Props = {
  type: '入库' | '移库' | '出库'
  closeFu: () => void
  dataResFu: (data: B1listType[]) => void
  oldCheckArr: B1listType[]
}

function A0selectGoods({ type, closeFu, dataResFu, oldCheckArr }: Props) {
  const [tableList, setTableList] = useState<B1listType[]>([])
  const [tableListAll, setTableListAll] = useState<B1listType[]>([])

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

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

  const [formData, setFormData] = useState({ ...B1fromDataBase, pageSize: 999999 })

  // 输入框改变
  const timeRef = useRef(-1)
  const txtChangeFu = useCallback(
    (e: React.ChangeEvent<HTMLInputElement>, key: 'searchKey') => {
      clearTimeout(timeRef.current)
      timeRef.current = window.setTimeout(() => {
        setFormData({
          ...formData,
          [key]: e.target.value,
          pageNum: 1
        })
      }, 500)
    },
    [formData]
  )

  // 点击重置
  const [inputKey, setInputKey] = useState(1)
  const resetSelectFu = useCallback(() => {
    // 把2个输入框和时间选择器清空
    setInputKey(Date.now())
    setFormData(B1fromDataBase)
  }, [])

  const getListFu = useCallback(async () => {
    const res = await API_selectGoods(type, formData)
    if (res.code === 0) {
      setTableList(res.data.records)
      if (timeRef.current === -1) {
        timeRef.current = 1
        setTableListAll(res.data.records)
      }
    }
  }, [formData, type])

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

  // 过滤掉 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: B1listType) => {
      // 藏品编辑只能单选
      if (checkArr.map(v => v.id).includes(item.id))
        setCheckArr(checkArr.filter(v => v.id !== item.id))
      else setCheckArr([...checkArr, item])
    },
    [checkArr]
  )

  const startBtn = useMemo(() => {
    return [
      {
        title: '选择',
        width: 50,
        render: (item: B1listType) => (
          <Checkbox
            checked={checkArr.map(v => v.id).includes(item.id)}
            onChange={() => checkFu(item)}
          />
        )
      }
    ]
  }, [checkArr, checkFu])

  const tableLastBtn = useMemo(() => {
    return [
      {
        title: '查看',
        width: 80,
        render: (item: B1listType) => (
          <Button size='small' type='text' onClick={() => openLink(`/goodsLook/${item.id}`)}>
            查看
          </Button>
        )
      }
    ]
  }, [])

  // 点击提交
  const btnOk = useCallback(() => {
    dataResFu(checkArr)
    closeFu()
  }, [checkArr, closeFu, dataResFu])

  return (
    <Modal
      wrapClassName={styles.A0selectGoods}
      open={true}
      title={
        <div className='AStit'>
          <div>选择藏品</div> <div>已选中 {resNum} 条</div>
        </div>
      }
      footer={
        [] // 设置footer为空，去掉 取消 确定默认按钮
      }
    >
      {/* 顶部筛选 */}
      <div className='AStop'>
        <div>
          <Input
            placeholder='请填入藏品编号或标题'
            maxLength={30}
            showCount
            key={inputKey}
            allowClear
            onChange={e => txtChangeFu(e, 'searchKey')}
            style={{ width: 300 }}
          />
          &emsp;
          <Select
            allowClear
            style={{ width: 200 }}
            placeholder='类型'
            options={dictSelect('藏品类型')}
            value={formData.typeDictId}
            onChange={e => setFormData({ ...formData, typeDictId: e })}
          />
          &emsp;
          <Select
            allowClear
            style={{ width: 200 }}
            placeholder='材质'
            options={dictSelect('藏品材质')}
            value={formData.textureDictId}
            onChange={e => setFormData({ ...formData, textureDictId: e })}
          />
        </div>
        <Button onClick={resetSelectFu}>重置</Button>
      </div>

      {/* 表格 */}
      <MyTable
        yHeight={575}
        classKey='AStable'
        list={tableList}
        columnsTemp={selectGoodsAddTableC}
        staBtn={startBtn}
        lastBtn={tableLastBtn}
        pagingInfo={false}
      />

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

const MemoA0selectGoods = React.memo(A0selectGoods)

export default MemoA0selectGoods
