import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import styles from './index.module.scss'
import { useDispatch, useSelector } from 'react-redux'
import store, { RootState } from '@/store'
import { Button, Cascader, DatePicker, Input, Select } from 'antd'
import history, { btnFlagFu } from '@/utils/history'
import MyPopconfirm from '@/components/MyPopconfirm'
import MyTable from '@/components/MyTable'
import { D3STAFF_PARAM_ROWS2, D3STAFF_TABLE_COLUMNS, DEFAULT_D3STAFF_PARAMS } from './constants'
import { D3StaffSearchType, ID3StaffItem, ID3StaffParams } from './types'
import { C21_APIdel } from '@/store/action/C21wealth'
import { MessageFu } from '@/utils/message'
import { sonTypeNameObj, statusObj } from '@/utils/tableData'
import { D3_APIList } from '@/store/action/D3staff'
import { filterEmptyStrings } from '@/utils/objects'
import { selectObj } from '@/utils/select'
import { D2_APIgetList } from '@/store/action/D2storSet'
import dayjs from 'dayjs'

const { RangePicker } = DatePicker

function D3staff() {
  // 从仓库拿数据
  const tableInfo = useSelector((state: RootState) => state.D3staff.tableInfo)
  const [formData, setFormData] = useState({ ...DEFAULT_D3STAFF_PARAMS })
  const formDataRef = useRef({ ...DEFAULT_D3STAFF_PARAMS })
  const formDataOldRef = useRef({ ...DEFAULT_D3STAFF_PARAMS })
  const dispatch = useDispatch()
  const { list: storageIdArr } = useSelector((state: RootState) => state.D2storSet.tableInfo)
  const D3StaffParamRows = useMemo<D3StaffSearchType[]>(
    () => [
      { name: '业务编号', key: 'num', type: '输入框' },
      // { name: '入库日期范围', key: 'inDate', type: '日期选择' },
      { name: '入库人员类型', key: 'sonTypeName', type: '下拉框', data: selectObj['入库人员类型'] },
      {
        name: '相关库房',
        key: 'storageInId',
        type: '下拉框',
        data: storageIdArr.map(i => ({
          label: i.name,
          value: i.id as number
        }))
      },
      { name: '发起部门', key: 'deptName', type: '输入框' }
    ],
    [storageIdArr]
  )

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

  // 顶部筛选
  const searchDom = useCallback(
    (arr: D3StaffSearchType[]) => {
      return arr.map(item => {
        return (
          <div key={item.name}>
            <span>{item.name}：</span>
            {item.type === '输入框' ? (
              <Input
                placeholder='请输入'
                maxLength={30}
                value={formData[item.key]}
                onChange={e => txtChangeFu(e.target.value, item.key)}
              />
            ) : item.type === '下拉框' ? (
              <Select
                options={item.data}
                placeholder='全部'
                allowClear={true}
                value={formData[item.key as 'num'] ? formData[item.key as 'num'] : null}
                onChange={e => setFormData({ ...formData, [item.key]: e })}
              />
            ) : item.type === '日期选择' ? (
              <RangePicker
                format='YYYY-MM-DD'
                allowClear={true}
                value={formData[item.key] as undefined}
                onChange={e => setFormData({ ...formData, [item.key]: e })}
              />
            ) : (
              <Cascader
                options={item.data}
                placeholder='全部'
                fieldNames={{ label: 'name', value: 'id', children: 'children' }}
                allowClear={true}
                value={
                  formData[item.key as 'num']
                    ? (formData[item.key as 'num'] as string).split(',')
                    : []
                }
                onChange={e => setFormData({ ...formData, [item.key]: e ? e.join(',') : '' })}
              />
            )}
          </div>
        )
      })
    },
    [formData, txtChangeFu]
  )

  // 点击搜索的 时间戳
  const [timeKey, setTimeKey] = useState(0)
  // 点击搜索
  const clickSearch = useCallback(() => {
    setFormData({ ...formData, pageNum: 1 })
    setTimeout(() => {
      setTimeKey(Date.now())
    }, 50)
  }, [formData])

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

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

  // 封装发送请求的函数
  const getListFu = useCallback(() => {
    const { date, ...rest } = formDataRef.current
    if (Array.isArray(date) && date.length) {
      // @ts-ignore
      rest.startTime = dayjs(date[0]).format('YYYY-MM-DD') + ' 00:00:00'
      // @ts-ignore
      rest.endTime = dayjs(date[1]).format('YYYY-MM-DD') + ' 23:59:59'
    }
    formDataOldRef.current = rest
    dispatch(D3_APIList(filterEmptyStrings(rest)))
  }, [dispatch])

  // 点击操作按钮
  const tableBtnFu = useCallback((id: any, key: string) => {
    history.push(`/staff_edit/${key}/${id}`)
  }, [])

  // 点击删除
  const delTableFu = useCallback(
    async (id: number) => {
      const res = await C21_APIdel(id)
      if (res.code === 0) {
        MessageFu.success('删除成功')
        getListFu()
      }
    },
    [getListFu]
  )

  const tableLastBtn = useMemo(() => {
    return [
      {
        title: '操作',
        render: (item: any) => {
          let obj = btnFlagFu(item)
          return !Object.values(obj).some(Boolean) ? (
            '-'
          ) : (
            <>
              {obj['编辑'] ? (
                <Button size='small' type='text' onClick={() => tableBtnFu(item.id, '2')}>
                  编辑
                </Button>
              ) : null}

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

              {obj['删除'] ? (
                <MyPopconfirm txtK='删除' onConfirm={() => delTableFu(item.id)} />
              ) : null}
            </>
          )
        }
      }
    ]
  }, [delTableFu, tableBtnFu])

  // 点击导出
  const deriveFu = useCallback(async () => {
    const res = await D3_APIList(
      {
        ...formDataOldRef.current,
        pageNum: 1,
        pageSize: 99999
      },
      true
    )

    if (res.code === 0) {
      if (res.data.records.length <= 0) return MessageFu.warning('当前搜索条件没有数据!')
      store.dispatch({
        type: 'layout/exInfo',
        payload: {
          name: '人员出入库',
          show: true,
          arr: [
            { key: 'num', txt: '业务编号' },
            { key: 'name', txt: '入库时间' },
            { key: 'sonTypeName', txt: '入库人员' },
            { key: 'reason', txt: '入库事由' },
            { key: 'storageName', txt: '相关库房' },
            { key: 'deptName', txt: '发起部门' },
            { key: 'creatorName', txt: '发起人' },
            { key: 'createTime', txt: '发起日期' },
            { key: 'status', txt: '申请状态' }
          ],
          data: res.data.records.map((v: ID3StaffItem) => ({
            ...v,
            status: statusObj[v.status as 1],
            sonTypeName: sonTypeNameObj[v.sonTypeName]
          }))
        }
      })
    }
  }, [])

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

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

  useEffect(() => {
    dispatch(D2_APIgetList({ pageNum: 1, pageSize: 99999 }))
  }, [dispatch])

  return (
    <div className={styles.D3staff}>
      <div className='pageTitle'>资源使用</div>

      {/* 第一行 */}
      <div className='C1top'>
        <div className='C1topll C1topllAll'>{searchDom(D3StaffParamRows)}</div>
      </div>

      {/* 第二行 */}
      <div className='C1top'>
        <div className='C1topll C1topllAll'>{searchDom(D3STAFF_PARAM_ROWS2)}</div>
      </div>

      {/* 第二行 */}
      <div className='C1top C1top2'>
        <Button type='primary' onClick={deriveFu}>
          批量导出
        </Button>
        &emsp;
        <Button type='primary' onClick={() => history.push('/staff_edit/1/null')}>
          新增
        </Button>
        &emsp;
        <Button type='primary' onClick={clickSearch}>
          查询
        </Button>
        &emsp;
        <Button onClick={resetSelectFu}>重置</Button>
      </div>

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

const MemoD3staff = React.memo(D3staff)

export default MemoD3staff
