import MyTable from '@/components/MyTable'
import { D7_APIGoodList } from '@/store/action/D7check'
import { MessageFu } from '@/utils/message'
import { InputNumber, Modal, Radio } from 'antd'
import { FC, useCallback, useEffect, useState } from 'react'
import { D7CEHCK_COLLECTION_RESULT_OBJ } from '../../constants'
import { D7CHECK_COLLECTION_RESULT_ENUM } from '../../types'
import { isNumber } from 'lodash'

export interface StocktakingModalProps {
  visible: boolean
  storageId: number | null
  setVisible: (v: boolean) => void
  onOk: (list: any[]) => void
}

export enum STOCKTAKING_TYPES {
  ALL = 1,
  NUM = 2,
  CHECK = 3
}

export const StocktakingModal: FC<StocktakingModalProps> = ({
  visible,
  storageId,
  setVisible,
  onOk
}) => {
  const [curIndex, setCurIndex] = useState(STOCKTAKING_TYPES.ALL)
  const [min, setMin] = useState<number | null>(null)
  const [max, setMax] = useState<number | null>(null)
  const [list, setList] = useState<any[]>([])
  const [loading, setLoading] = useState(false)
  const [confirmLoading, setConfirmLoading] = useState(false)
  const [checkedList, setCheckedList] = useState<any[]>([])

  const getList = useCallback(
    async (params?: any) => {
      if (!storageId) return

      try {
        Boolean(params) ? setConfirmLoading(true) : setLoading(true)
        const res = await D7_APIGoodList({
          storageId,
          type: curIndex,
          ...(params || {})
        })
        setList(res.data)
        return res.data
      } finally {
        Boolean(params) ? setConfirmLoading(false) : setLoading(false)
      }
    },
    [storageId, curIndex]
  )

  const handleCancel = () => {
    setVisible(false)
  }

  const handleSubmit = async () => {
    let stack: any[] = list

    switch (curIndex) {
      case STOCKTAKING_TYPES.NUM:
        if (!isNumber(min) || !isNumber(max)) {
          MessageFu.warning('请填写最小值和最大值')
          return
        }
        stack = await getList({
          min,
          max
        })
        break
      case STOCKTAKING_TYPES.CHECK:
        stack = checkedList
        break
    }
    // 过滤待盘点的藏品
    onOk(stack.filter(i => i.statusStorage !== D7CHECK_COLLECTION_RESULT_ENUM.PENDING))
    setVisible(false)
  }

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

  return (
    <Modal
      title='设置盘点范围'
      width={700}
      maskClosable={false}
      open={visible}
      okButtonProps={{
        disabled: loading
      }}
      confirmLoading={confirmLoading}
      onCancel={handleCancel}
      onOk={handleSubmit}
    >
      <Radio.Group
        value={curIndex}
        options={[
          { value: STOCKTAKING_TYPES.ALL, label: '该库房所有藏品' },
          { value: STOCKTAKING_TYPES.NUM, label: '按藏品分库号' },
          { value: STOCKTAKING_TYPES.CHECK, label: '按所选藏品' }
        ]}
        style={{ marginBottom: 15 }}
        onChange={e => setCurIndex(e.target.value)}
      />

      {curIndex === STOCKTAKING_TYPES.NUM && (
        <div style={{ display: 'flex', marginBottom: 15 }}>
          <InputNumber
            value={min}
            precision={0}
            placeholder='请填写最小值'
            min={0}
            style={{ flex: 1 }}
            onChange={setMin}
          />
          <span style={{ padding: '0 10px' }}>-</span>
          <InputNumber
            precision={0}
            value={max}
            min={min || 0}
            style={{ flex: 1 }}
            placeholder='请填写最大值'
            onChange={setMax}
          />
        </div>
      )}

      {curIndex === STOCKTAKING_TYPES.CHECK && (
        <MyTable
          rowSelection={{
            type: 'checkbox',
            getCheckboxProps: record => {
              return {
                name: record.name,
                disabled: record.statusStorage === D7CHECK_COLLECTION_RESULT_ENUM.PENDING
              }
            },
            onChange: (selectedRowKeys: React.Key[], selectedRows: any[]) => {
              setCheckedList(selectedRows)
            }
          }}
          columnsTemp={[
            ['txt', '库位号', 'siteNum'],
            ['txt', '编号类型', 'numName'],
            ['txt', '藏品编号', 'num'],
            ['txt', '藏品名称', 'name'],
            ['ping', '数量', 'pcs', 'pcsUnit'],
            ['txtChange', '库存状态', 'statusStorage', D7CEHCK_COLLECTION_RESULT_OBJ]
          ]}
          list={list}
        />
      )}
    </Modal>
  )
}
