import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import styles from './index.module.scss'
import { Button, DatePicker, Input, Select } from 'antd'
import { E1FormType, E1InputKeyType } from './type'
import { useDispatch, useSelector } from 'react-redux'
import { E1_APIdel, E1_APIgetList } from '@/store/action/E1accident'
import { MessageFu } from '@/utils/message'
import history, { btnFlagFu } from '@/utils/history'
import { FourTableType } from '@/pages/B_enterTibet/B1collect/type'
import MyPopconfirm from '@/components/MyPopconfirm'
import { RootState } from '@/store'
import dayjs from 'dayjs'
import ExportJsonExcel from 'js-export-excel'
import { E1inputKeyArr } from './data'
import { selectObj } from '@/utils/select'
import MyTable from '@/components/MyTable'
import { E1tableC, statusObj } from '@/utils/tableData'
import classNames from 'classnames'
import Y1cathet from '@/pages/Y_goodsDetails/Y1cathet'
const { RangePicker } = DatePicker

const E1baseFormData: E1FormType = {
  pageSize: 10,
  pageNum: 1,
  num: '',
  dateStart: '',
  dateEnd: '',
  numName: '',
  goodsNum: '',
  goodsName: '',
  userName: '',
  userType: ''
}

function E1accident() {
  const dispatch = useDispatch()

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

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

  // 封装发送请求的函数
  const getListFu = useCallback(() => {
    formDataOldRef.current = { ...formDataRef.current }
    dispatch(E1_APIgetList(formDataRef.current))
  }, [dispatch])

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

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

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

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

  // 打开侧边栏
  const [cathet, setCathet] = useState(0)

  const startBtn = useMemo(() => {
    return [
      {
        title: '藏品编号',
        render: (item: FourTableType) => {
          return (
            <span
              onClick={() => setCathet(Number(item.goodsIds))}
              className={classNames('D1GtNum', item.id === cathet ? 'D1GtNumAc' : '')}
            >
              {item.goodsNum}
            </span>
          )
        }
      }
    ]
  }, [cathet])

  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.E1accident.tableInfo)

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

    const res = await E1_APIgetList(
      {
        ...formDataOldRef.current,
        pageNum: 1,
        pageSize: 99999
      },
      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: [
              'goodsNum',
              'numName',
              'num',
              'date',
              'sonTypeName',
              'goodsName',
              'authUser',
              'creatorName',
              'createTime',
              'status'
            ],
            sheetHeader: [
              '藏品编号',
              '编号类型',
              '申请编号',
              '事故时间',
              '事故责任',
              '藏品名称',
              '鉴定人',
              '发起人',
              '发送日期',
              '申请状态'
            ],
            columnWidths: [10, 10, 10, 10, 10, 10, 10, 10, 10, 10]
          }
        ]
      }

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

  return (
    <div className={styles.E1accident}>
      <div className='pageTitle'>事故登记</div>
      <div className='E1top'>
        <div className='E1topll'>
          {E1inputKeyArr.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='E1toprr'>
          <Button type='primary' onClick={deriveFu}>
            批量导出
          </Button>
          &emsp;
          <Button type='primary' onClick={() => history.push('/accident_edit/1/null')}>
            新增
          </Button>
        </div>
      </div>

      <div className='E1top'>
        <div className='E1topll'>
          <div>
            <span>事故日期范围：</span>
            <RangePicker
              value={
                formData.dateStart ? [dayjs(formData.dateStart), dayjs(formData.dateEnd)] : null
              }
              onChange={timeChange}
            />
          </div>

          <div>
            <span>编号类型：</span>
            <Select
              allowClear={true}
              placeholder='全部'
              style={{ width: 150 }}
              value={formData.numName ? formData.numName : null}
              onChange={e => setFormData({ ...formData, numName: e })}
              options={selectObj['藏品编号类型']}
            />
          </div>

          <div>
            <span>选择角色：</span>
            <Select
              allowClear={true}
              style={{ width: 150 }}
              placeholder='全部'
              options={selectObj['角色']}
              // fieldNames={{ value: 'id', label: 'roleName' }}
              value={formData.userType ? formData.userType : null}
              onChange={e => setFormData({ ...formData, userType: e })}
            />
          </div>
        </div>
        <div className='E1toprr'>
          <Button type='primary' onClick={clickSearch}>
            查询
          </Button>
          &emsp;<Button onClick={resetSelectFu}>重置</Button>
        </div>
      </div>
      {/* 表格 */}
      <MyTable
        yHeight={610}
        list={tableInfo.list}
        columnsTemp={E1tableC}
        startBtn={startBtn}
        lastBtn={tableLastBtn}
        pageNum={formData.pageNum}
        pageSize={formData.pageSize}
        total={tableInfo.total}
        onChange={(pageNum, pageSize) => paginationChange(pageNum, pageSize)}
      />
      {/* 打开侧边栏 */}
      <Y1cathet sId={cathet} closeFu={() => setCathet(0)} />
    </div>
  )
}

const MemoE1accident = React.memo(E1accident)

export default MemoE1accident
