import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import styles from './index.module.scss'
import { Button, Checkbox, Form, FormInstance, Input, InputNumber, Modal } from 'antd'
import { D3_APIgetAddTreeList, D3_APIgetInfo, D3_APIsave } from '@/store/action/D3role'
import { MessageFu } from '@/utils/message'
import { TypeD3Role } from '../data'
import classNmaes from 'classnames'
import MyPopconfirm from '@/components/MyPopconfirm'
import TextArea from 'antd/es/input/TextArea'

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

function D3add({ sId, closeFu, addTableFu, editTableFu }: Props) {
  // 设置表单ref
  const FormBoxRef = useRef<FormInstance>(null)

  const [loding, setLoding] = useState(false)

  // 编辑进来获取详情
  const getInfoFu = useCallback(async (id: number) => {
    const res = await D3_APIgetInfo(id)
    if (res.code === 0) {
      FormBoxRef.current?.setFieldsValue(res.data.role)
      setRoleArr(res.data.permission)
      setLoding(true)
    }
  }, [])

  // 新增的默认数据
  const [roleArr, setRoleArr] = useState<TypeD3Role[]>([])

  const getAddInfoFu = useCallback(async () => {
    const res = await D3_APIgetAddTreeList()
    if (res.code === 0) {
      setRoleArr(res.data || [])
      setLoding(true)
    }
  }, [])

  useEffect(() => {
    if (sId > 0) getInfoFu(sId)
    else {
      FormBoxRef.current?.setFieldsValue({ sort: 999 })
      getAddInfoFu()
    }
  }, [getAddInfoFu, getInfoFu, sId])

  // 多选框变化
  const onChange = useCallback(
    (val: boolean, id: number) => {
      setRoleArr(
        roleArr.map(v => ({
          ...v,
          authority: v.id === id ? val : v.authority
        }))
      )
    },
    [roleArr]
  )

  // 二级选中的数组id集合
  const checkIds = useMemo(() => {
    const arr: number[] = []
    roleArr.forEach(v => {
      if (v.authority) arr.push(v.id)
    })
    return arr
  }, [roleArr])

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

  // 通过校验点击确定
  const onFinish = useCallback(
    async (values: any) => {
      const obj = {
        ...values,
        id: sId > 0 ? sId : null,
        resources: checkIds
      }

      const res = await D3_APIsave(obj)

      if (res.code === 0) {
        MessageFu.success(sId > 0 ? '编辑成功' : '新增成功')
        sId > 0 ? editTableFu() : addTableFu()
        closeFu()
      }
    },
    [addTableFu, checkIds, closeFu, editTableFu, sId]
  )

  return (
    <Modal
      wrapClassName={styles.D3add}
      open={true}
      title={sId > 0 ? '编辑' : '新增'}
      footer={
        [] // 设置footer为空，去掉 取消 确定默认按钮
      }
    >
      <div className='D3aMain'>
        <Form
          scrollToFirstError={true}
          ref={FormBoxRef}
          name='basic'
          labelCol={{ span: 3 }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete='off'
        >
          <Form.Item
            label='角色名称'
            name='roleName'
            rules={[{ required: true, message: '请输入角色名称' }]}
          >
            <Input maxLength={10} showCount placeholder='请输入内容' />
          </Form.Item>

          <Form.Item label='角色说明' name='roleDesc'>
            <TextArea maxLength={100} 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>

          <div className='D3abox'>
            <div className='D3aboxll'>
              <span> * </span> 功能权限：
            </div>
            <div className='D3aboxrr'>
              {roleArr.map(v => (
                <div key={v.id} className='D3aRow'>
                  <Checkbox
                    key={v.id}
                    checked={v.authority}
                    onChange={e => {
                      onChange(e.target.checked, v.id)
                    }}
                  >
                    {v.name}
                  </Checkbox>
                </div>
              ))}

              <div
                className={classNmaes('D3aErr', checkIds.length <= 0 && loding ? 'D3aErrAc' : '')}
              >
                至少选中一个
              </div>
            </div>
          </div>
          {/* 确定和取消按钮 */}
          <br />
          <Form.Item wrapperCol={{ offset: 11, span: 16 }}>
            <Button type='primary' htmlType='submit' disabled={checkIds.length <= 0}>
              提交
            </Button>
            &emsp;
            <MyPopconfirm txtK='取消' onConfirm={closeFu} />
          </Form.Item>
        </Form>
      </div>
    </Modal>
  )
}

const MemoD3add = React.memo(D3add)

export default MemoD3add
