import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import styles from './index.module.scss'
import { GoodsType } from '../SonGoodsList/data'
import { Button, Cascader, Checkbox, Input, Modal, Select } from 'antd'
import { openLink } from '@/utils/history'
import { MessageFu } from '@/utils/message'
import MyTable from '@/components/MyTable'
import MyPopconfirm from '@/components/MyPopconfirm'
import AddClues from '../AddClues'
import { FileUpInfoType } from '../data'

type Props = {
  API_getList: any
  baseFormData: any
  topSelectDom: any
  columnsTemp: any
  closeFu: () => void
  dataResFu: (data: GoodsType[]) => void
  oldCheckArr: GoodsType[]
  myType?: '线索' | '藏品'
  // 单选
  isOne?: boolean
  //其他额外的参数
  canObj?: any
}

function SelectGoods({
  API_getList,
  baseFormData,
  topSelectDom,
  columnsTemp,
  closeFu,
  dataResFu,
  oldCheckArr,
  isOne,
  canObj,
  myType = '线索'
}: Props) {
  const [formData, setFormData] = useState({ ...baseFormData })
  const formDataRef = useRef({ ...baseFormData })

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

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

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

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

  const [total, setTotal] = useState(0)
  const [tableList, setTableList] = useState<GoodsType[]>([])
  const [tableListAll, setTableListAll] = useState<GoodsType[]>([])

  // 封装发送请求的函数
  const getList = useCallback(async () => {
    let canObjTemp = canObj || {}
    const obj = {
      ...formDataRef.current,
      ...canObjTemp
    }

    // 第一次进来，获取到所有数据
    if (timeKey === 0) obj.pageSize = 99999

    const res = await API_getList(obj)
    // console.log(res)
    if (res.code === 0) {
      let resArr: any[] = res.data.records || []

      if (timeKey === 0) {
        resArr = resArr.filter((v, i) => i < baseFormData.pageSize)
        setTableListAll(res.data.records || [])
      }
      setTotal(res.data.total)
      setTableList(resArr)
    }
  }, [API_getList, baseFormData.pageSize, canObj, timeKey])

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

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

  // 旧数组
  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: GoodsType) => {
      // 单选
      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 staBtn = useMemo(() => {
    return [
      {
        title: isOne ? '单选' : '选择',
        width: 50,
        render: (item: GoodsType) => (
          <Checkbox
            checked={checkArr.map(v => v.id).includes(item.id)}
            onChange={() => checkFu(item)}
          ></Checkbox>
        )
      }
    ]
  }, [checkArr, checkFu, isOne])

  // 打开线索弹窗-查看详情
  const [clueInfo, setClueInfo] = useState({} as GoodsType)

  const tableLastBtn = useMemo(() => {
    return [
      {
        title: '操作',
        render: (item: GoodsType) => {
          return (
            <Button
              size='small'
              type='text'
              onClick={() => {
                if (myType === '线索') {
                  // 打开线索查看弹窗
                  setClueInfo(item)
                } else {
                  // 新页面打开藏品详情
                  openLink(`/goodsLook/${item.id}`)
                }
              }}
            >
              查看
            </Button>
          )
        }
      }
    ]
  }, [myType])

  // 点击提交
  const btnOk = useCallback(() => {
    dataResFu(checkArr)
    if (!isOne) MessageFu.success('提交成功')
    closeFu()
  }, [checkArr, closeFu, dataResFu, isOne])

  // 顶部筛选
  const searchDom = useCallback(
    (arr: any[]) => {
      return arr.map(item => {
        return (
          <div key={item.name}>
            {item.type === 'Input' ? (
              <Input
                value={formData[item.key]}
                onChange={e => setFormData({ ...formData, [item.key]: e.target.value })}
                placeholder={item.name}
                maxLength={30}
                showCount
                style={{ width: item.width || '' }}
              />
            ) : item.type === 'Select' ? (
              <Select
                options={item.options}
                placeholder={item.name}
                allowClear={true}
                value={formData[item.key] || null}
                onChange={e => setFormData({ ...formData, [item.key]: e })}
              />
            ) : item.type === 'Cascader' ? (
              <Cascader
                changeOnSelect
                options={item.options}
                placeholder={item.name}
                fieldNames={{ label: 'name', value: 'id', children: 'children' }}
                allowClear={!item.must}
                value={formData[item.key] ? formData[item.key].split(',') : []}
                onChange={e => setFormData({ ...formData, [item.key]: e ? e.join(',') : '' })}
              />
            ) : null}
          </div>
        )
      })
    },
    [formData]
  )

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

  return (
    <Modal
      wrapClassName={styles.SelectGoods}
      open={true}
      title={
        <div className='sgtit'>
          <div>选择{myType}</div> <div>已选中 {resNum} 条</div>
        </div>
      }
      footer={[]}
    >
      <div className='sgMain'>
        <div className='sgTop'>
          <div className='sgtopll'>{searchDom(topSelectDom)}</div>
          <div className='sgtoprr'>
            <Button type='primary' onClick={clickSearch}>
              查询
            </Button>
            &emsp;
            <Button onClick={resetSelectFu}>重置</Button>
          </div>
        </div>

        {/* 表格 */}
        <MyTable
          yHeight={565}
          classKey='SelectGoods'
          list={tableList}
          columnsTemp={columnsTemp}
          staBtn={staBtn}
          lastBtn={tableLastBtn}
          pageNum={formData.pageNum}
          pageSize={formData.pageSize}
          total={total}
          onChange={(pageNum, pageSize) => paginationChange(pageNum, pageSize)}
        />

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

      {/* 线索查看详情 */}
      {clueInfo.id ? (
        <AddClues
          info={clueInfo}
          closeFu={() => setClueInfo({} as GoodsType)}
          succFu={() => {}}
          moduleId={0}
          fileUpInfo={{} as FileUpInfoType}
          isLook={true}
        />
      ) : null}
    </Modal>
  )
}

const MemoSelectGoods = React.memo(SelectGoods)

export default MemoSelectGoods
