import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import styles from './index.module.scss'
import { Button, DatePicker, Input, Select } from 'antd'
import tabLeftArr, { RouterTypeRow } from '@/pages/Layout/data'
import MyTable from '@/components/MyTable'
import { MessageFu } from '@/utils/message'
import { A2_APIgetList } from '@/store/action/Abench/A2bench'
import { GI5tableType } from '@/pages/ZgoodsInfo/data'
import { authorityFu, tableListAuditBtnFu } from '@/utils/authority'
import history from '@/utils/history'
import { selectObj } from '@/utils/dataChange'
import { GI5tableC } from '@/utils/tableData'
import { useSelector } from 'react-redux'
import store, { RootState } from '@/store'

const { RangePicker } = DatePicker

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

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

  const [formData, setFormData] = useState({} as any)

  // 回调页面的时候 回显参数
  const A2formData = useSelector((state: RootState) => state.ZformData.A2formData)

  useEffect(() => {
    setFormData({ ...A2formData })
  }, [A2formData])

  const getListFu = useCallback(async () => {
    if (formData.pageNum) {
      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: GI5tableType[]; total: number }>({
    list: [],
    total: 0
  })

  const btnFu = useCallback(
    (pageKey: '3' | '4', obj: any, id: number) => {
      if (obj) {
        store.dispatch({ type: 'ZF/A2formData', payload: formData })
        authorityFu(obj.id, obj.name, () => history.push(`${obj.path}_edit/${pageKey}/${id}`))
      } else MessageFu.warning('业务类型错误')
    },
    [formData]
  )

  const tableLastBtn = useMemo(() => {
    return [
      {
        title: '操作',
        render: (item: any) => {
          const obj = typePageArr.find(v => v.pageType === item.type)
          return (
            <>
              <Button size='small' type='text' onClick={() => btnFu('4', obj, item.id)}>
                查看
              </Button>

              {tableListAuditBtnFu(item) ? (
                <Button size='small' type='text' onClick={() => btnFu('3', obj, item.id)}>
                  审批
                </Button>
              ) : null}
            </>
          )
        }
      }
    ]
  }, [btnFu, typePageArr])

  const staBtn = useMemo(() => {
    return [
      {
        title: '业务类型',
        render: (item: GI5tableType) => {
          let txt = '（空）'
          const obj = typePageArr.find(v => v.pageType === item.type)
          if (obj) txt = obj.name
          return txt
        }
      }
    ]
  }, [typePageArr])

  return (
    <div className={styles.A2table}>
      <div className='A2Ttop'>
        <div className='A2TtopLL'>
          <div>申请管理</div>
          {btnArr.map(v => (
            <Button
              onClick={() => setFormData({ ...formData, auditType: v.key, pageNum: 1 })}
              key={v.key}
              type={formData.auditType === v.key ? 'primary' : 'default'}
            >
              {v.name}
            </Button>
          ))}
        </div>
        <div className='A2TtopRR'>
          <div>
            <Select
              allowClear={true}
              placeholder='业务类型'
              style={{ width: 150 }}
              value={formData.type ? formData.type : null}
              onChange={e => setFormData({ ...formData, type: e, pageNum: 1 })}
              options={typePageArr.map(v => ({ value: v.pageType, label: v.name }))}
            />
          </div>

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

          <div>
            <RangePicker
              style={{ width: 260 }}
              onChange={timeChange}
              placeholder={['发起日期开始', '发起日期结束']}
            />
          </div>

          <div>
            <Select
              allowClear={true}
              placeholder='申请状态'
              style={{ width: 150 }}
              value={formData.status ? formData.status : null}
              onChange={e => setFormData({ ...formData, status: e, pageNum: 1 })}
              options={selectObj['订单审批状态']}
            />
          </div>
        </div>
      </div>

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

const MemoA2table = React.memo(A2table)

export default MemoA2table
