import React, { useCallback, useEffect, useRef } from 'react'
import styles from './index.module.scss'
import { A1ListSelectType } from '@/pages/A1record/data'
import { Button, Form, FormInstance, Input, Select } from 'antd'
import { A4_APIgetInfo, A4_APIsave } from '@/store/action/A4antique'
import { MessageFu } from '@/utils/message'
import TextArea from 'antd/es/input/TextArea'
import ZupTypes from '@/components/ZupTypes'
import MyPopconfirm from '@/components/MyPopconfirm'

type Props = {
  sId: number
  closeFu: () => void
  addTableFu: () => void
  upTableFu: () => void
  listAllRes: A1ListSelectType
  // 从烈士信息中进来
  martyrId?: number
}

function A4add({ sId, closeFu, addTableFu, upTableFu, listAllRes, martyrId }: Props) {
  // 表单的ref
  const FormBoxRef = useRef<FormInstance>(null)

  // 多张图片的ref
  const ZupImgsRef = useRef<any>(null)

  // 编辑进来获取详情
  const getInfoFu = useCallback(async (id: number) => {
    const res = await A4_APIgetInfo(id)
    if (res.code === 0) {
      const obj = res.data

      // 线索地址
      if (obj.province) obj.myCity = [obj.province]
      if (obj.city) obj.myCity.push(obj.city)
      if (obj.region) obj.myCity.push(obj.region)

      FormBoxRef.current?.setFieldsValue(obj)
    }

    const file = res.data.img || []
    // 传给 附件 组件的
    const sonInfo = {
      type: 'img',
      fileList: file
    }
    ZupImgsRef.current?.setFileComFileFu(sonInfo)
  }, [])

  useEffect(() => {
    if (sId > 0) getInfoFu(sId)
    if (martyrId) FormBoxRef.current?.setFieldsValue({ martyrId })
  }, [getInfoFu, martyrId, sId])

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

  //  通过校验点击确定
  const onFinish = useCallback(
    async (values: any) => {
      // 多张图片
      const { sonFileIds, sonIsOk, coverUrl, coverUrlBig } = ZupImgsRef.current?.fileComFileResFu()

      const obj = {
        ...values,
        id: sId > 0 ? sId : null,
        thumb: coverUrl || '',
        thumbPc: coverUrlBig || '',
        imgIds: sonIsOk ? '' : sonFileIds.join(',')
      }

      const res = await A4_APIsave(obj)
      if (res.code === 0) {
        MessageFu.success(sId > 0 ? '编辑成功' : '新增成功')
        sId > 0 ? upTableFu() : addTableFu()
        closeFu()
      }
    },
    [addTableFu, closeFu, sId, upTableFu]
  )

  const formDomRef = useRef<HTMLDivElement>(null)

  return (
    <div className={styles.A4add} style={{ position: martyrId ? 'fixed' : 'absolute' }}>
      <div className='A4addMain'>
        <div className='A4aTit'>{sId > 0 ? '编辑' : '新增'}文物</div>

        <div className='A4accc' ref={formDomRef}>
          <div>
            <Form
              ref={FormBoxRef}
              name='basic'
              onFinish={onFinish}
              onFinishFailed={onFinishFailed}
              autoComplete='off'
              scrollToFirstError
            >
              <div className='A4aRow'>
                <Form.Item
                  label='文件名称'
                  name='name'
                  rules={[{ required: true, message: '请输入文件名称' }]}
                  // getValueFromEvent={(e) => e.target.value.replace(/\s+/g, "")}
                  getValueFromEvent={e => e.target.value.trim()}
                >
                  <Input maxLength={50} showCount placeholder='请输入内容' />
                </Form.Item>

                <Form.Item
                  label='关联烈士'
                  name='martyrId'
                  rules={[{ required: true, message: '请选择关联烈士' }]}
                >
                  <Select
                    disabled={!!martyrId}
                    getPopupContainer={() => formDomRef.current!}
                    filterOption={(input, option) =>
                      (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
                    }
                    placeholder='请搜索并选择'
                    showSearch
                    options={listAllRes}
                  />
                </Form.Item>
              </div>

              {/* 多个图片 */}
              <div className='formRow'>
                <div className='formLeft'>图片：</div>
                <div className='formRight'>
                  <ZupTypes
                    multipleImg={true}
                    ref={ZupImgsRef}
                    isLook={false}
                    fileCheck={false}
                    selecFlag='图片'
                    imgSize={5}
                    imgLength={99999}
                    dirCode='A4antique'
                    myUrl='cms/relic/upload'
                    isTypeShow={true}
                    oneIsCover={true}
                  />
                </div>
              </div>

              <div className='A4aRowAll'>
                <Form.Item label='文件介绍' name='intro'>
                  <TextArea maxLength={500} showCount placeholder='请输入内容' />
                </Form.Item>
              </div>

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

const MemoA4add = React.memo(A4add)

export default MemoA4add
