import React, { useCallback, useEffect, useRef, useState } from 'react'
import styles from './index.module.scss'
import {
  Button,
  Cascader,
  Checkbox,
  DatePicker,
  Form,
  FormInstance,
  Input,
  Radio,
  Select
} from 'antd'
import MyPopconfirm from '@/components/MyPopconfirm'
import { nationSelect } from '../data'
import { useDispatch } from 'react-redux'
import { A1_APIgetInfo, A1_APIgetNumList, A1_APIsave } from '@/store/action/A1record'
import A1num from '../A1num'
import { myCity } from '@/utils/history'
import TextArea from 'antd/es/input/TextArea'
import ZupTypes from '@/components/ZupTypes'
import ZupVideos from '@/components/ZupVideos'
import dayjs from 'dayjs'
import { MessageFu } from '@/utils/message'

type Props = {
  sId: number
  closeFu: () => void
  addTableFu: () => void
  upTableFu: () => void
}

function A1add({ sId, closeFu, addTableFu, upTableFu }: 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 A1_APIgetInfo(id)
    if (res.code === 0) {
      const obj = res.data

      if (obj.dictPanId) fanHaoRef.current = obj.dictPanId

      // 生卒日期
      if (obj.dateStart) obj.dateStart = dayjs(obj.dateStart)
      if (obj.dateEnd) obj.dateEnd = dayjs(obj.dateEnd)

      // 籍贯
      if (obj.nativeProvince) obj.myNative = [obj.nativeProvince]
      if (obj.nativeCity) obj.myNative.push(obj.nativeCity)
      if (obj.nativeRegion) obj.myNative.push(obj.nativeRegion)

      // 牺牲地
      if (obj.lossProvince) obj.myLoss = [obj.lossProvince]
      if (obj.lossCity) obj.myLoss.push(obj.lossCity)
      if (obj.lossRegion) obj.myLoss.push(obj.lossRegion)

      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)
    else FormBoxRef.current?.setFieldsValue({ nation: '汉族' })
  }, [getInfoFu, sId])

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

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

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

      // 生卒日期
      let dateStart = ''
      if (values.dateStart) dateStart = dayjs(values.dateStart).format('YYYY-MM-DD')
      let dateEnd = ''
      if (values.dateEnd) dateEnd = dayjs(values.dateEnd).format('YYYY-MM-DD')

      // 籍贯
      let nativeProvince = ''
      let nativeCity = ''
      let nativeRegion = ''

      if (values.myNative && values.myNative.length) {
        nativeProvince = values.myNative[0] || ''
        nativeCity = values.myNative[1] || ''
        nativeRegion = values.myNative[2] || ''
      }

      // 牺牲地
      let lossProvince = ''
      let lossCity = ''
      let lossRegion = ''

      if (values.myLoss && values.myLoss.length) {
        lossProvince = values.myLoss[0] || ''
        lossCity = values.myLoss[1] || ''
        lossRegion = values.myLoss[2] || ''
      }

      const obj = {
        ...values,
        id: sId > 0 ? sId : null,
        dateStart,
        dateEnd,
        nativeProvince,
        nativeCity,
        nativeRegion,
        lossProvince,
        lossCity,
        lossRegion,
        thumb: coverUrl || '',
        thumbPc: coverUrlBig || '',
        imgIds: sonIsOk ? '' : sonFileIds.join(','),
        videoIds: list.map((v: any) => v.id).join(',')
      }

      const res = await A1_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)

  // -------------获取牺牲时所在单位列表--------------
  const dispatch = useDispatch()
  useEffect(() => {
    dispatch(A1_APIgetNumList())
  }, [dispatch])

  // const numList = useSelector((state: RootState) => state.A1record.numList)

  const [numShow, setNumShow] = useState(false)

  const fanHaoRef = useRef(0)

  return (
    <div className={styles.A1add}>
      <div className='A1addMain'>
        <div className='A1aTit'>{sId > 0 ? '编辑' : '新增'}烈士</div>

        <div className='A1accc' ref={formDomRef}>
          <div>
            <Form
              ref={FormBoxRef}
              name='basic'
              onFinish={onFinish}
              onFinishFailed={onFinishFailed}
              autoComplete='off'
              scrollToFirstError
            >
              <div className='A1aRow A1aRow3'>
                <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={10} showCount placeholder='请输入内容' />
                </Form.Item>
                <Form.Item
                  label='性别'
                  name='gender'
                  rules={[{ required: true, message: '请选择性别' }]}
                >
                  <Radio.Group
                    options={[
                      { value: 1, label: '男' },
                      { value: 2, label: '女' }
                    ]}
                  />
                </Form.Item>

                <Form.Item valuePropName='checked' label='寻亲烈士' name='display'>
                  <Checkbox></Checkbox>
                </Form.Item>
              </div>

              <div className='A1aRow'>
                <Form.Item label='民族' name='nation'>
                  <Select
                    getPopupContainer={() => formDomRef.current!}
                    allowClear
                    placeholder='请搜索并选择'
                    showSearch
                    options={nationSelect}
                  />
                </Form.Item>
                <Form.Item label='牺牲时所在单位' name='intro'>
                  <Input maxLength={50} showCount placeholder='请输入内容' />
                </Form.Item>
              </div>

              <div className='A1aRow'>
                <Form.Item label='籍贯' name='myNative'>
                  <Cascader options={myCity} placeholder='请选择' allowClear changeOnSelect />
                </Form.Item>
                <Form.Item label='籍贯详址' name='nativeAddress'>
                  <Input maxLength={50} showCount placeholder='请输入内容' />
                </Form.Item>
              </div>

              <div className='A1aRow'>
                <Form.Item label='牺牲地' name='myLoss'>
                  <Cascader options={myCity} placeholder='请选择' allowClear changeOnSelect />
                </Form.Item>
                <Form.Item label='牺牲详址' name='lossAddress'>
                  <Input maxLength={50} showCount placeholder='请输入内容' />
                </Form.Item>
              </div>

              <div className='A1aRow A1aRow3'>
                <Form.Item label='墓区位置' name='tombAddress'>
                  <Input maxLength={50} showCount placeholder='请输入内容' />
                </Form.Item>

                <Form.Item label='出生年月' name='dateStart'>
                  <DatePicker picker='month' placeholder='请选择年月' />
                </Form.Item>
                <Form.Item label='牺牲年月' name='dateEnd'>
                  <DatePicker picker='month' placeholder='请选择年月' />
                </Form.Item>
              </div>

              {/* <div className='A1aRowAll'>
                <Form.Item label='个人介绍' name='intro'>
                  <TextArea maxLength={500} 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='A1record'
                    myUrl='cms/martyr/upload'
                    isTypeShow={true}
                    oneIsCover={true}
                  />
                </div>
              </div>

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

              <div className='A1aRowAll'>
                <Form.Item label='场景链接' name='link'>
                  <TextArea maxLength={500} showCount placeholder='请输入内容' />
                </Form.Item>
              </div>
              <div className='A1aRowAll'>
                <Form.Item label='备注' name='remark'>
                  <TextArea maxLength={500} showCount placeholder='请输入内容' />
                </Form.Item>
              </div>

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

      {/* 牺牲时所在单位管理 */}
      {numShow ? (
        <A1num
          AcId={fanHaoRef.current}
          closeFu={() => setNumShow(false)}
          upNumList={() => dispatch(A1_APIgetNumList())}
        />
      ) : null}
    </div>
  )
}

const MemoA1add = React.memo(A1add)

export default MemoA1add
