import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import styles from './index.module.scss'
import { Button, Cascader, Input, Select, Table } from 'antd'
import {
  A1addType,
  TableSelectType,
  cameraTypeOptions,
  statusSaleOptions,
  statusStockOptions,
  statusSupportOptions,
  typeInOptions
} from './data'
import { useDispatch, useSelector } from 'react-redux'
import { A1_APIgetlist, A1_APIgetlistDerive, A1_APIremove } from '@/store/action/A1Camera'
import { RootState } from '@/store'
import { A1ListType } from '@/types'
import ExportJsonExcel from 'js-export-excel'
import { MessageFu } from '@/utils/message'
import dayjs from 'dayjs'
import AddCamera from './AddCamera'
import { mapDataAll2 } from '../C1User/AddUser/city'
import UpXlsx from '@/components/UpXlsx'
import history from '@/utils/history'
import MyPopconfirm from '@/components/MyPopconfirm'

const tableSelectBase: TableSelectType = {
  siteArr: undefined,
  cameraType: '', //相机类型
  cameraSn: '', //SN码
  zlProvince: '',
  zlCity: '', //所在地区 省/市
  zlUser: '', //城市负责人
  zlPhone: '', //联系方式
  statusSale: '', //租售状态
  statusSupport: '', //售后状态
  statusStock: '', //库存状态
  typeIn: '', //相机来源
  pageSize: 10,
  pageNum: 1
}

function A1Camera() {
  const dispatch = useDispatch()

  // 筛选和分页
  const [tableSelect, setTableSelect] = useState(tableSelectBase)

  const tableSelectRef = useRef({} as TableSelectType)

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

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

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

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

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

    if (tableSelectRef.current.siteArr) {
      const temp = tableSelectRef.current.siteArr
      objTemp.zlProvince = temp[0] || ''
      objTemp.zlCity = temp[1] || ''
    }

    const obj = {
      ...tableSelectRef.current,
      ...objTemp
    }

    dispatch(A1_APIgetlist(obj))
  }, [dispatch])

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

  // 从仓库获取列表
  const A1TableList = useSelector((state: RootState) => state.A1Camera.A1TableList)
  // 页码变化
  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 A1_APIremove(id)
      if (res.code === 0) {
        MessageFu.success('删除成功!')
        getListFu()
      }
    },
    [getListFu]
  )

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

    if (A1TableList.list.length === 0) return MessageFu.warning('当前搜索条件没有数据!')
    const name = '相机列表' + dayjs(new Date()).format('YYYY-MM-DD HH:mm')

    const objTemp: any = {}

    if (tableSelectRef.current.siteArr) {
      const temp = tableSelectRef.current.siteArr
      objTemp.zlProvince = temp[0] || ''
      objTemp.zlCity = temp[1] || ''
    }

    const res = await A1_APIgetlistDerive({
      ...tableSelect,
      ...objTemp,
      pageNum: 1,
      pageSize: 99999
    })

    if (res.code === 0) {
      if (res.data.records.length <= 0) return MessageFu.warning('当前搜索条件没有数据!')

      const option = {
        fileName: name,
        datas: [
          {
            sheetData: res.data.records.map((item: A1ListType) => ({
              cameraType: item.cameraType ? (item.cameraType === 'KK' ? '看看' : '看见') : '空',
              cameraSn: item.cameraSn,
              myCity: !item.zlProvince && !item.zlCity ? '空' : `${item.zlProvince}-${item.zlCity}`,
              zlUser: item.zlUser || '空',
              zlPhone: item.zlPhone || '空',
              statusSale: item.statusSale || '空',
              statusSupport: item.statusSupport || '空',
              statusStock: item.statusStock || '空',
              typeIn: item.typeIn ? (item.typeIn === 'pc' ? '系统' : '移动端') : '空',
              creatorName: item.creatorName || '空',
              updateTime: item.updateTime || '空'
            })),
            sheetName: name,
            sheetFilter: [
              'cameraType',
              'cameraSn',
              'myCity',
              'zlUser',
              'zlPhone',
              'statusSale',
              'statusSupport',
              'statusStock',
              'typeIn',
              'creatorName',
              'updateTime'
            ],
            sheetHeader: [
              '相机类型',
              '相机SN码',
              '当前所在地区',
              '城市负责人',
              '联系方式',
              '租售状态',
              '售后状态',
              '库存状态',
              '相机来源',
              '编辑人',
              '更新日期'
            ],
            columnWidths: [10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10]
          }
        ]
      }

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

  const columns = useMemo(() => {
    return [
      {
        title: '相机类型',
        render: (item: A1ListType) =>
          item.cameraType ? (item.cameraType === 'KK' ? '看看' : '看见') : '（空）'
      },
      {
        title: '相机SN码',
        dataIndex: 'cameraSn'
      },
      {
        title: '当前所在地区',
        render: (item: A1ListType) =>
          !item.zlProvince && !item.zlCity ? '（空）' : `${item.zlProvince}-${item.zlCity}`
      },
      {
        title: '城市负责人',
        render: (item: A1ListType) => item.zlUser || '（空）'
      },
      {
        title: '联系方式',
        render: (item: A1ListType) => item.zlPhone || '（空）'
      },
      {
        title: '租售状态',
        render: (item: A1ListType) => item.statusSale || '（空）'
      },
      {
        title: '售后状态',
        render: (item: A1ListType) => item.statusSupport || '（空）'
      },
      {
        title: '库存状态',
        render: (item: A1ListType) => item.statusStock || '（空）'
      },
      {
        title: '相机来源',
        render: (item: A1ListType) =>
          item.typeIn ? (item.typeIn === 'pc' ? '系统' : '移动端') : '（空）'
      },
      {
        title: '编辑人',
        render: (item: A1ListType) => item.creatorName || '（空）'
      },
      {
        title: '更新日期',
        render: (item: A1ListType) => item.updateTime || '（空）'
      },

      {
        title: '操作',
        render: (item: A1ListType) => (
          <>
            <Button size='small' type='text' onClick={() => history.push(`/lookList/${item.id}`)}>
              查看
            </Button>
            <Button
              size='small'
              type='text'
              onClick={() => setOpenInfo({ id: item.id, txt: '编辑' })}
            >
              编辑
            </Button>
            <MyPopconfirm txtK='删除' onConfirm={() => delByIdFu(item.id)} />
          </>
        )
      }
    ]
  }, [delByIdFu])

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

  // 点击新增和编辑的数据
  const [openInfo, setOpenInfo] = useState<A1addType>({ id: 0, txt: '' })

  // 左上角的 title
  const leftTitle = useMemo(() => {
    const obj = {
      '': '相机列表',
      新增: '相机列表-新增',
      编辑: '相机列表-编辑'
    }
    return obj[openInfo.txt]
  }, [openInfo.txt])

  // 上传xlsx 的ref
  const upXlsxRef = useRef<any>(null)

  return (
    <div className={styles.A1Camera}>
      <div className='pageTitle'>{leftTitle}</div>
      {/* 顶部筛选 */}
      <div className='A1top'>
        <div className='A1topSon'>
          <div className='A1topRow'>
            <span>相机类型：</span>
            <Select
              style={{ width: 190 }}
              value={tableSelect.cameraType}
              onChange={e => setTableSelect({ ...tableSelect, cameraType: e })}
              options={cameraTypeOptions}
            />
          </div>

          <div className='A1topRow'>
            <span>SN码：</span>
            <Input
              key={inputKey}
              maxLength={20}
              style={{ width: 190 }}
              placeholder='请输入SN码，最多20字'
              allowClear
              onChange={e => txtChangeFu(e.target.value, 'cameraSn')}
            />
          </div>

          <div className='A1topRow'>
            <span>当前所在地区：</span>
            <Cascader
              changeOnSelect
              style={{ width: 240 }}
              options={mapDataAll2}
              value={tableSelect.siteArr}
              placeholder='全部'
              onChange={e =>
                setTableSelect({
                  ...tableSelect,
                  siteArr: e as string[]
                })
              }
            />
          </div>

          <div className='A1topRow'>
            <span>城市负责人：</span>
            <Input
              key={inputKey}
              maxLength={20}
              style={{ width: 190 }}
              placeholder='请输入内容，最多20字'
              allowClear
              onChange={e => txtChangeFu(e.target.value, 'zlUser')}
            />
          </div>
        </div>

        <div className='A1topSon'>
          <div className='A1topRow'>
            <span>联系方式：</span>
            <Input
              key={inputKey}
              maxLength={20}
              style={{ width: 190 }}
              placeholder='请输入内容，最多20字'
              allowClear
              onChange={e => txtChangeFu(e.target.value, 'zlPhone')}
            />
          </div>

          <div className='A1topRow'>
            <span>租售状态：</span>
            <Select
              style={{ width: 137 }}
              value={tableSelect.statusSale}
              onChange={e => setTableSelect({ ...tableSelect, statusSale: e })}
              options={statusSaleOptions}
            />
          </div>

          <div className='A1topRow'>
            <span>售后状态：</span>
            <Select
              style={{ width: 137 }}
              value={tableSelect.statusSupport}
              onChange={e => setTableSelect({ ...tableSelect, statusSupport: e })}
              options={statusSupportOptions}
            />
          </div>
          <div className='A1topRow'>
            <span>库存状态：</span>
            <Select
              style={{ width: 137 }}
              value={tableSelect.statusStock}
              onChange={e => setTableSelect({ ...tableSelect, statusStock: e })}
              options={statusStockOptions}
            />
          </div>
          <div className='A1topRow'>
            <span>相机来源：</span>
            <Select
              style={{ width: 137 }}
              value={tableSelect.typeIn}
              onChange={e => setTableSelect({ ...tableSelect, typeIn: e })}
              options={typeInOptions}
            />
          </div>
        </div>

        <div className='A1topSon A1topSon2'>
          <Button onClick={resetSelectFu}>重置</Button>
          <Button type='primary' onClick={clickSearch}>
            查询
          </Button>
          <Button type='primary' onClick={() => setOpenInfo({ id: -1, txt: '新增' })}>
            新增
          </Button>
          <a href='/xlsx/相机列表导入模板.xlsx' download>
            <Button type='primary'>下载导入模块</Button>
          </a>
          <UpXlsx
            url='cms/camera/upload/excel'
            ref={upXlsxRef}
            xlsxResInfoFu={() => getListFu()}
            dirCode='cameraXlsx'
            existSn={[]}
          />
          {/* 上传xlsx */}
          <Button type='primary' onClick={() => upXlsxRef.current?.myInputClickFu()}>
            导入表格
          </Button>
          <Button type='primary' onClick={deriveFu}>
            导出表格
          </Button>
        </div>
      </div>
      {/* 表格主体 */}
      <div className='tableMain'>
        <Table
          scroll={{ y: 510 }}
          dataSource={A1TableList.list}
          columns={columns}
          rowKey='id'
          pagination={{
            showQuickJumper: true,
            position: ['bottomCenter'],
            showSizeChanger: true,
            current: tableSelect.pageNum,
            pageSize: tableSelect.pageSize,
            total: A1TableList.total,
            onChange: paginationChange()
          }}
        />
      </div>

      {/* 新增 编辑  出来的页面 */}
      {openInfo.id ? (
        <AddCamera
          openInfo={openInfo}
          closeFu={() => setOpenInfo({ id: 0, txt: '' })}
          upTableFu={getListFu}
          addTableFu={resetSelectFu}
        />
      ) : null}

      {/*  右下角的列表数量 */}
      <div className='tableNumBox'>
        共 <span>{A1TableList.total}</span> 条数据
      </div>
    </div>
  )
}

const MemoA1Camera = React.memo(A1Camera)

export default MemoA1Camera
