import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import styles from './index.module.scss'
import { Button, DatePicker, Input, Select } from 'antd'
import { useDispatch, useSelector } from 'react-redux'
import { B2fromDataBase } from '../B2register/data'
import { B4_APIgetlist, B4_APIresubmit } from '@/store/action/B4delete'
import { RootState } from '@/store'
import { B1listType } from '../B1ledger/data'
import history, { aduitBtnRoleFu, resubmitBtnRoleFu } from '@/utils/history'
import { B2tableC } from '@/utils/tableData'
import MyTable from '@/components/MyTable'
import { B2devFu } from '@/utils/deriveFu'
import { statusSelect } from '@/utils/select'
import MyPopconfirm from '@/components/MyPopconfirm'
import { API_getGoodsInfo } from '@/store/action/B1ledger'
import { MessageFu } from '@/utils/message'

const { RangePicker } = DatePicker

function B4delete() {
  const dispatch = useDispatch()
  const [formData, setFormData] = useState({ ...B2fromDataBase, type: 'SC' })

  const getListFu = useCallback(() => {
    dispatch(B4_APIgetlist(formData))
  }, [dispatch, formData])

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

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

  // 时间选择器改变
  const timeChange = useCallback(
    (date: any, dateString: any) => {
      let startTime = ''
      let endTime = ''
      if (dateString[0] && dateString[1]) {
        startTime = dateString[0] + ' 00:00:00'
        endTime = dateString[1] + ' 23:59:59'
      }
      setFormData({ ...formData, startTime, endTime, pageNum: 1 })
    },
    [formData]
  )

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

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

  // 点击重新提交
  const resubmitFu = useCallback(
    async (item: B1listType) => {
      // 先拿详情
      const res1 = await API_getGoodsInfo(item.goodIds)
      if (res1.code === 0) {
        const obj = res1.data
        const res2 = await B4_APIresubmit(item.id, obj)
        if (res2.code === 0) {
          MessageFu.success('重新提交成功')
          getListFu()
        }
      }
    },
    [getListFu]
  )

  const tableLastBtn = useMemo(() => {
    return [
      {
        title: '操作',
        render: (item: B1listType) => {
          return (
            <>
              <Button
                size='small'
                type='text'
                onClick={() => history.push(`/delete_look/1/${item.id}`)}
              >
                查看
              </Button>

              {aduitBtnRoleFu(item) ? (
                <Button
                  size='small'
                  type='text'
                  onClick={() => history.push(`/delete_look/2/${item.id}`)}
                >
                  审批
                </Button>
              ) : null}

              {resubmitBtnRoleFu(item) ? (
                <MyPopconfirm
                  txtK='重新提交'
                  onConfirm={() => resubmitFu(item)}
                  Dom={
                    <Button size='small' type='text'>
                      重新提交
                    </Button>
                  }
                />
              ) : null}
            </>
          )
        }
      }
    ]
  }, [resubmitFu])

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

  return (
    <div className={styles.B4delete}>
      <div className='pageTitle'>藏品删除</div>

      <div className='B4top'>
        <div className='B4topll' key={inputKey}>
          <Input
            placeholder='申请编号'
            maxLength={30}
            showCount
            allowClear
            onChange={e => txtChangeFu(e, 'num')}
            style={{ width: 200 }}
          />
          &emsp;
          <Input
            placeholder='藏品编号'
            maxLength={30}
            showCount
            allowClear
            onChange={e => txtChangeFu(e, 'snapNum')}
            style={{ width: 200 }}
          />
          &emsp;
          <Input
            placeholder='藏品名称'
            maxLength={30}
            showCount
            allowClear
            onChange={e => txtChangeFu(e, 'snapName')}
            style={{ width: 200 }}
          />
          &emsp;
          <RangePicker
            placeholder={['发起日期起', '发起日期终']}
            style={{ width: 240 }}
            onChange={timeChange}
          />
          &emsp;
          <Select
            allowClear
            style={{ width: 200 }}
            placeholder='申请状态'
            options={statusSelect}
            value={formData.status}
            onChange={e => setFormData({ ...formData, status: e })}
          />
          &emsp;
        </div>
        <div className='B4toprr'>
          <Button onClick={resetSelectFu}>重置</Button>&emsp;
          <Button type='primary' onClick={() => B2devFu(formData, '藏品删除')}>
            数据导出
          </Button>
        </div>
      </div>

      {/* 表格 */}
      <MyTable
        yHeight={655}
        list={tableInfo.list}
        columnsTemp={B2tableC}
        lastBtn={tableLastBtn}
        pageNum={formData.pageNum}
        pageSize={formData.pageSize}
        total={tableInfo.total}
        onChange={(pageNum, pageSize) => paginationChange(pageNum, pageSize)}
      />
    </div>
  )
}

const MemoB4delete = React.memo(B4delete)

export default MemoB4delete
