import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import styles from './index.module.scss'
import { Button, DatePicker, Input, Select } from 'antd'
import { A2_APIgetList } from '@/store/action/A2business'
import { RouterTypeRow } from '@/types'
import tabLeftArr from '@/pages/Layout/data'
import { selectObj } from '@/utils/select'
import { LogListType } from '@/pages/Y_goodsDetails/Y1cathet/Y44com'
import MyTable from '@/components/MyTable'
import { A2tableC } from '@/utils/tableData'
import { openGoodsInfoFu } from '@/utils/history'
import { MessageFu } from '@/utils/message'

const { RangePicker } = DatePicker

const btnArr = [
  { name: '我发起的', key: '1' },
  { name: '待我审批', key: '4' },
  { name: '抄送我的', key: '3' }
]

function A2table() {
  // 路由信息过滤过来
  const typePageArr = useMemo(() => {
    const arr: RouterTypeRow[] = []
    tabLeftArr.forEach(v1 => {
      v1.son.forEach(v2 => {
        if (v2.isLog) arr.push(v2)
      })
    })
    return arr
  }, [])

  const [formData, setFormData] = useState({
    pageNum: 1,
    pageSize: 10,
    name: '',
    num: '',
    startTime: '',
    endTime: '',
    status: '',
    userType: '1'
  })

  const getListFu = useCallback(async () => {
    const res = await A2_APIgetList(formData)
    if (res.code === 0) {
      setTableObj({ list: res.data.records || [], total: res.data.total })
    }
  }, [formData])

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

  // 时间选择器改变
  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 paginationChange = useCallback(
    (pageNum: number, pageSize: number) => {
      setFormData({ ...formData, pageNum, pageSize })
    },
    [formData]
  )

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

  const [tableObj, setTableObj] = useState<{ list: LogListType[]; total: number }>({
    list: [],
    total: 0
  })

  // 点击查看 新窗口打开
  const lookPage = useCallback(
    (name: string, id: number) => {
      const obj = typePageArr.find(v => v.name === name)
      if (obj) openGoodsInfoFu(id, 120, `#${obj.path}_edit/4/`)
      else MessageFu.warning('业务类型错误')
    },
    [typePageArr]
  )

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

  return (
    <div className={styles.A2table}>
      <div className='A2Ttop'>
        <div>
          {btnArr.map(v => (
            <Button
              onClick={() => setFormData({ ...formData, userType: v.key, pageNum: 1 })}
              key={v.key}
              type={formData.userType === v.key ? 'primary' : 'default'}
            >
              {v.name}
            </Button>
          ))}
        </div>
        <div className='A2TtopRR'>
          <div>
            <span>业务类型：</span>
            <Select
              allowClear={true}
              placeholder='全部'
              style={{ width: 120 }}
              value={formData.name ? formData.name : null}
              onChange={e => setFormData({ ...formData, name: e, pageNum: 1 })}
              options={typePageArr.map(v => ({ value: v.name, label: v.name }))}
            />
          </div>

          <div>
            <span>业务编号：</span>
            <Input
              style={{ width: 150 }}
              placeholder='请输入业务编号'
              maxLength={30}
              onChange={e => txtChangeFu(e, 'num')}
            />
          </div>

          <div>
            <span>发起日期范围：</span>
            <RangePicker style={{ width: 220 }} onChange={timeChange} />
          </div>

          <div>
            <span>申请状态：</span>
            <Select
              allowClear={true}
              placeholder='全部'
              style={{ width: 120 }}
              value={formData.status ? formData.status : null}
              onChange={e => setFormData({ ...formData, status: e, pageNum: 1 })}
              options={selectObj['申请状态'].filter(v => v.label !== '待盘点')}
            />
          </div>
        </div>
      </div>

      {/* 表格 */}
      <MyTable
        emptyText={true}
        list={tableObj.list}
        columnsTemp={A2tableC}
        lastBtn={tableLastBtn}
        pageNum={formData.pageNum}
        pageSize={formData.pageSize}
        total={tableObj.total}
        onChange={(pageNum, pageSize) => paginationChange(pageNum, pageSize)}
      />
    </div>
  )
}

const MemoA2table = React.memo(A2table)

export default MemoA2table
