import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import styles from './index.module.scss'
import { A1addType } from '@/pages/A1Camera/data'
import { Button, DatePicker, Form, FormInstance, Input, Select, Table, Tag, Tooltip } from 'antd'
import { A2A_APIadd, A2A_APIgetInfo } from '@/store/action/A2Abusiness'
import { MessageFu } from '@/utils/message'
import ZRichTexts from '@/components/ZRichTexts'
import Z3upFiles from '@/components/Z3upFiles'
import MyPopconfirm from '@/components/MyPopconfirm'
import { mapDataAll3 } from '@/pages/C1User/AddUser/city'
import UpXlsx from '@/components/UpXlsx'
import AddCamera from '@/pages/A1Camera/AddCamera'
import dayjs from 'dayjs'
import { TopTypeType } from '../data'

type Props = {
  topType: TopTypeType
  openInfo: A1addType
  closeFu: () => void
  upTableFu: () => void
  addTableFu: () => void
}
export type TableListType = {
  cameraSn: string
  cameraType: string
  remark: string
  id: number
  idxx: string
}

function AddBusiness({ topType, openInfo, closeFu, upTableFu, addTableFu }: Props) {
  // 表格数据
  const [tableList, setTableList] = useState<TableListType[]>([])

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

  const getListFu = useCallback(
    (info: any) => {
      const arr = info.camera || []
      setTableList([...arr, ...tableList])
    },
    [tableList]
  )

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

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

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

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

      // 回显 合同附件
      listFilesRef.current.sonFilesShowFu(data.files)

      // 设置富文本
      ZRichTextsRef1.current?.ritxtShowFu(JSON.parse(data.rtf))

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

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

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

  // 拿来占位，不然会报错
  const onChange = useCallback((value: string) => {
    // console.log(`selected ${value}`)
  }, [])

  const onSearch = useCallback((value: string) => {
    // console.log(`search ${value}`)
  }, [])

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

  // 通过校验点击确定
  const onFinish = useCallback(
    async (value: any) => {
      // 附件
      const listFilesRes = listFilesRef.current.sonFilesIdRes()

      // 日期处理
      const dateStart = dayjs(value.dateStart).format('YYYY-MM-DD')
      let dateEnd = ''

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

      // 城市处理
      const zlProvince = value.city.split('-')[0]
      const zlCity = value.city.split('-')[1]

      // 富文本
      const rtf = ZRichTextsRef1.current?.fatherBtnOkFu() || { flag: true }

      const obj = {
        ...value,
        id: openInfo.txt === '新增' ? null : openInfo.id,
        fileIds: listFilesRes.join(','),
        rtf: JSON.stringify(rtf.val || ''),
        cameras: tableList,
        dateStart,
        dateEnd,
        zlProvince,
        zlCity,
        type: topType
      }

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

      //   return
      // }

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

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

  // 富文本的ref
  const ZRichTextsRef1 = useRef<any>(null)

  // 合同附件的ref
  const listFilesRef = useRef<any>(null)

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

  return (
    <div className={styles.AddBusiness}>
      <div className='A2AaddMain'>
        <Form
          scrollToFirstError={true}
          ref={FormBoxRef}
          // labelCol={{ span: 4 }}
          name='basicWai'
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete='off'
        >
          <div className='A2Atit'>订单信息</div>

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

          <div className='formBox formBox2'>
            <div className='formBoxLL'>合同附件：</div>
            <div className='formBoxRR'>
              <Z3upFiles
                max={5}
                accept='*'
                isLook={false}
                ref={listFilesRef}
                fileCheck={false}
                dirCode='A2business'
                myUrl='cms/order/upload'
                topType={topType}
              />
            </div>
          </div>

          <Form.Item
            label='租凭日期'
            name='dateStart'
            rules={[{ required: true, message: '请选择日期!' }]}
          >
            <DatePicker placeholder='请选择日期' />
          </Form.Item>

          <Form.Item label='预计归还日期' name='dateEnd'>
            <DatePicker placeholder='请选择日期' />
          </Form.Item>

          <div className='formBox'>
            <div className='formBoxLL'>备注：</div>
            <div className='formBoxRR'>
              <ZRichTexts
                check={false}
                dirCode='A2business'
                isLook={false}
                ref={ZRichTextsRef1}
                myUrl='cms/order/upload'
                topType={topType}
              />
            </div>
          </div>

          <div className='A2Atit'>租凭方信息</div>

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

          <Form.Item
            label='城市：'
            name='city'
            rules={[{ required: true, message: '请选择城市!' }]}
          >
            <Select
              style={{ width: 400 }}
              showSearch
              placeholder='请选择城市'
              optionFilterProp='label'
              onChange={onChange}
              onSearch={onSearch}
              options={mapDataAll3}
            />
          </Form.Item>

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

          <Form.Item
            label='联系方式'
            name='zlPhone'
            rules={[{ required: true, message: '请输入内容!' }]}
            getValueFromEvent={e => e.target.value.replace(/\s+/g, '')}
          >
            <Input maxLength={20} showCount placeholder='请输入内容' />
          </Form.Item>
          {/* 确定和取消按钮 */}
          <Form.Item className='A2AaddBtn'>
            <Button type='primary' htmlType='submit'>
              提交
            </Button>
            <br />
            <br />
            <MyPopconfirm txtK='取消' onConfirm={closeFu} />
          </Form.Item>
        </Form>

        <div className='A2Atit A2Atit2'>
          <div>
            <div>相机清单</div>
            <div>
              <a href='/xlsx/相机列表导入模板.xlsx' download>
                <Button type='primary'>下载模块</Button>
              </a>
              <UpXlsx
                url='cms/order/upload/excel'
                ref={upXlsxRef}
                xlsxResInfoFu={info => getListFu(info)}
              />

              <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='A2AtableBoxAdd'>
          <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}
    </div>
  )
}

const MemoAddBusiness = React.memo(AddBusiness)

export default MemoAddBusiness
