import React, { useCallback, useEffect, useRef, useState } from 'react'
import styles from './index.module.scss'
import { Button, Cascader, Form, FormInstance, Input, InputNumber, Modal } from 'antd'
import MyPopconfirm from '@/components/MyPopconfirm'
import { useSelector } from 'react-redux'
import { RootState } from '@/store'
import { MessageFu } from '@/utils/message'
import { TypeZ1dict } from './type'
import { Z1_APIgetInfo, Z1_APIsave } from '@/store/action/Z1dict'

export type Z1AddInfoType = {
  id: string
  txt: '新增' | '编辑'
  acInfo: TypeZ1dict
}

type Props = {
  acShuTxt: string
  addInfo: Z1AddInfoType
  addFu: () => void
  closeFu: () => void
  isNoAcIds: string[] //没有数据或者删除了的时候-既右侧没有操作的时候用到
}

function Z1add({ addInfo, addFu, closeFu, isNoAcIds, acShuTxt }: Props) {
  const { dictList: treeData } = useSelector((state: RootState) => state.Z1dict)

  // 级联选择器改变的时候 筛选当前级联的 信息出来
  const [acCardInfo, setAcCardInfo] = useState({} as TypeZ1dict)
  const [parentIdArr, setParentIdArr] = useState<string[] | null>(null)

  // useEffect(() => {
  //   console.log(acCardInfo, parentIdArr)
  // }, [acCardInfo, parentIdArr])

  const saveIdsRef = useRef<string[]>([])

  useEffect(() => {
    setAcCardInfo(addInfo.acInfo)

    let ids: string[] | null = addInfo.acInfo.id ? [addInfo.acInfo.id] : null

    if (addInfo.acInfo.ancestor) ids = [...addInfo.acInfo.ancestor.split(','), addInfo.acInfo.id]

    let idsRes = ids
    if (ids && ids.length >= 1 && addInfo.txt === '编辑') {
      ids.pop()
    }

    if (idsRes) {
      // 保存的时候需要补前面3个级别
      saveIdsRef.current = idsRes.filter((v, i) => i <= 2)
      // 去掉0和前2级
      idsRes = idsRes.filter((v, i) => i > 2)
    }

    setParentIdArr(idsRes)
  }, [addInfo.acInfo, addInfo.txt])

  const cardChange = useCallback((aa: any, bb: any) => {
    setParentIdArr(aa)

    if (bb && bb.length) setAcCardInfo(bb[bb.length - 1])
    else setAcCardInfo({} as TypeZ1dict)
  }, [])

  const getInfoFu = useCallback(async (id: string) => {
    const res = await Z1_APIgetInfo(id)
    if (res.code === 0) {
      FormBoxRef.current?.setFieldsValue({
        ...res.data
      })
    }
  }, [])
  useEffect(() => {
    if (addInfo.txt === '编辑') getInfoFu(addInfo.id)
    else {
      FormBoxRef.current?.setFieldsValue({
        sort: 50000
      })
    }
  }, [addInfo.id, addInfo.txt, getInfoFu])

  // 设置表单初始数据（区分编辑和新增）
  const FormBoxRef = useRef<FormInstance>(null)

  // 没有通过校验
  const onFinishFailed = useCallback(() => {
    // return MessageFu.warning("有表单不符号规则!");
  }, [])

  // 通过校验点击确定
  const onFinish = useCallback(
    async (values: any) => {
      let ancestor = ''
      let parentId: string | null = null

      if (parentIdArr && parentIdArr.length >= 5 && addInfo.txt === '新增')
        return MessageFu.warning('最多支持五级!')

      if (acCardInfo) parentId = addInfo.txt === '编辑' ? acCardInfo.parentId : acCardInfo.id
      if (parentIdArr && parentId) {
        let arrTemp = [...saveIdsRef.current, ...parentIdArr.filter(v => v !== addInfo.id)]
        ancestor = arrTemp.join(',')
      }

      // 新增并且没有父级
      if (addInfo.txt === '新增' && !parentId && !ancestor) {
        // console.log('xxx', saveIdsRef.current)

        parentId = saveIdsRef.current[saveIdsRef.current.length - 1]
        ancestor = saveIdsRef.current.join(',')
        // console.log(123, parentId, ancestor)

        // 外层没有选中
        if (!addInfo.acInfo.id) {
          parentId = isNoAcIds[isNoAcIds.length - 1]
          ancestor = isNoAcIds.join(',')
        }
      }

      // let level = 1
      // if (parentIdArr) {
      //   level = addInfo.txt === '新增' ? acCardInfo.level + 1 : acCardInfo.level
      // }
      const obj = {
        ...values,
        id: addInfo.txt === '编辑' ? addInfo.id : null,
        ancestor,
        // level,
        parentId,
        type: 'dict'
      }
      // console.log(123, obj)
      // if (1 + 1 === 2) {
      //   return
      // }

      const res = await Z1_APIsave(obj)

      if (res.code === 0) {
        MessageFu.success(addInfo.txt + '成功!')
        addFu()
        closeFu()
      }
    },
    [acCardInfo, addFu, addInfo.acInfo.id, addInfo.id, addInfo.txt, closeFu, isNoAcIds, parentIdArr]
  )
  return (
    <Modal
      wrapClassName={styles.Z1add}
      open={true}
      title={addInfo.txt}
      footer={
        [] // 设置footer为空，去掉 取消 确定默认按钮
      }
    >
      <div className='Z1aMain'>
        <Form
          scrollToFirstError={true}
          ref={FormBoxRef}
          name='basic'
          labelCol={{ span: 3 }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete='off'
        >
          <div className='fromRow'>
            <div className='fromRowll'>上级字典：</div>
            <div className='fromRowrr'>
              <Cascader
                style={{ width: 658 }}
                disabled={addInfo.txt === '编辑'}
                changeOnSelect
                fieldNames={{ label: 'name', value: 'id', children: 'children' }}
                options={treeData}
                // placeholder={addInfo.txt === '编辑' ? '空' : '请选择'}
                placeholder={acShuTxt}
                value={parentIdArr ? [...parentIdArr] : []}
                onChange={cardChange}
              />
            </div>
          </div>

          <Form.Item
            label='字典值'
            name='name'
            rules={[{ required: true, message: '请输入字典值!' }]}
            getValueFromEvent={e => e.target.value.replace(/\s+/g, '')}
          >
            <Input maxLength={30} showCount placeholder='请输入内容' />
          </Form.Item>

          <div className='fromRow2'>
            <Form.Item
              label='排序值'
              name='sort'
              rules={[{ required: true, message: '请输入排序值!' }]}
            >
              <InputNumber min={1} max={50000} precision={0} placeholder='请输入' />
            </Form.Item>
            <div className='fromRowTit'>
              请输入1~50000的数字。数字越小，排序越靠前。数字相同时，更新发布的内容排在前面
            </div>
          </div>

          {/* 确定和取消按钮 */}
          <br />
          <Form.Item wrapperCol={{ offset: 9, span: 16 }}>
            <Button type='primary' htmlType='submit'>
              提交
            </Button>
            &emsp;
            <MyPopconfirm txtK='取消' onConfirm={closeFu} />
          </Form.Item>
        </Form>
      </div>
    </Modal>
  )
}

const MemoZ1add = React.memo(Z1add)

export default MemoZ1add
