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

export type UserListType = {
  id: number
  name: string
  perm: boolean
}

type Props = {
  authInfo: { id: number; name: string }
  closeFu: () => void
}

function Z1auth({ authInfo, closeFu }: Props) {
  const getAuthByUserIdFu = useCallback(async () => {
    const res = await Z1_APIgetAuthByUserId(authInfo.id)
    if (res.code === 0) {
      const info = res.data
      setResources(info.resources)
      setDataScopeIds(info.scope)
      setDataScope(info.dataScope || 1)
    }
  }, [authInfo.id])

  useEffect(() => {
    getAuthByUserIdFu()
  }, [getAuthByUserIdFu])

  // 页面权限
  const [resources, setResources] = useState<UserListType[]>([])

  // 选择古桥或者全部
  const [dataScope, setDataScope] = useState(0)

  // 古桥权限
  const [dataScopeIds, setDataScopeIds] = useState<UserListType[]>([])

  // 多选框变化
  const onChange1 = useCallback(
    (val: boolean, id: number) => {
      setResources(
        resources.map(v => ({
          ...v,
          perm: v.id === id ? val : v.perm
        }))
      )
    },
    [resources]
  )
  const onChange2 = useCallback(
    (val: boolean, id: number) => {
      setDataScopeIds(
        dataScopeIds.map(v => ({
          ...v,
          perm: v.id === id ? val : v.perm
        }))
      )
    },
    [dataScopeIds]
  )

  //  页面权限id集合
  const ids1 = useMemo(() => {
    return resources.filter(v => v.perm).map(c => c.id)
  }, [resources])

  // 古桥权限id集合
  const ids2 = useMemo(() => {
    return dataScopeIds.filter(v => v.perm).map(c => c.id)
  }, [dataScopeIds])

  // 点击确定
  const btnOkFu = useCallback(async () => {
    const obj = {
      userId: authInfo.id,
      resources: ids1,
      dataScopeIds: ids2,
      dataScope
    }

    const res = await Z1_APIsetAuth(obj)

    if (res.code === 0) {
      MessageFu.success('授权成功!')
      closeFu()
    }
  }, [authInfo.id, closeFu, dataScope, ids1, ids2])

  // 按钮是否能点击
  const btnFlag = useMemo(() => {
    let txt = ''
    if (ids1.length === 0) txt = '至少选中一个页面权限'
    else if (dataScope === 2 && ids2.length === 0) txt = '至少选中一个数据权限'
    return txt
  }, [dataScope, ids1.length, ids2.length])

  return (
    <Modal
      wrapClassName={styles.Z1auth}
      open={true}
      title={`${authInfo.name} - 权限管理`}
      footer={
        [] // 设置footer为空，去掉 取消 确定默认按钮
      }
    >
      <div className='Z1aEmain'>
        <div className='Z1aRow'>
          <div className='Z1aRowll'>页面权限：</div>
          <div className='Z1aRowrr'>
            {resources.map(c => (
              <Checkbox
                key={c.id}
                checked={c.perm}
                onChange={e => onChange1(e.target.checked, c.id)}
              >
                {c.name}
              </Checkbox>
            ))}
          </div>
        </div>

        <div className='Z1aRow'>
          <div className='Z1aRowll'>数据权限：</div>
          <div className='Z1aRowrr'>
            <Radio.Group
              value={dataScope}
              onChange={e => setDataScope(e.target.value)}
              options={[
                { value: 1, label: '全部' },
                { value: 2, label: '按古桥' }
              ]}
            />
          </div>
        </div>

        <div className='Z1aRow' hidden={dataScope !== 2}>
          <div className='Z1aRowll'>
            <Checkbox
              indeterminate={ids2.length > 0 && ids2.length < dataScopeIds.length}
              onChange={e => {
                const perm = e.target.checked
                setDataScopeIds(
                  dataScopeIds.map(v => ({
                    ...v,
                    perm
                  }))
                )
              }}
              checked={ids2.length === dataScopeIds.length}
            >
              {ids2.length === dataScopeIds.length ? '反' : '全'}选
            </Checkbox>
          </div>
          <div className='Z1aRowrr Z1aRowrr2'>
            {dataScopeIds.map(c => (
              <Checkbox
                key={c.id}
                checked={c.perm}
                onChange={e => onChange2(e.target.checked, c.id)}
              >
                {c.name}
              </Checkbox>
            ))}
          </div>
        </div>

        <div className={classNmaes('Z1aErr', btnFlag ? 'Z1aErrAc' : '')}>{btnFlag}</div>
      </div>

      <div className='Z1aEbtn'>
        <Button type='primary' onClick={btnOkFu} disabled={!!btnFlag}>
          提交
        </Button>
        &emsp;
        <MyPopconfirm txtK='取消' onConfirm={closeFu} />
      </div>
    </Modal>
  )
}

const MemoZ1auth = React.memo(Z1auth)

export default MemoZ1auth
