import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import styles from './index.module.scss'
import { useDispatch, useSelector } from 'react-redux'
import {
  A2AFromDataType,
  A2AtopTypeArr,
  A2AtopTypeEditLabel,
  A2AtopTypeObj,
  TopTypeType
} from './data'
import { A2A_APIgetlist, A2A_APIgetlistDerive, A2A_APIremove } from '@/store/action/A2Abusiness'
import { RootState } from '@/store'
import { MessageFu } from '@/utils/message'
import ExportJsonExcel from 'js-export-excel'
import dayjs from 'dayjs'
import { A2AListType } from '@/types'
import { A1addType } from '../A1Camera/data'
import { Button, Cascader, DatePicker, Input, Table } from 'antd'
import { mapDataAll2 } from '../C1User/AddUser/city'
import AddBusiness from './AddBusiness'
import history from '@/utils/history'
import MyPopconfirm from '@/components/MyPopconfirm'

const { RangePicker } = DatePicker

const tableSelectBase: A2AFromDataType = {
  num: '',
  dingNum: '',
  dateStart: '',
  dateEnd: '',
  zlName: '',

  siteArr: undefined,
  zlProvince: '',
  zlCity: '', //所在地区 省/市

  zlUser: '', //城市负责人
  zlPhone: '', //联系方式
  pageSize: 10,
  pageNum: 1
}

function A2Abusiness() {
  const dispatch = useDispatch()

  // 顶部的type 按钮
  const [topType, setTopType] = useState<TopTypeType>('ZL')

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

  const tableSelectRef = useRef({} as A2AFromDataType)

  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.zlProvince = temp[0] || ''
      objTemp.zlCity = temp[1] || ''
    }

    const obj = {
      ...tableSelectRef.current,
      ...objTemp,
      type: topType
    }
    dispatch(A2A_APIgetlist(obj))
  }, [dispatch, topType])

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

  // 输入框的改变
  const txtChangeFu = useCallback(
    (txt: string, key: 'num' | 'dingNum' | 'zlName' | 'zlUser' | 'zlPhone') => {
      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(tableSelectBase)
    setTimeout(() => {
      setTimeKey(Date.now())
    }, 50)
  }, [])

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

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

    if (A2ATableList.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 A2A_APIgetlistDerive({
      ...tableSelect,
      ...objTemp,
      pageNum: 1,
      pageSize: 99999,
      type: topType
    })

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

      const option = {
        fileName: name,
        datas: [
          {
            sheetData: res.data.records.map((item: A2AListType) => ({
              num: item.num || '空',
              dingNum: item.dingNum || '空',
              dateStart: item.dateStart || '空',
              dateEnd: item.dateEnd || '空',
              zlName: item.zlName || '空',
              myCity: !item.zlProvince && !item.zlCity ? '空' : `${item.zlProvince}-${item.zlCity}`,
              zlUser: item.zlUser || '空',
              zlPhone: item.zlPhone || '空',
              pcs: item.pcs || '空',
              creatorName: item.creatorName || '空',
              updateTime: item.updateTime || '空'
            })),
            sheetName: name,
            sheetFilter: [
              'num',
              'dingNum',
              'dateStart',
              'dateEnd',
              'zlName',
              'myCity',
              'zlUser',
              'zlPhone',
              'pcs',
              'creatorName',
              'updateTime'
            ],
            sheetHeader: [
              '订单编号',
              '钉钉审批号',
              '租赁日期',
              '预计归还日期',
              '租赁方名称',
              '地区',
              '负责人',
              '联系方式',
              '设备台数',
              '编辑人',
              '更新日期'
            ],
            columnWidths: [10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10]
          }
        ]
      }

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

  const columns = useMemo(() => {
    return [
      {
        title: '订单编号',
        render: (item: A2AListType) => item.num || '（空）'
      },
      {
        title: '钉钉审批号',
        render: (item: A2AListType) => item.dingNum || '（空）'
      },
      {
        title: '租赁日期',
        render: (item: A2AListType) => item.dateStart || '（空）'
      },
      {
        title: '预计归还日期',
        render: (item: A2AListType) => item.dateEnd || '（空）'
      },
      {
        title: '租赁方名称',
        render: (item: A2AListType) => item.zlName || '（空）'
      },
      {
        title: '地区',
        render: (item: A2AListType) =>
          !item.zlProvince && !item.zlCity ? '（空）' : `${item.zlProvince}-${item.zlCity}`
      },
      {
        title: '负责人',
        render: (item: A2AListType) => item.zlUser || '（空）'
      },
      {
        title: '联系方式',
        render: (item: A2AListType) => item.zlPhone || '（空）'
      },
      {
        title: '设备台数',
        render: (item: A2AListType) => item.pcs || '（空）'
      },

      {
        title: '编辑人',
        render: (item: A2AListType) => item.creatorName || '（空）'
      },
      {
        title: '更新日期',
        render: (item: A2AListType) => item.updateTime || '（空）'
      },

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

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

  // 左上角的 title
  const leftTitle = useMemo(() => {
    const obj = {
      '': '业务订单',
      新增: '业务订单-新增',
      编辑: '业务订单-编辑'
    }
    return obj[openInfo.txt]
  }, [openInfo.txt])

  // 时间选择器改变
  const timeChange = (date: any, dateString: any) => {
    let dateStart = ''
    let dateEnd = ''
    if (dateString[0] && dateString[1]) {
      dateStart = dateString[0] + ' 00:00:00'
      dateEnd = dateString[1] + ' 23:59:59'
    }
    setTableSelect({ ...tableSelect, dateStart, dateEnd })
  }
  // 第二个信息标题
  const tit2 = useMemo(() => {
    return Reflect.get(A2AtopTypeObj, topType)
  }, [topType])

  return (
    <div className={styles.A2Abusiness}>
      <div className='pageTitle'>
        {leftTitle}
        {openInfo.id ? `（${A2AtopTypeArr.find(v => v.key === topType)!.name}）` : ''}
      </div>
      {/* 顶部筛选 */}
      <div className='A2Atop'>
        <div className='A2AtopSon'>
          {A2AtopTypeArr.map(item => (
            <Button
              key={item.key}
              onClick={() => setTopType(item.key)}
              type={item.key === topType ? 'primary' : 'default'}
            >
              {item.name}
            </Button>
          ))}
        </div>

        <div className='A2AtopSon'>
          <div className='A2AtopRow'>
            <span>订单编号：</span>
            <Input
              key={inputKey}
              maxLength={12}
              style={{ width: 190 }}
              placeholder='请输入内容，最多12字'
              allowClear
              onChange={e => txtChangeFu(e.target.value, 'num')}
            />
          </div>

          <div className='A2AtopRow'>
            <span>钉钉审批号：</span>
            <Input
              key={inputKey}
              maxLength={30}
              style={{ width: 190 }}
              placeholder='请输入内容，最多30字'
              allowClear
              onChange={e => txtChangeFu(e.target.value, 'dingNum')}
            />
          </div>

          <div className='A2AtopRow'>
            <span>{A2AtopTypeEditLabel(topType)}日期：</span>
            <RangePicker key={inputKey} onChange={timeChange} />
          </div>

          <div className='A2AtopRow'>
            <span>{tit2}名称：</span>
            <Input
              key={inputKey}
              maxLength={20}
              style={{ width: 190 }}
              placeholder='请输入内容，最多20字'
              allowClear
              onChange={e => txtChangeFu(e.target.value, 'zlName')}
            />
          </div>
        </div>

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

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

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

          <div>
            <Button onClick={resetSelectFu}>重置</Button>
            <Button type='primary' onClick={clickSearch}>
              查询
            </Button>
            <Button type='primary' onClick={() => setOpenInfo({ id: -1, txt: '新增' })}>
              新增
            </Button>
            <Button type='primary' onClick={deriveFu}>
              导出表格
            </Button>
          </div>
        </div>
      </div>
      {/* 表格主体 */}
      <div className='tableMain'>
        <Table
          scroll={{ y: 510 }}
          dataSource={A2ATableList.list}
          columns={columns}
          rowKey='id'
          pagination={{
            showQuickJumper: true,
            position: ['bottomCenter'],
            showSizeChanger: true,
            current: tableSelect.pageNum,
            pageSize: tableSelect.pageSize,
            total: A2ATableList.total,
            onChange: paginationChange()
          }}
        />
      </div>

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

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

const MemoA2Abusiness = React.memo(A2Abusiness)

export default MemoA2Abusiness
