import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import styles from './index.module.scss'
import { Button, Cascader, Checkbox, Input, Popconfirm, Table, Tooltip } from 'antd'
import { useDispatch, useSelector } from 'react-redux'
import { B2_APIgetlistDel, B2_APIrecoversDel, B2_APIremoveDel } from '@/store/action/B2Scene'
import { RootState } from '@/store'
import { MessageFu } from '@/utils/message'
import { mapDataAll1 } from '@/pages/C1User/AddUser/city'
import { LeftOutlined, QuestionCircleOutlined } from '@ant-design/icons'
import { B2tableType } from '@/types'
import { B2ResNum } from '../data'
import LookReDo from '../LookReDo'

type TopObjType = {
  siteArr: undefined | string[]
  province: string
  city: string
  region: string
  searchKey: string
  roomName: string
  isSiteEmpty: 1 | 0
  pageSize: number
  pageNum: number
}

const topObj: TopObjType = {
  siteArr: undefined,
  province: '',
  city: '',
  region: '',
  searchKey: '',
  roomName: '',
  isSiteEmpty: 0,
  pageSize: 10,
  pageNum: 1
}

type Props = {
  sonDelCloseFu: () => void
  upTableFu: () => void
}

function B2DelList({ sonDelCloseFu, upTableFu }: Props) {
  const dispatch = useDispatch()

  // 筛选和分页
  const [tableSelect, setTableSelect] = useState<TopObjType>(topObj)

  const tableSelectRef = useRef({} as TopObjType)

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

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

  // 发送接口的函数
  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] || ''
    }

    const obj = {
      ...tableSelectRef.current,
      ...objTemp
    }
    dispatch(B2_APIgetlistDel(obj))
  }, [dispatch])

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

  // 输入框的改变
  const txtChangeFu = useCallback(
    (txt: string, key: 'roomName' | 'searchKey') => {
      setTableSelect({ ...tableSelect, [key]: txt })
    },
    [tableSelect]
  )

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

  // 点击重置
  const [inputKey, setInputKey] = useState(1)
  const resetSelectFu = useCallback(() => {
    // 把2个输入框和时间选择器清空
    setInputKey(Date.now())
    setTableSelect(topObj)
    setTimeout(() => {
      setTimeKey(Date.now())
    }, 50)
  }, [])

  // 从仓库获取列表
  const B2TableListDel = useSelector((state: RootState) => state.B2Scene.B2TableListDel)
  // 页码变化
  const paginationChange = useCallback(
    () => (pageNum: number, pageSize: number) => {
      setTableSelect({ ...tableSelect, pageNum, pageSize })
      setTimeout(() => {
        setTimeKey(Date.now())
      }, 50)
    },
    [tableSelect]
  )

  // 点击表格里面的删除
  const delByIdFu = useCallback(
    async (id: number) => {
      const res = await B2_APIremoveDel(id)
      if (res.code === 0) {
        MessageFu.success('删除成功!')
        getListFu()
      }
    },
    [getListFu]
  )

  // 看看是点击了 恢复 并且 恢复成功
  const isRecovers = useRef(false)

  //  点击返回
  const backFu = useCallback(() => {
    if (isRecovers.current) upTableFu()
    sonDelCloseFu()
  }, [sonDelCloseFu, upTableFu])

  // 点击表格里面的 恢复
  const recoversByIdFu = useCallback(
    async (id: number) => {
      const res = await B2_APIrecoversDel(id)
      if (res.code === 0) {
        MessageFu.success('恢复成功!')
        isRecovers.current = true
        getListFu()
      }
    },
    [getListFu]
  )

  const columns = useMemo(() => {
    return [
      {
        title: '机房编码',
        render: (item: B2tableType) => item.roomNum || '（空）'
      },
      {
        title: '站址地区',
        render: (item: B2tableType) =>
          !item.province && !item.city && !item.region
            ? '（空）'
            : `${item.province}-${item.city}-${item.region}`
      },
      {
        title: '站址名称',
        render: (item: B2tableType) => item.roomName || '（空）'
      },
      // {
      //   title: '场景名称',
      //   render: (item: B2tableType) => item.sceneName || '（空）'
      // },
      {
        title: '场景链接',
        render: (item: B2tableType) =>
          item.link ? (
            <a
              target='_blank'
              href={item.link}
              style={{ cursor: 'pointer' }}
              title={item.link}
              rel='noreferrer'
            >
              {item.link.length >= 25 ? item.link.substring(0, 25) + '...' : item.link}
            </a>
          ) : (
            '（空）'
          )
      },
      {
        title: '场景码',
        render: (item: B2tableType) => (
          <>
            {item.sceneCode || '（空）'}

            {/* up-只有计算失败的时候显示 ?  */}
            {item.scheduleStatus === 2 ? (
              <span
                style={{ cursor: 'pointer' }}
                hidden={!item.scheduleStatus && item.scheduleStatus !== 0}
              >
                <Tooltip title={Reflect.get(B2ResNum, item.scheduleStatus)}>
                  &nbsp;
                  <QuestionCircleOutlined rev={undefined} />
                </Tooltip>
              </span>
            ) : null}
          </>
        )
      },
      {
        title: '相机SN码',
        render: (item: B2tableType) => item.cameraSn || '（空）'
      },
      {
        title: '拍摄时间',
        render: (item: B2tableType) => item.shootTime || '（空）'
      },
      {
        title: '删除时间',
        render: (item: B2tableType) => item.shootTime || '（空）'
      },

      {
        title: '删除人',
        render: (item: B2tableType) => item.creatorName || '（空）'
      },
      {
        title: '操作',
        render: (item: B2tableType) => (
          <>
            <Popconfirm
              title='确定恢复吗?'
              okText='恢复'
              cancelText='取消'
              onConfirm={() => recoversByIdFu(item.id)}
              okButtonProps={{ loading: false }}
            >
              <Button size='small' type='text'>
                恢复
              </Button>
            </Popconfirm>

            <Popconfirm
              title='删除后无法恢复，是否删除?'
              okText='删除'
              cancelText='取消'
              onConfirm={() => delByIdFu(item.id)}
              okButtonProps={{ loading: false }}
            >
              <Button size='small' type='text' danger>
                彻底删除
              </Button>
            </Popconfirm>
          </>
        )
      }
    ]
  }, [delByIdFu, recoversByIdFu])

  // 查看重复的场景
  const [lookReDo, setLookReDo] = useState(false)

  return (
    <div className={styles.B2DelList}>
      {/* 顶部筛选 */}
      <div className='B2top'>
        {/* 左侧输入框 */}
        <div className='B2top1'>
          <div className='B2topRow'>
            <Button icon={<LeftOutlined rev={undefined} />} onClick={backFu}>
              返回
            </Button>
          </div>

          <div className='B2topRow'>
            <span>搜索项：</span>
            <Input
              key={inputKey}
              maxLength={24}
              style={{ width: 250 }}
              placeholder='请输入机房编码/场景码,最多24字'
              allowClear
              onChange={e => txtChangeFu(e.target.value, 'searchKey')}
            />
          </div>

          <div className='B2topRow'>
            <span>站址地区：</span>
            <Cascader
              disabled={!!tableSelect.isSiteEmpty}
              changeOnSelect
              value={tableSelect.siteArr}
              style={{ width: 250 }}
              options={mapDataAll1}
              placeholder='全部'
              onChange={e => setTableSelect({ ...tableSelect, siteArr: e as string[] })}
            />
          </div>
        </div>
        {/* 右侧按钮 */}
        <div className='B2top2'>
          <div>
            <div className='B2topRow'>
              <span>站址名称：</span>
              <Input
                key={inputKey}
                maxLength={10}
                style={{ width: 250 }}
                placeholder='请输入站址名称,最多10字'
                allowClear
                onChange={e => txtChangeFu(e.target.value, 'roomName')}
              />
            </div>

            <div className='B2topRow B2topRow2'>
              <Checkbox
                checked={!!tableSelect.isSiteEmpty}
                onChange={e =>
                  setTableSelect({
                    ...tableSelect,
                    siteArr: e.target.checked ? undefined : tableSelect.siteArr,
                    isSiteEmpty: e.target.checked ? 1 : 0
                  })
                }
              >
                仅查看站址地区为空的场景
              </Checkbox>
            </div>
          </div>
          <div>
            <Button onClick={() => setLookReDo(true)}>查看重复的场景</Button>
            &emsp;
            <Button onClick={resetSelectFu}>重置</Button>&emsp;
            <Button type='primary' onClick={clickSearch}>
              查询
            </Button>
          </div>
        </div>
      </div>

      {/* 表格主体 */}
      <div className='tableMain'>
        <Table
          size='small'
          scroll={{ y: 500 }}
          dataSource={B2TableListDel.list}
          columns={columns}
          rowKey='id'
          pagination={{
            showQuickJumper: true,
            position: ['bottomCenter'],
            showSizeChanger: true,
            current: tableSelect.pageNum,
            pageSize: tableSelect.pageSize,
            total: B2TableListDel.total,
            onChange: paginationChange()
          }}
        />
      </div>
      {/* 查看重复的场景 */}
      {lookReDo ? <LookReDo closePageFu={() => setLookReDo(false)} apiUrl='recycle' /> : null}
    </div>
  )
}

const MemoB2DelList = React.memo(B2DelList)

export default MemoB2DelList
