import React, { useCallback, useEffect, useMemo, useState } from 'react'
import styles from './index.module.scss'
import { Button, Checkbox, Modal } from 'antd'
import MyPopconfirm from '@/components/MyPopconfirm'
import classNmaes from 'classnames'
import { MessageFu } from '@/utils/message'
import { RouterTypeRow } from '@/types'
import { A1_APIsetStock } from '@/store/action/A1workbench'

type Props = {
  sId: number
  arr: RouterTypeRow[]
  closeFu: () => void
  succFu: () => void
}

function A1setStock({ arr, closeFu, succFu, sId }: Props) {
  const [roleArr, setRoleArr] = useState<RouterTypeRow[]>([])

  useEffect(() => {
    setRoleArr(arr)
  }, [arr])

  // 多选框变化
  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 && v.name !== '工作台') arr.push(v.id)
    })
    return arr
  }, [roleArr])

  // 点击提交
  const btnOk = useCallback(async () => {
    const res = await A1_APIsetStock(sId, JSON.stringify(roleArr))
    if (res.code === 0) {
      MessageFu.success('设置成功')
      succFu()
      closeFu()
    }
  }, [closeFu, roleArr, sId, succFu])

  return (
    <Modal
      wrapClassName={styles.A1setStock}
      open={true}
      title='常用功能'
      footer={
        [] // 设置footer为空，去掉 取消 确定默认按钮
      }
    >
      <div className='A1Smain'>
        <div className='Z5eboxrr'>
          {roleArr.map(v => (
            <div className='Z5eRow2' key={v.id}>
              {v.name === '工作台' ? null : (
                <Checkbox checked={v.authority} onChange={e => onChange(e.target.checked, v.id)}>
                  {v.name}
                </Checkbox>
              )}
            </div>
          ))}

          <div className={classNmaes('Z5eErr', checkIds.length <= 0 ? 'Z5eErrAc' : '')}>
            至少选中一个
          </div>
        </div>

        <div className='A1Sbtn'>
          <Button type='primary' disabled={checkIds.length <= 0} onClick={btnOk}>
            提交
          </Button>
          &emsp;
          <MyPopconfirm txtK='取消' onConfirm={closeFu} />
        </div>
      </div>
    </Modal>
  )
}

const MemoA1setStock = React.memo(A1setStock)

export default MemoA1setStock
