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 TextArea from 'antd/es/input/TextArea'
import { I5AddInfoType, TypeI5Tree } from '@/pages/Isystem/I5organization/data'
import { E1_APIgetInfo, E1_APIsave } from '@/store/action/Eculture/E1tag'

type Props = {
  addInfo: I5AddInfoType
  addFu: () => void
  closeFu: () => void
}

function E1add({ addInfo, addFu, closeFu }: Props) {
  const treeData = useSelector((state: RootState) => state.E1tag.treeData)

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

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

  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) idsRes = idsRes.filter((v, i) => v !== '0')

    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 TypeI5Tree)
  }, [])

  const getInfoFu = useCallback(async (id: string) => {
    const res = await E1_APIgetInfo(id)
    if (res.code === 0) {
      FormBoxRef.current?.setFieldsValue({
        ...res.data
      })
    }
  }, [])
  useEffect(() => {
    if (addInfo.txt === '编辑') getInfoFu(addInfo.id)
    else {
      FormBoxRef.current?.setFieldsValue({
        sort: 999
      })
    }
  }, [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 >= 6 && addInfo.txt === '新增')
        return MessageFu.warning('最多支持六级!')

      if (acCardInfo) parentId = addInfo.txt === '编辑' ? acCardInfo.parentId : acCardInfo.id
      if (parentIdArr && parentId) ancestor = parentIdArr.filter(v => v !== addInfo.id).join(',')

      let level = 1
      if (parentIdArr) {
        level = addInfo.txt === '新增' ? acCardInfo.level + 1 : acCardInfo.level
      }

      // 补0
      if (addInfo.id === '-1') {
        // 新增
        if (!parentId && !ancestor) {
          ancestor = '0'
          parentId = '0'
        } else ancestor = '0,' + ancestor
      } else {
        // 编辑
        if (!ancestor) ancestor = '0'
        else ancestor = '0,' + ancestor
      }

      const obj = {
        ...values,
        id: addInfo.id === '-1' ? null : addInfo.id,
        ancestor,
        level,
        parentId
      }
      // console.log(123, obj)
      // if (1 + 1 === 2) {
      //   return
      // }

      const res = await E1_APIsave(obj)

      if (res.code === 0) {
        MessageFu.success(addInfo.txt + '成功!')
        addFu()
        closeFu()
      }
    },
    [acCardInfo, addFu, addInfo.id, addInfo.txt, closeFu, parentIdArr]
  )

  return (
    <Modal
      wrapClassName={styles.E1add}
      open={true}
      title={addInfo.txt}
      footer={
        [] // 设置footer为空，去掉 取消 确定默认按钮
      }
    >
      <div className='E1aMain'>
        <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 === '编辑' ? '空' : '请选择'}
                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={20} showCount placeholder='请输入内容' />
          </Form.Item>

          <Form.Item label='标签说明' name='intro'>
            <TextArea maxLength={500} showCount placeholder='请输入内容' />
          </Form.Item>

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

export default MemoE1add
