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,
  InputNumber,
  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 { A2AtopTypeEditLabel, A2AtopTypeObj, TopTypeType } from '../data'
import { A2AListCamerasType } from '@/types'

type Props = {
  topType: TopTypeType
  openInfo: A1addType
  closeFu: () => void
  upTableFu: () => void
  addTableFu: () => void
}

function AddBusiness({ topType, openInfo, closeFu, upTableFu, addTableFu }: Props) {
  // 表格数据
  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 A2A_APIgetInfo(id)
    if (res.code === 0) {
      const data = res.data

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

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

      // 设置富文本-问题描述
      ZRichTextsRef2.current?.ritxtShowFu(JSON.parse(data.rtfDesc))

      // 回显表格
      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 rtfDesc = ZRichTextsRef2.current?.fatherBtnOkFu() || { flag: true }

      const obj = {
        ...value,
        id: openInfo.txt === '新增' ? null : openInfo.id,
        fileIds: listFilesRes.join(','),
        rtf: JSON.stringify(rtf.val || ''),
        rtfDesc: JSON.stringify(rtfDesc.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)
  const ZRichTextsRef2 = useRef<any>(null)

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

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

  // 第二个信息标题
  const tit2 = useMemo(() => {
    return Reflect.get(A2AtopTypeObj, topType)
  }, [topType])

  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={`${A2AtopTypeEditLabel(topType)}日期`}
            name='dateStart'
            rules={[{ required: true, message: '请选择日期!' }]}
          >
            <DatePicker placeholder='请选择日期' />
          </Form.Item>

          {['ZL', 'WX'].includes(topType) ? (
            <Form.Item label={topType === 'ZL' ? '预计归还日期' : '完成日期'} name='dateEnd'>
              <DatePicker placeholder='请选择日期' />
            </Form.Item>
          ) : null}

          {['BX', 'DS', 'WX'].includes(topType) ? (
            <div className='formBox'>
              <div className='formBoxLL'>
                {topType === 'BX' ? '问题描述' : topType === 'DS' ? '定损结果' : '处理结果'}：
              </div>
              <div className='formBoxRR'>
                <ZRichTexts
                  check={false}
                  dirCode='A2business'
                  isLook={false}
                  ref={ZRichTextsRef2}
                  myUrl='cms/order/upload'
                  topType={topType}
                />
              </div>
            </div>
          ) : null}

          {['DS'].includes(topType) ? (
            <Form.Item
              label='定损报价'
              name='price'
              rules={[{ required: true, message: '请输入内容!' }]}
            >
              <InputNumber
                style={{ width: 300 }}
                placeholder='请输入数字，支持小数点后两位'
                precision={2}
              />
            </Form.Item>
          ) : null}

          {['DS', 'WX'].includes(topType) ? (
            <Form.Item label={topType === 'DS' ? '报损单发送对象' : '处理人'} name='user'>
              <Input maxLength={30} showCount placeholder='请输入内容' />
            </Form.Item>
          ) : null}

          <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'>{tit2}信息</div>

          <Form.Item
            label={`${tit2}名称`}
            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={arr => setTableList([...arr, ...tableList])}
                dirCode='businessXlsx'
                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='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
