import React, { useCallback, useEffect, useRef } from 'react'
import styles from './index.module.scss'
import { Button, Cascader, Form, FormInstance, Input, Radio, Select } from 'antd'
import { A2_APIgetInfo, A2_APIsave } from '@/store/action/A2clue'
import { MessageFu } from '@/utils/message'
import { A2select1, A2select2 } from '../data'
import { myCity } from '@/utils/history'
import ZupTypes from '@/components/ZupTypes'
import ZupVideos from '@/components/ZupVideos'
import MyPopconfirm from '@/components/MyPopconfirm'
import TextArea from 'antd/es/input/TextArea'
import { A1ListSelectType } from '@/pages/A1record/data'

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

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

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

  // 多个视频的ref
  const ZupVideosRef = useRef<any>(null)

  // 编辑进来获取详情
  const getInfoFu = useCallback(async (id: number) => {
    const res = await A2_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)
    ZupVideosRef.current?.setFileComFileFu(res.data.video || [])
  }, [])

  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 } = ZupImgsRef.current?.fileComFileResFu()

      // 多个视频
      const list = ZupVideosRef.current?.fileComFileResFu() || []

      // 线索地址
      let province = ''
      let city = ''
      let region = ''

      if (values.myCity && values.myCity.length) {
        province = values.myCity[0] || ''
        city = values.myCity[1] || ''
        region = values.myCity[2] || ''
      }

      const obj = {
        ...values,
        id: sId > 0 ? sId : null,
        province,
        city,
        region,
        imgIds: sonIsOk ? '' : sonFileIds.join(','),
        videoIds: list.map((v: any) => v.id).join(',')
      }

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

      // if (1 + 1 === 2) {
      //   console.log('------222', obj)
      //   return
      // }
    },
    [addTableFu, closeFu, sId, upTableFu]
  )

  const formDomRef = useRef<HTMLDivElement>(null)

  return (
    <div className={styles.A2add} style={{ position: martyrId ? 'fixed' : 'absolute' }}>
      <div className='A2addMain'>
        <div className='A2aTit'>{sId > 0 ? '编辑' : '新增'}线索</div>

        <div className='A2accc' ref={formDomRef}>
          <div>
            <Form
              ref={FormBoxRef}
              name='basic'
              onFinish={onFinish}
              onFinishFailed={onFinishFailed}
              autoComplete='off'
              scrollToFirstError
            >
              <div className='A2aRow'>
                <Form.Item
                  label='线索类型'
                  name='type'
                  rules={[{ required: true, message: '请选择线索类型' }]}
                >
                  <Select
                    getPopupContainer={() => formDomRef.current!}
                    placeholder='请选择'
                    options={A2select1}
                  />
                </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='A2aRow'>
                <Form.Item
                  label='线索状态'
                  name='status'
                  rules={[{ required: true, message: '请选择线索状态' }]}
                >
                  <Radio.Group options={A2select2} />
                </Form.Item>
                <Form.Item label='提供者信息' name='supply'>
                  <Input maxLength={50} showCount placeholder='请输入内容' />
                </Form.Item>
              </div>

              <div className='A2aRow'>
                <Form.Item label='线索地址' name='myCity'>
                  <Cascader options={myCity} placeholder='请选择' allowClear changeOnSelect />
                </Form.Item>
                <Form.Item label='线索详址' name='address'>
                  <Input maxLength={50} showCount placeholder='请输入内容' />
                </Form.Item>
              </div>

              <div className='A2aRowAll'>
                <Form.Item label='线索说明' name='remark'>
                  <TextArea maxLength={500} showCount placeholder='请输入内容' />
                </Form.Item>
              </div>

              <div className='A2aRowAll'>
                <Form.Item label='处理结果' name='result'>
                  <TextArea maxLength={1000} showCount placeholder='请输入内容' />
                </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='A2clue'
                    myUrl='cms/clue/upload'
                    isTypeShow={true}
                  />
                </div>
              </div>

              {/* 多个视频 */}
              <div className='formRow formRow2'>
                <div className='formLeft'>视频：</div>
                <div className='formRight'>
                  <ZupVideos
                    isLook={false}
                    size={500}
                    fileNum={50}
                    dirCode='A2clueVideo'
                    myUrl='cms/clue/upload'
                    upTxt='；数量不超过50个。'
                    ref={ZupVideosRef}
                  />
                </div>
              </div>

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

const MemoA2add = React.memo(A2add)

export default MemoA2add
