import MyTable from '@/components/MyTable'
import { Y44tableC } from '@/utils/tableData'
import { Button, DatePicker, Input, Select } from 'antd'
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { TypeY44form } from './type'
import dayjs from 'dayjs'
import { B3_4inputKeyArr, D3InputKeyType } from '@/pages/B_enterTibet/B1collect/data'
import { API_getInfoLogList } from '@/store/action/C1ledger'
import tabLeftArr from '@/pages/Layout/data'
import { RouterTypeRow } from '@/types'
import { MessageFu } from '@/utils/message'
import { openGoodsInfoFu } from '@/utils/history'
const { RangePicker } = DatePicker

const baseFormData: TypeY44form = {
  pageSize: 10,
  pageNum: 1,
  num: '',
  name: '',
  deptName: '',
  creatorName: '',
  startTime: '',
  endTime: '',
  status: '',
  typeName: ''
}

export type LogListType = {
  createTime: string
  creatorName: string
  deptName: string
  goodsIds: string
  name: string
  num: string
  orderId: number
  status: number
  typeName: string
}
type Props = {
  isLook?: boolean
  sId: number
}

function Y44com({ isLook, sId }: Props) {
  // 路由信息过滤过来
  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(baseFormData)
  const formDataRef = useRef(baseFormData)

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

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

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

  // 点击搜索
  const clickSearch = useCallback(() => {
    setFormData({ ...formData, pageNum: 1 })
    setTimeout(() => {
      setTimeKey(Date.now())
    }, 50)
  }, [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 })
    },
    [formData]
  )

  // 封装发送请求的函数
  const getListFu = useCallback(async () => {
    const obj = {
      ...formDataRef.current,
      goodsId: Number(sId)
    }
    const res = await API_getInfoLogList(obj)
    if (res.code === 0) {
      setTableObj({ list: res.data.records || [], total: res.data.total })
    }
  }, [sId])

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

  // 输入框的改变
  const txtChangeFu = useCallback(
    (txt: string, key: D3InputKeyType) => {
      setFormData({
        ...formData,
        [key]: txt
      })
    },
    [formData]
  )

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

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

  // 点击查看 新窗口打开
  const lookPage = useCallback(
    (name: string, id: number) => {
      const obj = typePageArr.find(v => v.name === name)
      if (obj) openGoodsInfoFu(id, 9901, `#${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.orderId)}>
              查看
            </Button>
          )
        }
      }
    ]
  }, [lookPage])

  return (
    <div className='Y44com'>
      {isLook ? (
        <>
          <div className='Y44top'>
            <div className='Y44topll'>
              {B3_4inputKeyArr.map(item => (
                <div key={item.name}>
                  <span>{item.name}：</span>
                  <Input
                    placeholder={`请输入${item.name}`}
                    maxLength={30}
                    value={formData[item.key]}
                    onChange={e => txtChangeFu(e.target.value, item.key)}
                  />
                </div>
              ))}
            </div>
            <div className='Y44toprr'></div>
          </div>
          <div className='Y44top'>
            <div className='Y44topll'>
              <div>
                <span>发起日期范围：</span>
                <RangePicker
                  value={
                    formData.startTime ? [dayjs(formData.startTime), dayjs(formData.endTime)] : null
                  }
                  onChange={timeChange}
                />
              </div>

              <div>
                <span>业务类型：</span>
                <Select
                  allowClear={true}
                  placeholder='全部'
                  style={{ width: 200 }}
                  value={formData.typeName ? formData.typeName : null}
                  onChange={e => setFormData({ ...formData, typeName: e })}
                  options={typePageArr
                    .filter(c => c.name !== '藏品征集')
                    .map(v => ({ value: v.name, label: v.name }))}
                />
              </div>

              {/* <div>
                <span>申请状态：</span>
                <Select
                  allowClear={true}
                  placeholder='全部'
                  style={{ width: 200 }}
                  value={formData.status ? formData.status : null}
                  onChange={e => setFormData({ ...formData, status: e })}
                  options={selectObj['申请状态'].filter(v => v.label !== '待盘点')}
                />
              </div> */}
            </div>
            <div className='Y44toprr'>
              <Button type='primary' onClick={clickSearch}>
                查询
              </Button>
              &emsp;<Button onClick={resetSelectFu}>重置</Button>
            </div>
          </div>
        </>
      ) : null}

      {/* 表格 */}
      <MyTable
        rowKey='orderId'
        classKey='Y44comTable'
        yHeight={isLook ? 530 : 666}
        list={tableObj.list}
        columnsTemp={Y44tableC}
        lastBtn={tableLastBtn}
        pageNum={formData.pageNum}
        pageSize={formData.pageSize}
        total={tableObj.total}
        onChange={(pageNum, pageSize) => paginationChange(pageNum, pageSize)}
      />
    </div>
  )
}

const MemoY44com = React.memo(Y44com)

export default MemoY44com
