import React, { useCallback, useEffect, useRef, useState } from 'react'
import styles from './index.module.scss'
import { Button, Form, FormInstance, Input, Modal, Select } from 'antd'
import MyPopconfirm from '@/components/MyPopconfirm'
import TextArea from 'antd/es/input/TextArea'
import Z3upFiles from '@/components/Z3upFiles'
import ZRichTexts from '@/components/ZRichTexts'
import { selectObj } from '@/utils/select'
import { B1X_APIgetInfo, B1X_APIsave } from '@/store/action/B1collect'
import { MessageFu } from '@/utils/message'
import { B1Xtype } from '../../type'

type Props = {
  sId: number
  closeFu: () => void
  succFu: (val: B1Xtype, txt: '新增' | '编辑') => void
  look?: boolean
}

function B1MoAdd({ sId, closeFu, succFu, look = false }: Props) {
  const [file, setFile] = useState([])

  const getInfoFu = useCallback(async (id: number) => {
    const res = await B1X_APIgetInfo(id)
    if (res.code === 0) {
      const data: B1Xtype = res.data
      FormBoxRef.current?.setFieldsValue({
        ...data,
        type: data.type ? data.type : null
      })
      // 设置富文本
      ZRichTextRef.current?.ritxtShowFu(JSON.parse(data.rtf || '{}'))

      // 设置附件
      setFile(data.file || [])
    }
  }, [])

  useEffect(() => {
    if (sId > 0) getInfoFu(sId)
  }, [getInfoFu, sId])

  // 设置表单初始数据（区分编辑和新增）
  const FormBoxRef = useRef<FormInstance>(null)

  // 没有通过校验
  const onFinishFailed = useCallback(() => {
    // return MessageFu.warning("有表单不符号规则!");
  }, [])

  // 通过校验点击确定
  const onFinish = useCallback(
    async (values: any) => {
      const rtf1 = ZRichTextRef.current?.fatherBtnOkFu() || { flag: true }

      // 上传附件
      const filesRes = filesRef.current.filesIdRes()

      const obj = {
        ...values,
        fileIds: filesRes.join(','),
        rtf: JSON.stringify(rtf1.val || ''),
        id: sId > 0 ? sId : null
      }

      const res = await B1X_APIsave(obj)

      if (res.code === 0) {
        MessageFu.success(sId > 0 ? '编辑成功' : '新增成功')
        succFu(res.data, sId > 0 ? '编辑' : '新增')
        closeFu()
      }
    },
    [closeFu, sId, succFu]
  )

  // 上传附件的ref
  const filesRef = useRef<any>(null)

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

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

  return (
    <Modal
      wrapClassName={styles.B1MoAdd}
      destroyOnClose
      open={true}
      title={`征集线索-${look ? '查看' : sId > 0 ? '编辑' : '新增'}`}
      footer={
        [] // 设置footer为空，去掉 取消 确定默认按钮
      }
    >
      <div className='B1Mmain'>
        <Form
          scrollToFirstError={true}
          ref={FormBoxRef}
          name='basic'
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete='off'
        >
          <div className='B1MformBox'>
            <Form.Item
              label='线索名称'
              name='name'
              rules={[{ required: true, message: '请输入线索名称' }]}
            >
              <Input readOnly={look} maxLength={30} showCount placeholder='请输入内容' />
            </Form.Item>

            <Form.Item label='线索类别' name='type'>
              <Select disabled={look} placeholder='请选择' options={selectObj['线索类别']} />
            </Form.Item>

            <Form.Item label='联系人' name='linkman'>
              <Input readOnly={look} maxLength={30} showCount placeholder='请输入内容' />
            </Form.Item>
            <Form.Item label='联系电话' name='phone'>
              <Input readOnly={look} maxLength={30} showCount placeholder='请输入内容' />
            </Form.Item>
            <Form.Item label='联系地址' name='addr'>
              <TextArea readOnly={look} maxLength={500} showCount placeholder='请输入内容' />
            </Form.Item>

            <div className='B1Mrow'>
              <div className='B1Mrowll'>附件：</div>
              <div className='B1Mrowrr'>
                <Z3upFiles
                  max={10}
                  isLook={look}
                  ref={filesRef}
                  fileCheck={false}
                  dirCode='B1collectSon'
                  myUrl='cms/orderCollect/upload'
                  lookData={file}
                  size={500}
                />
              </div>
            </div>

            <div className='B1Mrow'>
              <div className='B1Mrowll'>备注：</div>
              <div className='B1Mrowrr'>
                <ZRichTexts
                  check={false}
                  dirCode='B1collectSon'
                  myUrl='cms/orderCollect/upload'
                  isLook={look}
                  ref={ZRichTextRef}
                  isOne={true}
                  upAudioBtnNone={true}
                />
              </div>
            </div>
          </div>

          {/* 确定和取消按钮 */}
          <Form.Item className='B1Mbtn'>
            {look ? (
              <Button onClick={closeFu}>关闭</Button>
            ) : (
              <>
                <Button type='primary' htmlType='submit'>
                  提交
                </Button>
                &emsp;
                <MyPopconfirm txtK='取消' onConfirm={closeFu} />
              </>
            )}
          </Form.Item>
        </Form>
      </div>
    </Modal>
  )
}

const MemoB1MoAdd = React.memo(B1MoAdd)

export default MemoB1MoAdd
