import React, { useCallback, useEffect, useMemo, useState } from 'react'
import styles from './index.module.scss'
import { Button, Input, Select, DatePicker } from 'antd'
import { useDispatch, useSelector } from 'react-redux'
import { B2EditInfoType } from './data'
import { B_APIgetList, B_APIdel, B_APIexportExcel } from '@/store/action/Breserve'
import { RootState } from '@/store'
import { B2tableType } from '@/types'
import MyPopconfirm from '@/components/MyPopconfirm'
import MyTable from '@/components/MyTable'
import { B2tableC } from '@/utils/tableData'
import B2look from './B2look'
import { MessageFu } from '@/utils/message'
import dayjs from 'dayjs'

// import { exportExcelFile } from '@/utils/xlsxExport'

const pageDataBase = {
  pageNum: 1,
  pageSize: 10
}

function B2reserve2() {
  const { RangePicker } = DatePicker
  const dispatch = useDispatch()
  const [name, setName] = useState('')
  const [pageData, setPageData] = useState(pageDataBase)
  const [queryData, setQueryData] = useState<{
    startTime?: string
    endTime?: string
    status?: number
  }>({})

  const getListFu = useCallback(
    (name?: string) => {
      dispatch(B_APIgetList({ ...pageData, name: name || '', type: 2, ...queryData }))
    },
    [dispatch, pageData, queryData]
  )

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

  // 点击重置
  const resetSelectFu = useCallback(() => {
    setPageData({ ...pageDataBase })
  }, [])

  const tableInfo = useSelector((state: RootState) => state.Breserve.tableInfo)

  const delTableFu = useCallback(
    async (id: number) => {
      const res = await B_APIdel(id)
      if (res.code === 0) {
        MessageFu.success('删除成功!')
        if (tableInfo.list.length === 1 && pageData.pageNum > 1) {
          setPageData({ ...pageData, pageNum: pageData.pageNum - 1 })
        }
        getListFu()
      }
    },
    [getListFu, pageData, tableInfo.list.length]
  )

  // 导出excel前端实现
  // const exportExcelFu = useCallback(() => {
  //   const listData = tableInfo.list.map(item => {
  //     const list = item.visitors.map(visitor => {
  //       return {
  //         申请时间: item.createTime,
  //         申请人姓名: item.userName,
  //         联系电话: item.phone,
  //         活动名称: item.activityTitle,
  //         预约日期: item.appointmentTime,
  //         身份证: item.idCard,
  //         参观者姓名: visitor.name,
  //         参观者身份证号: visitor.idCard,
  //         参观者联系电话: visitor.phone
  //       }
  //     })
  //     return list
  //   })
  //   console.log(listData.flat(), 'listData')
  //   exportExcelFile(listData.flat(), [150, 80, 100, 100, 100, 140, 80, 140, 130], '活动预约记录')
  // }, [tableInfo.list])

  // 导出excel后端实现
  const exportExcelFu2 = useCallback(async () => {
    const res: any = await B_APIexportExcel({ type: 2, name: name || '', ...queryData })
    const downloadUrl = window.URL.createObjectURL(res)
    const link = document.createElement('a')
    link.href = downloadUrl
    link.download = '活动预约表.xlsx'
    document.body.appendChild(link)
    link.click()
  }, [name, queryData])

  const tableLastBtn = useMemo(() => {
    return [
      {
        title: '操作',
        render: (item: B2tableType) => (
          <>
            <Button
              size='small'
              type='text'
              onClick={() => setEditInfo({ id: item.id, txt: '查看' })}
            >
              查看
            </Button>
            <MyPopconfirm txtK='删除' onConfirm={() => delTableFu(item.id)} />
          </>
        )
      }
    ]
  }, [delTableFu])

  //查看
  const [editInfo, setEditInfo] = useState<B2EditInfoType>({
    id: 0,
    txt: ''
  })

  return (
    <div className={styles.B2reserve2}>
      <div className='pageTitle'>活动预约记录</div>

      {/* 顶部筛选 */}
      <div className='B2top'>
        <div className='B1topLeft'>
          <Input
            style={{ width: 200 }}
            placeholder='请输入姓名'
            onChange={e => setName(e.target.value)}
            value={name}
          />
          <Button type='primary' onClick={() => getListFu(name)}>
            搜索
          </Button>
          <Button
            type='primary'
            onClick={() => {
              resetSelectFu()
              setName('')
              setQueryData({})
            }}
          >
            重置
          </Button>
          <div>
            预约日期：
            <RangePicker
              style={{ width: 400 }}
              format='YYYY-MM-DD'
              value={
                queryData.startTime || queryData.endTime
                  ? [
                      queryData.startTime ? dayjs(queryData.startTime) : null,
                      queryData.endTime ? dayjs(queryData.endTime) : null
                    ]
                  : [undefined, undefined]
              }
              onChange={date => {
                setQueryData({
                  ...queryData,
                  startTime: date ? date[0]?.format('YYYY-MM-DD') : '',
                  endTime: date ? date[1]?.format('YYYY-MM-DD') : ''
                })
              }}
            />
          </div>

          <div className='rowItem'>
            状态：
            <Select
              style={{ width: 120 }}
              defaultValue={0}
              options={[
                { label: '全部', value: 0 },
                { label: '已取消', value: -1 },
                { label: '已预约', value: 2 }
              ]}
              onChange={value => setQueryData({ ...queryData, status: value })}
            />
          </div>
        </div>
        <Button type='primary' onClick={exportExcelFu2}>
          导出
        </Button>
      </div>

      {/* 表格主体 */}
      <div className='B2tableBox'>
        <MyTable
          myKey='id'
          yHeight={625}
          list={tableInfo.list}
          columnsTemp={B2tableC}
          lastBtn={tableLastBtn}
          pageNum={pageData.pageNum}
          pageSize={pageData.pageSize}
          total={tableInfo.total}
          onChange={(pageNum, pageSize) => setPageData({ ...pageData, pageNum, pageSize })}
        />
      </div>

      {/* 查看 */}
      {editInfo.id ? (
        <B2look
          editInfo={editInfo}
          closeFu={() => setEditInfo({ id: 0, txt: '导出' })}
          addTableFu={resetSelectFu}
          editTableFu={getListFu}
        />
      ) : null}
    </div>
  )
}

const MemoB2reserve2 = React.memo(B2reserve2)

export default MemoB2reserve2
