import React, { useCallback, useEffect, useMemo, useState } from 'react'
import styles from './index.module.scss'
import { Button, Select } from 'antd'
import { API_GIlog } from '@/store/action/Cledger/C1ledger'
import history from '@/utils/history'
import MyTable from '@/components/MyTable'
import { GI5tableC } from '@/utils/tableData'
import tabLeftArr from '@/pages/Layout/data'
import { GI5tableType } from '../data'
import { MessageFu } from '@/utils/message'
import { authorityFu } from '@/utils/authority'

type Props = {
  goodId: number
}

function GItab5({ goodId }: Props) {
  const [type, setType] = useState(null)

  const [tableList, setTableList] = useState<GI5tableType[]>([])

  // 封装发送请求的函数
  const getListFu = useCallback(async () => {
    if (goodId) {
      const params = {
        pageNum: 1,
        pageSize: 99999,
        type,
        goodId
      }

      const res = await API_GIlog(params)
      if (res.code === 0) {
        setTableList(res.data.records || [])
      }
    }
  }, [goodId, type])

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

  const [list, setList] = useState<any[]>([])

  const tableLastBtn = useMemo(() => {
    return [
      {
        title: '操作',
        render: (item: GI5tableType) => (
          <>
            <Button
              size='small'
              type='text'
              onClick={() => {
                // console.log(item)
                const obj = list.find(v => v.value === item.type)
                if (obj) {
                  authorityFu(obj.id, obj.label, () =>
                    history.push(`${obj.path}_edit/4/${item.id}`)
                  )
                } else MessageFu.warning('申请类型错误')
              }}
            >
              查看
            </Button>
          </>
        )
      }
    ]
  }, [list])

  useEffect(() => {
    const arr: any[] = []
    tabLeftArr.forEach(v1 => {
      v1.son.forEach(v2 => {
        if (v2.pageType) arr.push({ path: v2.path, value: v2.pageType, label: v2.name, id: v2.id })
      })
    })

    setList(arr)
  }, [])

  const staBtn = useMemo(() => {
    return [
      {
        title: '申请类型',
        render: (item: GI5tableType) => {
          let txt = '（空）'
          const obj = list.find(v => v.value === item.type)
          if (obj) txt = obj.label
          return txt
        }
      }
    ]
  }, [list])

  return (
    <div className={styles.GItab5}>
      <div className='GI5top'>
        <Select
          allowClear
          placeholder='申请类型'
          style={{ width: 300 }}
          options={list}
          value={type || null}
          onChange={e => setType(e)}
        />
      </div>

      <MyTable
        classKey='GItab5'
        yHeight={560}
        list={tableList}
        columnsTemp={GI5tableC()}
        lastBtn={tableLastBtn}
        staBtn={staBtn}
        pagingInfo={false}
        widthSet={{ remark: 800 }}
      />
    </div>
  )
}

const MemoGItab5 = React.memo(GItab5)

export default MemoGItab5
