import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { B2FromDataArer } from './data'
import { useDispatch, useSelector } from 'react-redux'
import { B1_APIgetlistArea } from '@/store/action/B1Plan'
import { RootState } from '@/store'
import { B1tableAreaType } from '@/types'
import { Button, Table } from 'antd'
import { MessageFu } from '@/utils/message'
import dayjs from 'dayjs'
import ExportJsonExcel from 'js-export-excel'
import PlanModal from './PlanModal'
import history from '@/utils/history'
import B1LookCity from './B1LookCity'

const tableSelectTemp: B2FromDataArer = {
  // 按机房统计
  siteArr: undefined,
  province: '',
  city: ''
}

function B1tab1() {
  const dispatch = useDispatch()

  // 筛选和分页
  const [tableSelect, setTableSelect] = useState<B2FromDataArer>({
    ...tableSelectTemp
  })

  const tableSelectRef = useRef({} as B2FromDataArer)

  useEffect(() => {
    tableSelectRef.current = { ...tableSelect }
  }, [tableSelect])

  // 点击搜索的 时间戳
  const [timeKey, setTimeKey] = useState(-1)

  // 点击搜索
  const clickSearch = useCallback(() => {
    setTableSelect({ ...tableSelect })
    setTimeout(() => {
      setTimeKey(Date.now())
    }, 50)
  }, [tableSelect])

  // 发送接口的函数
  const getListFu = useCallback(() => {
    const objTemp: any = {}

    if (tableSelectRef.current.siteArr) {
      const temp = tableSelectRef.current.siteArr
      objTemp.province = temp[0] || ''
      objTemp.city = temp[1] || ''
      objTemp.region = temp[2] || ''
    }
    dispatch(B1_APIgetlistArea({ ...tableSelectRef.current, ...objTemp }))
  }, [dispatch])

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

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

  // 从仓库获取列表
  const B1TableList = useSelector((state: RootState) => state.B1Plan.B1TableListArea)

  // 跳到 机房管理 或者 场景审核
  const skipUrlFu = useCallback((val: string, url: '/psychz' | '/scene') => {
    if (val === '其他') history.push(encodeURI(`${url}?N=1`))
    else history.push(encodeURI(`${url}?C=${val}`))
  }, [])

  const columns = useMemo(() => {
    return [
      {
        title: '站址地区',
        render: (item: B1tableAreaType) => item.cityAll || '空'
      },
      {
        title: '机房总数',
        render: (item: B1tableAreaType) => (
          <span onClick={() => skipUrlFu(item.cityAll, '/psychz')} className='B1tableClick'>
            {item.pcsRoom || 0}
          </span>
        )
      },
      {
        title: '上传机房',
        render: (item: B1tableAreaType) => item.pcsSceneDistinct || 0
      },
      {
        title: '上传场景',
        render: (item: B1tableAreaType) => (
          <span onClick={() => skipUrlFu(item.cityAll, '/scene')} className='B1tableClick'>
            {item.pcsScene || 0}
          </span>
        )
      },
      {
        title: '完成场景计算',
        render: (item: B1tableAreaType) => item.pcsCalculate || 0
      },
      {
        title: '审核驳回',
        render: (item: B1tableAreaType) => item.pcsReject || 0
      },
      {
        title: '初审通过',
        render: (item: B1tableAreaType) => item.pcsFirst || 0
      },
      {
        title: '审核通过',
        render: (item: B1tableAreaType) => item.pcsPass || 0
      },

      {
        title: '场景推送成功',
        render: (item: B1tableAreaType) => item.pcsPushScene || 0
      },
      {
        title: '链接推送成功',
        render: (item: B1tableAreaType) => item.pcsPushLink || 0
      },
      {
        title: 'Json推送成功',
        render: (item: B1tableAreaType) => item.pcsPushJson || 0
      },
      {
        title: '操作',
        render: (item: B1tableAreaType) => (
          <>
            <Button size='small' type='text' onClick={() => setModalTitle(item.cityAll)}>
              按日期统计
            </Button>
            {['上海市', '北京市', '天津市', '重庆市', '其他'].includes(item.cityAll) ? null : (
              <Button size='small' type='text' onClick={() => setLookCity(item.cityAll)}>
                查看城市
              </Button>
            )}
          </>
        )
      }
    ]
  }, [skipUrlFu])

  // 点击导出
  const deriveFu = useCallback(async () => {
    if (B1TableList.total > 30000)
      return MessageFu.warning('只支持导出最多30000条数据。请增加筛选条件，并重新尝试')

    if (B1TableList.list.length === 0) return MessageFu.warning('当前搜索条件没有数据!')
    const name = '进度统计' + dayjs(new Date()).format('YYYY-MM-DD HH:mm')

    const option = {
      fileName: name,
      datas: [
        {
          sheetData: B1TableList.list.map((v: B1tableAreaType) => ({
            ...v,
            id: v.cityAll || '（空）'
          })),
          sheetName: name,
          sheetFilter: [
            'id',
            'pcsRoom',
            'pcsSceneDistinct',
            'pcsScene',
            'pcsCalculate',
            'pcsReject',
            'pcsFirst',
            'pcsPass',
            'pcsPushScene',
            'pcsPushLink',
            'pcsPushJson'
          ],
          sheetHeader: [
            '站址地区',
            '机房总数',
            '上传机房',
            '上传场景',
            '完成场景计算',
            '审核驳回',
            '初审通过',
            '审核通过',
            '场景推送成功',
            '链接推送成功',
            'Json推送成功'
          ],
          columnWidths: [10, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5]
        }
      ]
    }

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

  // 点击 按日期统计
  const [modalTitle, setModalTitle] = useState('')

  // 点击 查看城市
  const [lookCity, setLookCity] = useState('')

  return (
    <>
      <div className='pageTitle'>
        进度统计&emsp;
        {/* <ExclamationCircleOutlined rev={undefined} /> */}
        <div>数据更新时间：{B1TableList.time}</div>
      </div>
      {/* 顶部筛选 */}
      <div className='B1top'>
        <div>
          <div hidden>
            <Button onClick={resetSelectFu}>重置</Button>&emsp;
            <Button type='primary' onClick={clickSearch}>
              查询
            </Button>
            &emsp;
          </div>

          <Button type='primary' onClick={deriveFu}>
            导出表格
          </Button>
        </div>
      </div>
      {/* 表格主体 */}
      <div className='tableMain'>
        <Table
          scroll={{ y: 650 }}
          dataSource={B1TableList.list}
          columns={columns}
          rowKey='id'
          pagination={false}
        />
      </div>
      {/*  右下角的列表数量 */}
      <div className='tableNumBox'>
        共 <span>{B1TableList.total}</span> 条数据
      </div>

      {/* 点击 按日期查看 出来的页面 */}
      {modalTitle ? <PlanModal title={modalTitle} closePageFu={() => setModalTitle('')} /> : null}

      {/* 点击查看城市 */}
      {lookCity ? (
        <div className='cityListBox'>
          <B1LookCity closeSon={() => setLookCity('')} city1={lookCity} />
        </div>
      ) : null}
    </>
  )
}

const MemoB1tab1 = React.memo(B1tab1)

export default MemoB1tab1
