import React, { useCallback, useEffect, useState } from 'react'
import styles from './index.module.scss'
import { Button, Input, InputNumber, Modal, Radio, Select } from 'antd'
import MyPopconfirm from '@/components/MyPopconfirm'
import { useDispatch, useSelector } from 'react-redux'
import { RootState } from '@/store'
import { MessageFu } from '@/utils/message'
import { I4proListType } from '../data'
import { UserTableListType } from '../../I7user/data'
import { I4_APIgetProInfo, I4_APIgetProSave } from '@/store/action/Isystem/I4processSet'
import { I6_APIgetList } from '@/store/action/Isystem/I6role'

const baseFormData = {
  id: -1,
  name: '',
  type: '',
  sort: 999
} as I4proListType

type Props = {
  sId: number
  closeFu: () => void
  succFu: () => void
  userList: UserTableListType[]
  flowId: number
}

function I4addPro({ sId, closeFu, succFu, userList, flowId }: Props) {
  const dispatch = useDispatch()
  // 获取角色列表
  const { list: roleList } = useSelector((state: RootState) => state.I6role.tableInfo)

  const [form, setForm] = useState(baseFormData)

  const getInfoFu = useCallback(async (id: number) => {
    const res = await I4_APIgetProInfo(id)
    if (res.code === 0) {
      const data: I4proListType = res.data

      let moduleIds: any = data.moduleIds.split(',')

      data.type === 'user'
        ? setIdsArr1(moduleIds.map((v: any) => Number(v)))
        : setIdsArr2(moduleIds.map((v: any) => Number(v)))

      setForm(data)
    }
  }, [])

  useEffect(() => {
    dispatch(I6_APIgetList({ pageNum: 1, pageSize: 99999 }))

    if (sId > 0) getInfoFu(sId)
    else {
      setForm({ ...baseFormData, type: 'user' })
    }
  }, [dispatch, getInfoFu, sId])

  const formChange = useCallback(
    (key: 'name' | 'type' | 'sort', val: any) => {
      setForm({
        ...form,
        [key]: val
      })
    },
    [form]
  )

  const [idsArr1, setIdsArr1] = useState<string[]>([])
  const [idsArr2, setIdsArr2] = useState<string[]>([])

  // 点击提交
  const btnOk = useCallback(async () => {
    if (!form.name) return MessageFu.warning('请输入节点名称')
    if (!form.sort) return MessageFu.warning('请输入正整数排序值')

    const id1 = (idsArr1 || []).join(',')

    if (form.type === 'user' && !id1) return MessageFu.warning('请选择指定用户')

    const id2 = (idsArr2 || []).join(',')

    if (form.type === 'role' && !id2) return MessageFu.warning('请选择角色')

    const obj = {
      ...form,
      moduleIds: form.type === 'user' ? id1 : id2,
      id: sId > 0 ? sId : null,
      flowId
    }

    const res = await I4_APIgetProSave(obj)

    if (res.code === 0) {
      MessageFu.success(sId > 0 ? '编辑成功' : '新增成功')
      succFu()
      closeFu()
    }
  }, [closeFu, flowId, form, idsArr1, idsArr2, sId, succFu])

  return (
    <Modal
      wrapClassName={styles.I4addPro}
      destroyOnClose
      open={true}
      title={sId > 0 ? '编辑' : '新增'}
      footer={
        [] // 设置footer为空，去掉 取消 确定默认按钮
      }
    >
      <div className='I4aRow'>
        <div className='I4aRowll'>
          <span> * </span> 节点名称：
        </div>
        <div className='I4aRowrr'>
          <Input
            placeholder='请输入内容'
            maxLength={10}
            showCount
            value={form.name}
            onChange={e => formChange('name', e.target.value.trim())}
          />
        </div>
      </div>

      <div className='I4aRow'>
        <div className='I4aRowll'>
          <span> * </span> 办理人：
        </div>
        <div className='I4aRowrr'>
          <Radio.Group
            value={form.type}
            onChange={e => formChange('type', e.target.value)}
            options={[
              { value: 'user', label: '指定用户' },
              { value: 'role', label: '按角色' }
            ]}
          />
        </div>
      </div>

      <div className='I4aRow'>
        <div className='I4aRowll'></div>

        <div className='I4aRowrr' hidden={form.type !== 'user'}>
          <Select
            showSearch={false}
            mode='multiple'
            allowClear
            style={{ width: '100%' }}
            placeholder='请选择'
            value={idsArr1}
            onChange={value => setIdsArr1(value)}
            options={userList}
            fieldNames={{ value: 'id', label: 'realName' }}
          />
        </div>
        <div className='I4aRowrr' hidden={form.type !== 'role'}>
          <Select
            showSearch={false}
            mode='multiple'
            allowClear
            style={{ width: '100%' }}
            placeholder='请选择'
            value={idsArr2}
            onChange={value => setIdsArr2(value)}
            options={roleList}
            fieldNames={{ value: 'id', label: 'roleName' }}
          />
        </div>
      </div>

      <div className='I4aRow'>
        <div className='I4aRowll'>
          <span> * </span> 排序值：
        </div>
        <div className='I4aRowrr'>
          <InputNumber
            min={1}
            max={999}
            precision={0}
            placeholder='请输入'
            value={form.sort}
            onChange={e => formChange('sort', e)}
          />
          <div className='fromRowTit'>
            请输入1~999的数字。数字越小，排序越靠前。数字相同时，更新发布的内容排在前面
          </div>
        </div>
      </div>

      <div className='I4aBtn'>
        <Button type='primary' onClick={btnOk}>
          提交
        </Button>
        &emsp;
        <MyPopconfirm txtK='取消' onConfirm={closeFu} />
      </div>
    </Modal>
  )
}

const MemoI4addPro = React.memo(I4addPro)

export default MemoI4addPro
