import React, { useCallback, useEffect, useRef, useState } from 'react'
import styles from './index.module.scss'
import { A1ListSelectType, A1RRlistType } from '@/pages/A1record/data'
import { Button, Cascader, Form, FormInstance, Input, Select } from 'antd'
import { A3_APIgetInfo, A3_APIsave } from '@/store/action/A3clan'
import { MessageFu } from '@/utils/message'
import { myCity } from '@/utils/history'
import TextArea from 'antd/es/input/TextArea'
import ZupTypes from '@/components/ZupTypes'
import ZupVideos from '@/components/ZupVideos'
import MyPopconfirm from '@/components/MyPopconfirm'

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

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

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

  // 多个视频的ref
  const ZupVideosRef = useRef<any>(null)
  // 存一个备份key 判断一下关联烈士有没有改变
  const relationKeyRef = useRef('')

  // 判断关联烈士是否编辑的时候删除掉
  const relationIdRef = useRef(0)

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

      setNowName(obj.name)

      setRelationObj(obj.relation || {})

      if (obj.relation && obj.relation.id) {
        relationIdRef.current = obj.relation.id

        relationKeyRef.current =
          obj.relation.martyrId +
          (obj.relation.relationMartyr || '') +
          (obj.relation.relationModule || '')
      }

      // 所在城市
      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 (myMartyrId) setRelationObj({ martyrId: myMartyrId } as A1RRlistType)
  }, [getInfoFu, myMartyrId, sId])

  const formDomRef = useRef<HTMLDivElement>(null)

  // 关联烈士
  const [relationObj, setRelationObj] = useState({} as A1RRlistType)

  // 下拉框id转换成lable
  const selectNameRes = useCallback(
    (moduleId: number) => {
      let txt = ''
      const obj = listAllRes.find(v => v.value === moduleId)
      if (obj) txt = obj.label
      return txt
    },
    [listAllRes]
  )

  // 当前用户信息存起来
  const [nowName, setNowName] = useState('')

  // 没有通过校验
  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] || ''
      }

      let relation: any = null

      // 对比一下key
      if (relationObj.martyrId) {
        const newKey =
          relationObj.martyrId +
          (relationObj.relationMartyr || '') +
          (relationObj.relationModule || '')

        // if (1 + 1 === 2) {
        //   console.log(newKey, relationKeyRef.current)
        //   return
        // }
        if (newKey !== relationKeyRef.current) {
          relation = {
            id: relationObj.id ? relationObj.id : null,
            martyrId: relationObj.martyrId,
            moduleId: sId > 0 ? sId : null,
            relationMartyr: relationObj.relationMartyr,
            relationModule: relationObj.relationModule,
            type: 'kinship'
          }
        } else relation = null
      }

      let delRelationId: any = null

      if (relationIdRef.current && !relationObj.martyrId) delRelationId = relationIdRef.current

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

      const res = await A3_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, relationObj]
  )

  return (
    <div className={styles.A3add} style={{ position: myMartyrId ? 'fixed' : 'absolute' }}>
      <div className='A3addMain'>
        <div className='A3aTit'>{sId > 0 ? '编辑' : '新增'}亲属</div>

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

                <Form.Item label='联系方式' name='contact'>
                  <Input maxLength={50} showCount placeholder='请输入内容' />
                </Form.Item>
              </div>

              <div className='A3aRow'>
                <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='A3aRowAll'>
                <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='A3clan'
                    myUrl='cms/kinship/upload'
                    isTypeShow={true}
                  />
                </div>
              </div>

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

              <div className='formRow'>
                <div className='formLeft'>关联烈士：</div>
                <div className='formRight formRightBox'>
                  <div>
                    <Select
                      disabled={!!myMartyrId}
                      style={{ width: 558 }}
                      getPopupContainer={() => document.querySelector('.ant-modal-content')!}
                      filterOption={(input, option) =>
                        (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
                      }
                      allowClear
                      placeholder='请搜索并选择'
                      showSearch
                      options={listAllRes}
                      value={relationObj.martyrId || null}
                      onChange={e => setRelationObj({ ...relationObj, martyrId: e })}
                    />
                  </div>
                  <div className='A1Rrow2'>
                    <div>
                      {nowName} → {selectNameRes(relationObj.martyrId!)}
                    </div>
                    <div>
                      {selectNameRes(relationObj.martyrId!)} → {nowName}
                    </div>
                  </div>

                  <div className='A1Rrow3'>
                    <div>
                      <Input
                        placeholder='请输入'
                        maxLength={10}
                        showCount
                        value={relationObj.relationMartyr}
                        onChange={e =>
                          setRelationObj({ ...relationObj, relationMartyr: e.target.value.trim() })
                        }
                      />
                    </div>
                    <div>
                      <Input
                        placeholder='请输入'
                        maxLength={10}
                        showCount
                        value={relationObj.relationModule}
                        onChange={e =>
                          setRelationObj({ ...relationObj, relationModule: e.target.value.trim() })
                        }
                      />
                    </div>
                  </div>
                </div>
              </div>

              <div className='A3aRowAll'>
                <Form.Item label='备注' name='remark'>
                  <TextArea maxLength={500} showCount placeholder='请输入内容' />
                </Form.Item>
              </div>

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

const MemoA3add = React.memo(A3add)

export default MemoA3add
