import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import styles from './index.module.scss'
import { useDispatch, useSelector } from 'react-redux'
import {
  B2_APIdel,
  B2_APIgetList,
  B2_APIgetListAll,
  B2_APIgetNumAll,
  B2_APIupdate
} from '@/store/action/B2exhiLog'
import { RootState } from '@/store'
import { MessageFu } from '@/utils/message'
import { B2derArrType, B2FromDataType, B2SonListType, B2tableType } from './type'
import { Button, DatePicker, Input, Select, Switch } from 'antd'
import MyPopconfirm from '@/components/MyPopconfirm'
import MyTable from '@/components/MyTable'
import { B2tableC } from '@/utils/tableData'
import B2look from './B2look'
import { B2selectArr } from './data'
import LocStat from '../A6record/LocStat'
import ExportJsonExcel from 'js-export-excel'
import dayjs from 'dayjs'
import { domShowFu } from '@/utils/domShow'

const { RangePicker } = DatePicker

const fromDataBase: B2FromDataType = {
  searchKey: '',
  status: '',
  pageNum: 1,
  pageSize: 10,
  startTime: '',
  endTime: ''
}

function B2exhiLog() {
  const dispatch = useDispatch()

  const [fromData, setFromData] = useState(fromDataBase)

  // 总人数
  const [numAll, setNumAll] = useState(0)

  const getListFu = useCallback(async () => {
    dispatch(B2_APIgetList(fromData))
    const res = await B2_APIgetNumAll(fromData)
    if (res.code === 0) {
      setNumAll(res.data)
    }
  }, [dispatch, fromData])

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

  const [inputKey, setInputKey] = useState(1)

  // 输入框的输入
  const timeRef = useRef(-1)
  const txtChangeFu = useCallback(
    (e: React.ChangeEvent<HTMLInputElement>, key: 'searchKey') => {
      clearTimeout(timeRef.current)
      timeRef.current = window.setTimeout(() => {
        setFromData({
          ...fromData,
          [key]: e.target.value.replaceAll("'", ''),
          pageNum: 1
        })
      }, 500)
    },
    [fromData]
  )

  // 点击重置
  const resetSelectFu = useCallback(() => {
    setInputKey(Date.now())
    setFromData(fromDataBase)
  }, [])

  // 时间选择器改变
  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'
      }
      setFromData({ ...fromData, startTime, endTime, pageNum: 1 })
    },
    [fromData]
  )

  const { tableInfo } = useSelector((state: RootState) => state.B2exhiLog)

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

  // 核销
  const updateFu = useCallback(
    async (id: number, status: 0 | 1) => {
      const res = await B2_APIupdate(id, status)
      if (res.code === 0) {
        MessageFu.success('操作成功!')
        getListFu()
      }
    },
    [getListFu]
  )

  const tableLastBtn = useMemo(() => {
    return [
      {
        title: '核销状态',
        render: (item: B2tableType) => (
          <Switch
            checkedChildren='已核销'
            unCheckedChildren='未核销'
            value={item.status === 1}
            onChange={() => updateFu(item.id, item.status === 1 ? 0 : 1)}
          />
        )
      },
      {
        title: '操作',
        render: (item: B2tableType) => (
          <>
            <Button size='small' type='text' onClick={() => setLookId(item.id)}>
              查看
            </Button>

            <MyPopconfirm txtK='删除' onConfirm={() => delTableFu(item.id)} />
          </>
        )
      }
    ]
  }, [delTableFu, updateFu])

  // 点击查看
  const [lookId, setLookId] = useState(0)

  // 点击地区统计
  const [locShow, setLocShow] = useState(false)

  // 点击导出
  const deriveFu = useCallback(() => {
    B2_APIgetListAll(fromData, res => {
      if (res && res.length) {
        domShowFu('#AsyncSpinLoding', true)
        const derArr: B2derArrType[] = []
        // 优化导出逻辑
        res.forEach(v1 => {
          const sonArr: B2SonListType[] = JSON.parse(v1.rtf) || []
          sonArr.forEach(v2 => {
            derArr.push({
              createTime: v1.createTime,
              type: v1.type === 'person' ? '个人预约' : '团队预约',
              name: v2.name,
              phone: v2.phone,
              idType: v2.papers,
              identity: v2.identity,
              cityStr: v1.cityStr,
              bookDate: v1.bookDate,
              time: v1.time,
              status: v1.status ? '已核销' : '未核销'
            })
          })
        })

        // 开始导出流程
        const name = '展馆预约记录' + dayjs(new Date()).format('YYYY-MM-DD HH:mm')

        const option = {
          fileName: name,
          datas: [
            {
              sheetData: derArr,
              sheetName: name,
              sheetFilter: [
                'createTime',
                'type',
                'name',
                'phone',
                'idType',
                'identity',
                'cityStr',
                'bookDate',
                'time',
                'status'
              ],
              sheetHeader: [
                '申请时间',
                '预约类型',
                '姓名',
                '联系方式',
                '证件类型',
                '证件号码',
                '来自地区',
                '预约日期',
                '预约时段',
                '核销状态'
              ],
              columnWidths: [10, 10, 10, 10, 10, 10, 10, 10, 10]
            }
          ]
        }

        const toExcel = new ExportJsonExcel(option) //new
        toExcel.saveExcel() //保存
        setTimeout(() => {
          domShowFu('#AsyncSpinLoding', false)
        }, 500)
      } else MessageFu.warning('导出错误')
    })
  }, [fromData])

  return (
    <div className={styles.B2exhiLog}>
      <div className='pageTitle'>展馆预约记录</div>

      <div className='B2top'>
        <div className='B2top1'>
          <div className='B2topRow'>
            <span>搜索：</span>
            <Input
              key={inputKey}
              maxLength={50}
              style={{ width: 200 }}
              placeholder='请输入姓名/联系电话'
              allowClear
              onChange={e => txtChangeFu(e, 'searchKey')}
            />
          </div>
          <div className='B2topRow'>
            <span>核销状态：</span>
            <Select
              style={{ width: 200 }}
              value={fromData.status}
              onChange={e => setFromData({ ...fromData, pageNum: 1, status: e })}
              options={B2selectArr}
            />
          </div>
          <div className='B2topRow'>
            <span>预约日期：</span>
            <RangePicker key={inputKey} onChange={timeChange} />
          </div>
        </div>
        <div className='B2top1'>
          <Button onClick={deriveFu}>导出</Button>&emsp;
          <Button onClick={() => setLocShow(true)}>地区统计</Button>&emsp;
          <Button onClick={resetSelectFu}>重置</Button>
        </div>
      </div>

      <MyTable
        yHeight={626}
        list={tableInfo.list}
        columnsTemp={B2tableC}
        lastBtn={tableLastBtn}
        pageNum={fromData.pageNum}
        pageSize={fromData.pageSize}
        total={tableInfo.total}
        onChange={(pageNum, pageSize) => setFromData({ ...fromData, pageNum, pageSize })}
      />

      {/* 总人数 */}
      <div className='B2numAll'>总人数：{numAll}</div>

      {/* 点击查看 */}
      {lookId ? <B2look sId={lookId} closeFu={() => setLookId(0)} /> : null}

      {/* 点击地区统计 */}
      {locShow ? (
        <LocStat type='展馆' apiObj={fromData} closeFu={() => setLocShow(false)} />
      ) : null}
    </div>
  )
}

const MemoB2exhiLog = React.memo(B2exhiLog)

export default MemoB2exhiLog
