import React, { useCallback, useEffect, useRef, useState } from 'react'
import styles from './index.module.scss'
import { A1addType } from '../data'
import { Button, Form, FormInstance, Input, Popconfirm } from 'antd'
import { A1_APIadd, A1_APIcheckSN, A1_APIgetInfo } from '@/store/action/A1Camera'
import TextArea from 'antd/es/input/TextArea'
import { MessageFu } from '@/utils/message'

const cameraTypeList: { name: string; key: 'KK' | 'KJ' }[] = [
  { name: '看见', key: 'KJ' },
  { name: '看看', key: 'KK' }
]

type Props = {
  openInfo: A1addType
  closeFu: () => void
  upTableFu: () => void
  addTableFu: (info?: any) => void
  isLoc?: boolean //从业务订单的 新增/编辑-相机清单-新增 进来
  existSn?: string[]
}

function AddCamera({ openInfo, closeFu, upTableFu, addTableFu, isLoc, existSn }: Props) {
  // 表单的ref
  const FormBoxRef = useRef<FormInstance>(null)

  // 通过id获取详情
  const getInfoFu = useCallback(async (id: number) => {
    const res = await A1_APIgetInfo(id)
    if (res.code === 0) {
      FormBoxRef.current?.setFieldsValue(res.data)
      setCameraType(res.data.cameraType || 'KJ')
    }
  }, [])

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

  // 相机类型
  const [cameraType, setCameraType] = useState<'KK' | 'KJ'>('KJ')

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

  // 通过校验点击确定
  const onFinish = useCallback(
    async (value: any) => {
      const obj = {
        ...value,
        id: openInfo.txt === '新增' ? null : openInfo.id,
        cameraType,
        typeIn: 'pc'
      }

      if (isLoc) {
        if (existSn && existSn.includes(value.cameraSn)) {
          // 没有存入数据库的时候 自己校验 sn码的唯一性
          return MessageFu.warning('SN码重复!')
        }

        //  传后端检查一下 sn的唯一性
        const topRes = await A1_APIcheckSN(value.cameraSn)

        if (topRes.code === 0) {
          if (topRes.data && topRes.data.length > 0) {
            return MessageFu.warning('SN码重复!')
          } else {
            MessageFu.success('新增成功!')
            obj.idxx = Date.now() + ''
            addTableFu(obj)
            closeFu()
          }
        }
      } else {
        const res = await A1_APIadd(obj)
        if (res.code === 0) {
          MessageFu.success(openInfo.txt + '成功!')
          openInfo.txt === '新增' ? addTableFu() : upTableFu()
          closeFu()
        }
      }
    },
    [addTableFu, cameraType, closeFu, existSn, isLoc, openInfo.id, openInfo.txt, upTableFu]
  )

  return (
    <div className={styles.AddCamera}>
      <div className='A1addMain'>
        <Form
          scrollToFirstError={true}
          ref={FormBoxRef}
          labelCol={{ span: 3 }}
          name='basic'
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete='off'
        >
          <div className='formBox'>
            <div className='formBoxLL'>
              <span>* </span>相机类型：
            </div>
            <div className='formBoxRR'>
              {cameraTypeList.map(item => (
                <Button
                  onClick={() => setCameraType(item.key)}
                  type={item.key === cameraType ? 'primary' : 'default'}
                  key={item.key}
                >
                  {item.name}
                </Button>
              ))}
            </div>
          </div>

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

          <Form.Item label='备注' name='remark'>
            <TextArea
              style={{ width: 600 }}
              autoSize
              placeholder='请输入内容'
              showCount
              maxLength={200}
            />
          </Form.Item>

          {/* 确定和取消按钮 */}
          <br />
          <Form.Item className='A1addBtn'>
            <Button type='primary' htmlType='submit'>
              提交
            </Button>
            &emsp;
            <Popconfirm
              title='放弃编辑后，信息将不会保存!'
              okText='放弃'
              cancelText='取消'
              onConfirm={closeFu}
              okButtonProps={{ loading: false }}
            >
              <Button>取消</Button>
            </Popconfirm>
          </Form.Item>
        </Form>
      </div>
    </div>
  )
}

const MemoAddCamera = React.memo(AddCamera)

export default MemoAddCamera
