import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import styles from './index.module.scss'
import { Button, DatePicker, Input, Select, Table } from 'antd'
import { A2BaddType, A2BFromDataType, A2BFromTypeArr } from './data'
import { useDispatch, useSelector } from 'react-redux'
import { A2B_APIgetlist, A2B_APIgetlistDerive, A2B_APIremove } from '@/store/action/A2Blogistics'
import ExportJsonExcel from 'js-export-excel'
import { RootState } from '@/store'
import { MessageFu } from '@/utils/message'
import dayjs from 'dayjs'
import { A2BListType } from '@/types'
import history from '@/utils/history'
import MyPopconfirm from '@/components/MyPopconfirm'
import { A2AtopTypeArr } from '../A2Abusiness/data'
import AddLogistics from './AddLogistics'

const tableSelectBase: A2BFromDataType = {
  num: '',
  type: '',
  orderNum: '',
  orderType: '',
  dateStart: '',
  dateEnd: '',
  pageSize: 10,
  pageNum: 1
}

function A2Blogistics() {
  const dispatch = useDispatch()

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

  const tableSelectRef = useRef({} as A2BFromDataType)

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

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

  // 发送接口的函数
  const getListFu = useCallback(() => {
    const obj = {
      ...tableSelectRef.current
    }
    dispatch(A2B_APIgetlist(obj))
  }, [dispatch])

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

  // 输入框的改变
  const txtChangeFu = useCallback(
    (txt: string, key: 'num' | 'orderNum') => {
      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)
  }, [])

  // 2个日期选择框的改变
  const timeChange1 = useCallback(
    (_: any, dateString: string) => {
      let dateStart = ''
      if (dateString) dateStart = dateString + ' 00:00:00'
      setTableSelect({ ...tableSelect, dateStart })
    },
    [tableSelect]
  )

  const timeChange2 = useCallback(
    (_: any, dateString: string) => {
      let dateEnd = ''
      if (dateString) dateEnd = dateString + ' 23:59:59'
      setTableSelect({ ...tableSelect, dateEnd })
    },
    [tableSelect]
  )

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

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

    if (A2BTableList.list.length === 0) return MessageFu.warning('当前搜索条件没有数据!')
    const name = '物流订单' + dayjs(new Date()).format('YYYY-MM-DD HH:mm')

    const res = await A2B_APIgetlistDerive({
      ...tableSelect,
      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: A2BListType) => ({
              num: item.num || '空',
              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() //保存
    }
  }, [A2BTableList.list.length, A2BTableList.total, tableSelect])

  const columns = useMemo(() => {
    return [
      {
        title: '订单编号',
        render: (item: A2BListType) => item.num || '（空）'
      },
      {
        title: '订单类型',
        render: (item: A2BListType) => (item.type === 'CK' ? '出库' : '入库')
      },
      {
        title: '关联业务订单号',
        render: (item: A2BListType) => item.orderNum || '（空）'
      },
      {
        title: '关联业务类型',
        render: (item: A2BListType) =>
          A2AtopTypeArr.find(v => v.key === item.orderType)?.name || '（空）'
      },
      {
        title: '发货日期',
        render: (item: A2BListType) => (item.type === 'CK' ? item.dateStart || '（空）' : '/')
      },
      {
        title: '收货日期',
        render: (item: A2BListType) => (item.type === 'RK' ? item.dateStart || '（空）' : '/')
      },
      {
        title: '编辑人',
        render: (item: A2BListType) => item.creatorName || '（空）'
      },
      {
        title: '更新日期',
        render: (item: A2BListType) => item.updateTime || '（空）'
      },

      {
        title: '备注',
        render: (item: A2BListType) =>
          item.rtf ? (
            item.rtf.length >= 50 ? (
              <span style={{ cursor: 'pointer' }} title={item.rtf}>
                {item.rtf.substring(0, 50) + '...'}
              </span>
            ) : (
              item.rtf
            )
          ) : (
            '（空）'
          )
      },

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

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

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

  return (
    <div className={styles.A2Blogistics}>
      <div className='pageTitle'>
        {leftTitle}
        {openInfo.type ? (openInfo.type === 'CK' ? '（出库）' : '（入库）') : ''}
      </div>
      {/* 顶部筛选 */}
      <div className='A2Btop'>
        <div className='A2BtopSon'>
          <div className='A2BtopRow'>
            <span>订单编号：</span>
            <Input
              key={inputKey}
              maxLength={12}
              style={{ width: 190 }}
              placeholder='请输入内容，最多12字'
              allowClear
              onChange={e => txtChangeFu(e.target.value, 'num')}
            />
          </div>

          <div className='A2BtopRow'>
            <span>订单类型：</span>
            <Select
              style={{ width: 190 }}
              value={tableSelect.type}
              onChange={e => setTableSelect({ ...tableSelect, type: e })}
              options={A2BFromTypeArr}
            />
          </div>

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

          <div className='A2BtopRow'>
            <span>关联业务类型：</span>
            <Select
              style={{ width: 190 }}
              value={tableSelect.orderType}
              onChange={e => setTableSelect({ ...tableSelect, orderType: e })}
              options={[
                { value: '', label: '全部' },
                ...A2AtopTypeArr.map(v => ({ value: v.key, label: v.name }))
              ]}
            />
          </div>
        </div>

        <div className='A2BtopSon A2BtopSon2'>
          <div>
            <div className='A2BtopRow'>
              <span>发货日期：</span>
              <DatePicker style={{ width: 190 }} key={inputKey} onChange={timeChange1} />
            </div>

            <div className='A2BtopRow'>
              <span>收货日期：</span>
              <DatePicker style={{ width: 190 }} key={inputKey} onChange={timeChange2} />
            </div>
          </div>

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

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

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

const MemoA2Blogistics = React.memo(A2Blogistics)

export default MemoA2Blogistics
