import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import styles from './index.module.scss'
import { Button, DatePicker, Input, Select } from 'antd'
import { FourTableType, TypeB3Form } from './type'
import dayjs from 'dayjs'
import MyTable from '@/components/MyTable'
import MyPopconfirm from '@/components/MyPopconfirm'
import { B3tableC, statusObj } from '@/utils/tableData'
import history, { btnFlagFu } from '@/utils/history'
import { useDispatch, useSelector } from 'react-redux'
import { FourAPI_del, FourAPI_getList, FourKeyType } from '@/store/action/FourAll'
import { selectObj } from '@/utils/select'
import { RootState } from '@/store'
import { MessageFu } from '@/utils/message'
import ExportJsonExcel from 'js-export-excel'
const { RangePicker } = DatePicker

export type D3InputKeyType = 'num' | 'name' | 'deptName' | 'userName'

const objUrl = {
  入馆: '/entering',
  入藏: '/enterTibet',
  登记: '/register',
  删除: '/delete'
}

const objKey = {
  入馆: '1',
  入藏: '2',
  登记: '3',
  删除: '4'
}

export const B3_4inputKeyArr: {
  name: string
  key: D3InputKeyType
}[] = [
  { name: '业务单号', key: 'num' },
  { name: '申请名称', key: 'name' },
  { name: '发起部门', key: 'deptName' },
  { name: '发起人', key: 'userName' }
]

export const B3baseFormData: TypeB3Form = {
  pageSize: 10,
  pageNum: 1,
  num: '',
  name: '',
  deptName: '',
  userName: '',
  startTime: '',
  endTime: '',
  status: null,
  userType: null
}

type Props = {
  pageSta: '入馆' | '入藏' | '登记' | '删除'
}

function B34page({ pageSta }: Props) {
  const dispatch = useDispatch()

  const pagekey = useMemo(() => {
    return Reflect.get(objKey, pageSta) as FourKeyType
  }, [pageSta])

  const [formData, setFormData] = useState(B3baseFormData)
  const formDataRef = useRef(B3baseFormData)
  const formDataOldRef = useRef(B3baseFormData)

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

  // 点击搜索的 时间戳
  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(() => {
    formDataOldRef.current = { ...formDataRef.current }
    dispatch(FourAPI_getList(formDataRef.current, pagekey))
  }, [dispatch, pagekey])

  // 从仓库中获取数据
  const tableObj = useSelector((state: RootState) => state.FourAll.listObj[pagekey])

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

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

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

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

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

  // 点击各种操作按钮
  const btnFu = useCallback(
    (id: number | string, key: string) => {
      const url = Reflect.get(objUrl, pageSta)

      history.push(`${url}_edit/${key}/${id}/${pagekey}`)
    },
    [pageSta, pagekey]
  )

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

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

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

  // 点击导出
  const deriveFu = useCallback(async () => {
    const name = '藏品' + pageSta + dayjs(new Date()).format('YYYY-MM-DD HH:mm')

    const res = await FourAPI_getList(
      {
        ...formDataOldRef.current,
        pageNum: 1,
        pageSize: 99999
      },
      pagekey,
      true
    )

    if (res.code === 0) {
      if (res.data.records.length <= 0) return MessageFu.warning('当前搜索条件没有数据!')

      const option = {
        fileName: name,
        datas: [
          {
            sheetData: res.data.records.map((v: FourTableType) => ({
              ...v,
              status: statusObj[v.status as 1]
            })),
            sheetName: name,
            sheetFilter: ['num', 'name', 'deptName', 'creatorName', 'createTime', 'status'],
            sheetHeader: ['业务单号', '申请名称', '发起部门', '发送人', '发起日期', '申请状态'],
            columnWidths: [10, 10, 10, 10, 10, 10]
          }
        ]
      }

      const toExcel = new ExportJsonExcel(option) //new
      toExcel.saveExcel() //保存
    }
  }, [pageSta, pagekey])

  return (
    <div className={styles.B34page}>
      <div className='pageTitle'>藏品{pageSta}</div>

      <div className='B3top'>
        <div className='B3topll'>
          {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='B3toprr'>
          <Button type='primary' onClick={deriveFu}>
            批量导出
          </Button>
          &emsp;
          <Button type='primary' onClick={() => btnFu('null', '1')}>
            新增
          </Button>
        </div>
      </div>
      <div className='B3top'>
        <div className='B3topll'>
          <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.status}
              onChange={e => setFormData({ ...formData, status: e })}
              options={selectObj['申请状态'].filter(v => v.label !== '待盘点')}
            />
          </div>

          <div>
            <span>选择角色：</span>
            <Select
              allowClear={true}
              style={{ width: 200 }}
              placeholder='全部'
              options={selectObj['角色']}
              // fieldNames={{ value: 'id', label: 'roleName' }}
              value={formData.userType}
              onChange={e => setFormData({ ...formData, userType: e })}
            />
          </div>
        </div>
        <div className='B3toprr'>
          <Button type='primary' onClick={clickSearch}>
            查询
          </Button>
          &emsp;<Button onClick={resetSelectFu}>重置</Button>
        </div>
      </div>

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

const MemoB34page = React.memo(B34page)

export default MemoB34page
