import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import styles from './index.module.scss'
import { useDispatch, useSelector } from 'react-redux'
import { D6baseFormData, D6InputKeyType, D6typeArr } from './data'
import { D6_APIdel, D6_APIgetList } from '@/store/action/D6putsStor'
import { MessageFu } from '@/utils/message'
import history, { btnFlagFu } from '@/utils/history'
import { FourTableType } from '@/pages/B_enterTibet/B1collect/type'
import { Button, DatePicker, Input, Select } from 'antd'
import MyPopconfirm from '@/components/MyPopconfirm'
import store, { RootState } from '@/store'
import { D6tableC, statusObj } from '@/utils/tableData'
import dayjs from 'dayjs'
import { selectObj } from '@/utils/select'
import MyTable from '@/components/MyTable'
const { RangePicker } = DatePicker

function D6putsStor() {
  const dispatch = useDispatch()
  const [formData, setFormData] = useState(D6baseFormData)
  const formDataRef = useRef(D6baseFormData)
  const formDataOldRef = useRef(D6baseFormData)

  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 businessTimeStart = ''
      let businessTimeEnd = ''
      if (dateString[0] && dateString[1]) {
        businessTimeStart = dateString[0] + ' 00:00:00'
        businessTimeEnd = dateString[1] + ' 23:59:59'
      }
      setFormData({ ...formData, businessTimeStart, businessTimeEnd })
    },
    [formData]
  )

  const timeChange2 = 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(D6_APIgetList(formDataRef.current))
  }, [dispatch])

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

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

  // 点击重置
  const resetSelectFu = useCallback(() => {
    setFormData(D6baseFormData)
    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 D6_APIdel(id)
      if (res.code === 0) {
        MessageFu.success('删除成功')
        getListFu()
      }
    },
    [getListFu]
  )

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

  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={() => 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 tableInfo = useSelector((state: RootState) => state.D6putsStor.tableInfo)

  // 点击导出
  const deriveFu = useCallback(async () => {
    const res = await D6_APIgetList(
      {
        ...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: 'date', txt: '提用日期' },
            { key: 'sonTypeName', txt: '提退类型' },
            { key: 'num', txt: '提退单编号' },
            { key: 'sonUnit', txt: '提用/借入单位' },
            { key: 'sonNum', txt: '分库缩写' },
            { key: 'creatorName', txt: '发起人' },
            { key: 'createTime', txt: '发起日期' },
            { key: 'status', txt: '申请状态' }
          ],
          data: res.data.records.map((v: FourTableType) => ({
            ...v,
            sonTypeName: D6typeArr.find(c => c.value === v.sonTypeName)?.label,
            status: statusObj[v.status as 1]
          }))
        }
      })
    }
  }, [])

  return (
    <div className={styles.D6putsStor}>
      <div className='pageTitle'>藏品出库</div>
      <div className='D6top'>
        <div className='D6topll'>
          <div>
            <span>提用日期范围：</span>
            <RangePicker
              style={{ width: 220 }}
              value={
                formData.businessTimeStart
                  ? [dayjs(formData.businessTimeStart), dayjs(formData.businessTimeEnd)]
                  : null
              }
              onChange={timeChange}
            />
          </div>

          <div>
            <span>提退类型：</span>
            <Select
              allowClear={true}
              placeholder='全部'
              style={{ width: 150 }}
              value={formData.sonTypeName ? formData.sonTypeName : null}
              onChange={e => setFormData({ ...formData, sonTypeName: e })}
              options={D6typeArr}
            />
          </div>

          <div>
            <span>提退单编号：</span>
            <Input
              placeholder='请输入提退单编号'
              maxLength={30}
              value={formData.num}
              onChange={e => txtChangeFu(e.target.value, 'num')}
            />
          </div>

          <div>
            <span>提用/借入单位：</span>
            <Input
              style={{ width: 225 }}
              placeholder='请输入提用/借入单位'
              maxLength={30}
              value={formData.sonUnit}
              onChange={e => txtChangeFu(e.target.value, 'sonUnit')}
            />
          </div>
        </div>
        <div className='D6toprr'>
          <Button type='primary' onClick={deriveFu}>
            批量导出
          </Button>
          &emsp;
          <Button type='primary' onClick={() => history.push('/putsStor_edit/1/null')}>
            新增
          </Button>
        </div>
      </div>

      <div className='D6top'>
        <div className='D6topll'>
          <div>
            <span>发起日期范围：</span>
            <RangePicker
              style={{ width: 220 }}
              value={
                formData.startTime ? [dayjs(formData.startTime), dayjs(formData.endTime)] : null
              }
              onChange={timeChange2}
            />
          </div>

          <div>
            <span>分库缩写：</span>
            <Input
              style={{ width: 125 }}
              placeholder='请输入分库缩写'
              maxLength={30}
              value={formData.sonNum}
              onChange={e => txtChangeFu(e.target.value, 'sonNum')}
            />
          </div>

          <div>
            <span>发起人：</span>
            <Input
              style={{ width: 120 }}
              placeholder='请输入发起人'
              maxLength={30}
              value={formData.userName}
              onChange={e => txtChangeFu(e.target.value, 'userName')}
            />
          </div>

          <div>
            <span>申请状态：</span>
            <Select
              allowClear={true}
              placeholder='全部'
              style={{ width: 128 }}
              value={formData.status ? formData.status : null}
              onChange={e => setFormData({ ...formData, status: e })}
              options={selectObj['申请状态'].filter(v => v.label !== '待盘点')}
            />
          </div>

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

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

const MemoD6putsStor = React.memo(D6putsStor)

export default MemoD6putsStor
