import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import styles from './index.module.scss'
import { A2BaddType } from '../data'
import { A2AListCamerasType } from '@/types'
import { A1addType } from '@/pages/A1Camera/data'
import { Button, DatePicker, Form, FormInstance, Input, Table, Tag, Tooltip } from 'antd'
import MyPopconfirm from '@/components/MyPopconfirm'
import { A2B_APIadd, A2B_APIgetCamera, A2B_APIgetInfo } from '@/store/action/A2Blogistics'
import dayjs from 'dayjs'
import { MessageFu } from '@/utils/message'
import UpXlsx from '@/components/UpXlsx'
import AddCamera from '@/pages/A1Camera/AddCamera'
import TextArea from 'antd/lib/input/TextArea'
import CheckTable from '../CheckTable'

type Props = {
  openInfo: A2BaddType
  closeFu: () => void
  upTableFu: () => void
  addTableFu: () => void
  orderNumTemp?: string //当从业务订单详情中，点击“新增出库“”新增入库“时，需带入业务订单编号
}

function AddLogistics({ openInfo, closeFu, upTableFu, addTableFu, orderNumTemp }: Props) {
  // 关联业务订单
  const [orderNum, setOrderNum] = useState('')
  // 关联业务订单--查询
  const [orderNumSearch, setOrderNumSearch] = useState('')

  useEffect(() => {
    if (orderNumTemp) setOrderNum(orderNumTemp)
  }, [orderNumTemp])

  // 表格数据
  const [tableList, setTableList] = useState<A2AListCamerasType[]>([])

  // 点击表格里面新增的数据
  const [tableAdd, setTableAdd] = useState<A1addType>({ id: 0, txt: '' })

  // 表格点击删除
  const delTableFu = useCallback(
    (idxx: number) => {
      setTableList(tableList.filter(v => v.idxx !== idxx))
    },
    [tableList]
  )

  const columns = useMemo(() => {
    return [
      {
        width: 100,
        title: '相机类型',
        render: (item: A2AListCamerasType) =>
          item.cameraType ? (item.cameraType === 'KK' ? '看看' : '看见') : '（空）'
      },
      {
        title: 'SN码',
        render: (item: A2AListCamerasType) => (
          <>
            {item.cameraSn}
            {item.id ? (
              ''
            ) : (
              <Tooltip title='此SN编码未录入在相机列表中'>
                &nbsp;
                <Tag>new</Tag>
              </Tooltip>
            )}
          </>
        )
      },
      {
        title: '备注',
        render: (item: A2AListCamerasType) =>
          item.remark ? (
            item.remark.length >= 50 ? (
              <span style={{ cursor: 'pointer' }} title={item.remark}>
                {item.remark.substring(0, 50) + '...'}
              </span>
            ) : (
              item.remark
            )
          ) : (
            '（空）'
          )
      },
      {
        title: '操作',
        render: (item: A2AListCamerasType) => (
          <MyPopconfirm txtK='删除' onConfirm={() => delTableFu(item.idxx)} />
        )
      }
    ]
  }, [delTableFu])

  // 表单的ref
  const FormBoxRef = useRef<FormInstance>(null)

  // 通过id获取详情
  const getInfoFu = useCallback(async (id: number) => {
    const res = await A2B_APIgetInfo(id)
    if (res.code === 0) {
      const data = res.data

      // 回显业务订单
      setOrderNum(data.orderNum)

      // 回显表格
      setTableList(
        data.cameras.map((v: any) => ({
          ...v,
          idxx: v.id
        }))
      )

      const obj = {
        ...data,
        city: data.zlProvince + '-' + data.zlCity,
        dateStart: data.dateStart ? dayjs(data.dateStart) : null
      }

      FormBoxRef.current?.setFieldsValue(obj)
    }
  }, [])

  // 没有通过校验
  const onFinishFailed = useCallback(() => {}, [])

  // 通过校验点击确定
  const onFinish = useCallback(
    async (value: any) => {
      // 日期处理
      let dateStart = ''

      if (value.dateStart) dateStart = dayjs(value.dateStart).format('YYYY-MM-DD')

      const obj = {
        ...value,
        id: openInfo.txt === '新增' ? null : openInfo.id,
        cameras: tableList,
        dateStart,
        type: openInfo.type,
        orderNum
      }

      // if (1 + 1 === 2) {
      //   console.log(obj)

      //   return
      // }

      const res = await A2B_APIadd(obj)
      if (res.code === 0) {
        MessageFu.success(openInfo.txt + '成功!')
        openInfo.txt === '新增' ? addTableFu() : upTableFu()
        closeFu()
      }
    },
    [addTableFu, closeFu, openInfo.id, openInfo.txt, openInfo.type, orderNum, tableList, upTableFu]
  )

  useEffect(() => {
    if (openInfo.txt === '新增') {
    } else getInfoFu(openInfo.id)
  }, [getInfoFu, openInfo])

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

  // 点击 从业务订单中添加
  const getCameraFu = useCallback(async () => {
    if (!orderNumSearch) return MessageFu.warning('请输入查询的业务订单编号')
    const res = await A2B_APIgetCamera(orderNumSearch)
    if (res.code === 0) {
      const data: A2AListCamerasType[] = res.data || []
      if (data.length) {
        // 打开筛选列表
        setCheckList(
          data.map(v => ({
            ...v,
            idxx: v.id
          }))
        )
        setCheckShow(true)
      } else {
        MessageFu.warning('未查询到业务订单')
      }
    }
  }, [orderNumSearch])

  // 关联业务订单列表
  const [checkList, setCheckList] = useState<A2AListCamerasType[]>([])

  // 关联业务订单 打开 关闭
  const [checkShow, setCheckShow] = useState(false)

  // 从业务订单 弹窗列表中点击确定
  const checkSonBtnOk = useCallback(
    (arr: A2AListCamerasType[], delIdxx: number[]) => {
      const idxxArr = arr.map(v => v.idxx)

      const oldArr = tableList.filter(v => !idxxArr.includes(v.idxx))
      const newArr = [...arr, ...oldArr]

      const newArrRes = newArr.filter(v => !delIdxx.includes(v.idxx))

      setTableList(newArrRes)
    },
    [tableList]
  )

  return (
    <div className={styles.AddLogistics}>
      {/* 从业务订单进来 才显示在右边的  入库还是出库 */}
      {orderNumTemp ? (
        <div className='A2AlookToA2Badd'>{openInfo.type === 'CK' ? '新增出库' : '新增入库'}</div>
      ) : null}

      <div className='A2BaddMain'>
        <Form
          scrollToFirstError={true}
          ref={FormBoxRef}
          // labelCol={{ span: 4 }}
          name='basicWai'
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete='off'
        >
          <div className='A2Btit'>订单信息</div>

          <Form.Item
            label={openInfo.type === 'CK' ? '发货日期' : '收货日期'}
            name='dateStart'
            rules={[{ required: true, message: '请选择日期!' }]}
          >
            <DatePicker placeholder='请选择日期' />
          </Form.Item>

          <Form.Item label={openInfo.type === 'CK' ? '收货地址' : '发货地址'} name='address'>
            <Input maxLength={50} showCount placeholder='请输入内容' />
          </Form.Item>

          <Form.Item
            label='物流编号'
            name='logisticsNum'
            rules={[{ required: true, message: '请输入内容!' }]}
            getValueFromEvent={e => e.target.value.replace(/\s+/g, '')}
          >
            <Input maxLength={20} showCount placeholder='请输入内容' />
          </Form.Item>

          <Form.Item label='备注' name='rtf'>
            <TextArea maxLength={200} showCount placeholder='请输入内容' />
          </Form.Item>

          <div className='A2Btit A2Btit3'>业务订单</div>

          <div className='formBox'>
            <div className='formBoxLL'>关联业务订单：</div>
            <div className='formBoxRR'>
              <Input
                disabled={!!orderNumTemp}
                value={orderNum}
                onChange={e => setOrderNum(e.target.value.replace(/\s+/g, ''))}
                maxLength={12}
                showCount
                placeholder='请输入内容'
              />
            </div>
          </div>

          {/* 确定和取消按钮 */}
          <Form.Item className='A2BaddBtn'>
            <Button type='primary' htmlType='submit'>
              提交
            </Button>
            <br />
            <br />
            <MyPopconfirm txtK='取消' onConfirm={closeFu} />
          </Form.Item>
        </Form>

        <div className='A2Btit A2Btit2'>
          <div>
            <div className='A2Btit2Row'>
              相机清单&emsp;&emsp;{' '}
              <Input
                value={orderNumSearch}
                onChange={e => setOrderNumSearch(e.target.value.replace(/\s+/g, ''))}
                maxLength={12}
                showCount
                placeholder='请输入业务订单编号'
                style={{ width: 400 }}
              />
            </div>
            <div>
              <Button type='primary' onClick={getCameraFu}>
                从业务订单中查询
              </Button>

              <a href='/xlsx/相机列表导入模板.xlsx' download>
                <Button type='primary'>下载模块</Button>
              </a>
              <UpXlsx
                url='cms/logistics/upload/excel'
                ref={upXlsxRef}
                xlsxResInfoFu={arr => setTableList([...arr, ...tableList])}
                dirCode='logisticsXlsx'
                existSn={tableList.map(v => v.cameraSn)}
              />

              <Button type='primary' onClick={() => upXlsxRef.current?.myInputClickFu()}>
                批量导入
              </Button>
              <Button
                type='primary'
                onClick={() => {
                  if (tableList.length >= 200) return MessageFu.warning('最多支持200条数据!')
                  setTableAdd({ id: -1, txt: '新增' })
                }}
              >
                新增
              </Button>
            </div>
          </div>
        </div>

        {/* --------------表格-------------- */}
        <div className='tableListBox'>
          <Table
            size='small'
            dataSource={tableList}
            columns={columns}
            rowKey='idxx'
            pagination={false}
          />
          {/*  右下角的列表数量 */}
          <div className='tableNumBox'>
            共 <span>{tableList.length}</span> 条数据
          </div>
        </div>
      </div>
      {/* 点击表格里面的新增 出来的页面 */}
      {tableAdd.id ? (
        <div className='A2BtableBoxAdd'>
          <div>
            <AddCamera
              isLoc={true}
              existSn={tableList.map(v => v.cameraSn)}
              openInfo={tableAdd}
              closeFu={() => setTableAdd({ id: 0, txt: '' })}
              upTableFu={() => {}}
              addTableFu={info => setTableList([info, ...tableList])}
            />
          </div>
        </div>
      ) : null}
      {/* 点击关联业务订单 打开的页面*/}
      {checkShow ? (
        <div className='A2BtableBoxAdd'>
          <div>
            <CheckTable
              checkTableList={checkList}
              allList={tableList}
              checkSonBtnOk={(arr, delIdxx) => checkSonBtnOk(arr, delIdxx)}
              checkSonClose={() => setCheckShow(false)}
            />
          </div>
        </div>
      ) : null}
    </div>
  )
}

const MemoAddLogistics = React.memo(AddLogistics)

export default MemoAddLogistics
