import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import styles from './index.module.scss'
import { Button, Empty, Input, Modal, Select } from 'antd'
import { MessageFu } from '@/utils/message'
import MyPopconfirm from '@/components/MyPopconfirm'
import { A1RRlistType } from '../data'
import { useDispatch, useSelector } from 'react-redux'
import { A1_APIgetList, A1_APIsaveRR } from '@/store/action/A1record'
import { RootState } from '@/store'
import { DeleteOutlined } from '@ant-design/icons'
import classNames from 'classnames'

type Props = {
  sId: number
  sName: string
  closeFu: () => void
  upDataFu: () => void
  oldList: A1RRlistType[]
}

function A1relation({ sId, closeFu, upDataFu, oldList, sName }: Props) {
  // 获取所有烈士信息
  const dispatch = useDispatch()

  useEffect(() => {
    dispatch(
      A1_APIgetList({
        pageNum: 1,
        pageSize: 99999
      })
    )
  }, [dispatch])

  const listAll = useSelector((state: RootState) => state.A1record.tableInfo.list)
  const [list, setList] = useState<A1RRlistType[]>([])

  const listAllRes = useMemo(() => {
    return listAll
      .filter(v => v.id !== sId)
      .map(c => ({
        value: c.id,
        label: c.name,
        disabled: list.map(q => q.moduleId).includes(c.id)
      }))
  }, [list, listAll, sId])
  // 获取所有烈士信息-end

  // useEffect(() => {
  //   console.log('xxxxx', list)
  // }, [list])

  const [loding, setLoding] = useState(false)

  useEffect(() => {
    setList(oldList)
    setLoding(true)
  }, [oldList])

  // 点击删除
  const delArrRef = useRef<number[]>([])

  const delOneFu = useCallback(
    (item: A1RRlistType) => {
      if (!item.isNew) delArrRef.current.push(item.id)
      setList(list.filter(v => v.id !== item.id))
    },
    [list]
  )

  // 下拉框的改变
  const selectChangeFu = useCallback(
    (id: number, value: any, key: 'moduleId' | 'relationMartyr' | 'relationModule') => {
      // if (list.find(v => v.moduleId === id)) {
      //   return MessageFu.warning('不可重复选择')
      // }

      setList(
        list.map(v => ({
          ...v,
          [key]: v.id === id ? value : v[key]
        }))
      )
    },
    [list]
  )

  // 下拉框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]
  )

  // 是否可以点击确定 为true表示不满足，不能点击
  const isOkFlag = useMemo(() => {
    let index = 0
    const findIndex = list.findIndex(v => !v.moduleId || !v.relationModule || !v.relationMartyr)

    if (findIndex >= 0) index = findIndex + 1

    return index
  }, [list])

  // 点击提交
  const addBtn = useCallback(async () => {
    const obj = {
      delIds: delArrRef.current,
      relation: list.map(v => ({
        id: v.isNew ? null : v.id,
        martyrId: sId,
        moduleId: v.moduleId,
        relationMartyr: v.relationMartyr,
        relationModule: v.relationModule,
        type: 'martyr'
      }))
    }
    const res = await A1_APIsaveRR(obj)
    if (res.code === 0) {
      MessageFu.success('编辑成功')
      upDataFu()
      closeFu()
    }
  }, [closeFu, list, sId, upDataFu])

  return (
    <Modal
      wrapClassName={styles.A1relation}
      open={true}
      title={
        <div className='A1Rtit'>
          <div>关联烈士</div>
          <Button
            type='primary'
            onClick={() => {
              if (list.length >= 50) return MessageFu.warning('可关联最多50个烈士')
              setList([
                ...list,
                {
                  id: Date.now(),
                  moduleName: '',
                  moduleId: null,
                  relationMartyr: '',
                  relationModule: '',
                  isNew: true
                }
              ])
            }}
          >
            新增
          </Button>
        </div>
      }
      footer={
        [] // 设置footer为空，去掉 取消 确定默认按钮
      }
    >
      <div className='A1Rmain'>
        {list.length === 0 && loding ? (
          <div style={{ textAlign: 'center' }}>
            <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
          </div>
        ) : (
          <>
            {list.map((item, index) => (
              <div className='A1Rrow' key={item.id}>
                <div className='A1RrowIndex'>{index + 1}：</div>

                <div className='A1Rrow1'>
                  <Select
                    style={{ width: 455 }}
                    getPopupContainer={() => document.querySelector('.ant-modal-content')!}
                    filterOption={(input, option) =>
                      (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
                    }
                    allowClear
                    placeholder='请搜索并选择'
                    showSearch
                    options={listAllRes}
                    value={item.moduleId || null}
                    onChange={e => selectChangeFu(item.id, e, 'moduleId')}
                  />
                  <MyPopconfirm
                    txtK='删除'
                    onConfirm={() => delOneFu(item)}
                    Dom={<DeleteOutlined />}
                  />
                </div>
                <div className='A1Rrow2'>
                  <div>
                    {selectNameRes(item.moduleId!)} → {sName}
                  </div>
                  <div>
                    {sName} → {selectNameRes(item.moduleId!)}
                  </div>
                </div>

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

      <div className='A1Rbtn'>
        <Button type='primary' onClick={addBtn} disabled={!!isOkFlag}>
          提交
        </Button>
        &emsp;
        <MyPopconfirm txtK='取消' onConfirm={closeFu} />
        <p className={classNames(isOkFlag ? 'A1RbtnTxt' : '')}>请完善第 {isOkFlag} 条关联信息</p>
      </div>
    </Modal>
  )
}

const MemoA1relation = React.memo(A1relation)

export default MemoA1relation
