import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import styles from './index.module.scss'
import { Button, Checkbox, Form, FormInstance, Input, InputNumber, Modal, Radio } from 'antd'
import TextArea from 'antd/es/input/TextArea'
import MyPopconfirm from '@/components/MyPopconfirm'
import classNmaes from 'classnames'
import { MessageFu } from '@/utils/message'
import { I6_APIgetAddTreeList, I6_APIgetInfo, I6_APIsave } from '@/store/action/Isystem/I6role'
import { I6processChildren, TypeI6Role } from './data'
import { I1_APIwarehouseSimpleList } from '@/store/action/Isystem/I1storageSet'
import { Typetable } from '@/pages/Zother/data'

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

function I6edit({ sId, closeFu, addTableFu, editTableFu }: Props) {
  const [goodsIdArr, setGoodsIdArr] = useState<string[]>([])

  // 设置表单ref
  const FormBoxRef = useRef<FormInstance>(null)

  // 侧边栏
  const [roleArr, setRoleArr] = useState<TypeI6Role[]>([])

  // 藏品详情
  const [goodIds, setGoodIds] = useState<TypeI6Role[]>([])

  // 藏品总账
  const [zhangIds, setZhangIds] = useState<TypeI6Role[]>([])

  // 流程可见权限
  const [dataScope, setDataScope] = useState(0)

  // 藏品可见权限
  const [scopeStorage, setScopeStorage] = useState(0)
  // 与库房相关的藏品id

  const getScopeStorageList = useCallback(async () => {
    const res = await I1_APIwarehouseSimpleList({ pageNum: 1, pageSize: 99999 })
    if (res.code === 0) {
      setScopeStorageList(res.data.records || [])
    }
  }, [])

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

  // 从库房拿列表信息
  const [scopeStorageList, setScopeStorageList] = useState<Typetable[]>([])
  const [scopeStorageIds, setScopeStorageIds] = useState<Number[]>([])

  const otherIdsFu = useCallback((data: TypeI6Role[]) => {
    setGoodIds(I6processChildren(data, 330, '藏品信息'))
    setZhangIds(I6processChildren(data, 310, '藏品总账'))
  }, [])

  // 编辑进来获取详情
  const getInfoFu = useCallback(
    async (id: number) => {
      const res = await I6_APIgetInfo(id)
      if (res.code === 0) {
        const data: any = res.data
        const roleInfo = data.role
        FormBoxRef.current?.setFieldsValue(roleInfo)
        // 设置多选框
        setRoleArr(data.permission)
        otherIdsFu(data.permission)

        // 设置其他单选框
        setDataScope(roleInfo.dataScope || 1)

        setScopeStorage(roleInfo.scopeStorage || 1)
        if (roleInfo.scopeStorageIds)
          setScopeStorageIds(roleInfo.scopeStorageIds.split(',').map((v: string) => Number(v)))

        // 后面加的藏品权限
        if (roleInfo.scopeGoods) {
          setGoodsIdArr(roleInfo.scopeGoods.split(','))
        }
      }
    },
    [otherIdsFu]
  )

  // 新增进来获取权限数据
  const getAddInfoFu = useCallback(async () => {
    const res = await I6_APIgetAddTreeList()
    if (res.code === 0) {
      const resArr: TypeI6Role[] = res.data || []
      setRoleArr(resArr)
      otherIdsFu(resArr)
    }
  }, [otherIdsFu])

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

      setDataScope(1)

      getAddInfoFu()
      setScopeStorage(1)
    }
  }, [getAddInfoFu, getInfoFu, sId])

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

  // 侧边栏选中id集合
  const checkIds = useMemo(() => {
    const arr: number[] = []
    roleArr.forEach(v => {
      v.children.forEach(c => {
        if (c.authority) arr.push(c.id)
      })
    })
    // 过滤角色
    return arr
  }, [roleArr])

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

  // 通过校验点击确定
  const onFinish = useCallback(
    async (values: any) => {
      if (checkIds.length <= 0) MessageFu.warning('至少选中一个侧边栏')

      if (scopeStorage === 2) {
        if (!scopeStorageIds || scopeStorageIds.length === 0)
          return MessageFu.warning('藏品可见权限-至少选中一个库房')
      }

      const goodIdsRes = goodIds.filter(v => v.authority).map(c => c.id)
      const zhangIdsRes = zhangIds.filter(v => v.authority).map(c => c.id)

      const obj = {
        ...values,
        id: sId > 0 ? sId : null,
        resources: [...checkIds, ...goodIdsRes, ...zhangIdsRes],
        scopeStorage,
        scopeStorageIds: scopeStorageIds.join(','),
        scopeGoods: goodsIdArr.join(','),
        dataScope
      }

      const res = await I6_APIsave(obj)

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

  return (
    <Modal
      wrapClassName={styles.I6edit}
      open={true}
      title={sId > 0 ? '编辑' : '新增'}
      footer={
        [] // 设置footer为空，去掉 取消 确定默认按钮
      }
    >
      <div className='I6eMain'>
        <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='I6ebox'>
            <div className='I6eboxll'>功能权限：</div>
            <div className='I6eboxrr'>
              <div className='I6eboxrrBox'>
                <div className='I6eboxrrTit'>侧边栏</div>
                {roleArr.map(v => (
                  <div key={v.id} className='I6eRow'>
                    <div className='I6eRow1'>
                      <Checkbox
                        checked={v.children.every(c => c.authority)}
                        indeterminate={
                          v.children.some(b => b.authority) && !v.children.every(c => c.authority)
                        }
                        onChange={e => {
                          const flag = v.children.every(c => c.authority)

                          setRoleArr(
                            roleArr.map(p => ({
                              ...p,
                              children:
                                v.id === p.id
                                  ? v.children.map(a => ({ ...a, authority: !flag }))
                                  : p.children
                            }))
                          )
                        }}
                      >
                        {v.name}：
                      </Checkbox>
                    </div>
                    <div className='I6eRow2'>
                      {v.children.map(c => (
                        <Checkbox
                          style={{ display: c.name === '角色管理' ? 'none' : 'inline-flex' }}
                          key={c.id}
                          checked={c.authority}
                          onChange={e => onChange(e.target.checked, v.id, c.id)}
                        >
                          {c.name}
                        </Checkbox>
                      ))}
                    </div>
                  </div>
                ))}
                <div className={classNmaes('I6eErr', checkIds.length <= 0 ? 'I6eErrAc' : '')}>
                  至少选中一个
                </div>
              </div>

              <div className='I6eboxrrBox I6eboxrrBox2'>
                <div className='I6eboxrrTit'>藏品详情</div>

                {goodIds.map(v => (
                  <Checkbox
                    key={v.id}
                    checked={v.authority}
                    onChange={e =>
                      setGoodIds(
                        goodIds.map(c => ({
                          ...c,
                          authority: c.id === v.id ? e.target.checked : c.authority
                        }))
                      )
                    }
                  >
                    {v.name}
                  </Checkbox>
                ))}
              </div>

              <div className='I6eboxrrBox I6eboxrrBox2'>
                <div className='I6eboxrrTit'>藏品总账</div>

                {zhangIds.map(v => (
                  <Checkbox
                    key={v.id}
                    checked={v.authority}
                    onChange={e =>
                      setZhangIds(
                        zhangIds.map(c => ({
                          ...c,
                          authority: c.id === v.id ? e.target.checked : c.authority
                        }))
                      )
                    }
                  >
                    {v.name}
                  </Checkbox>
                ))}
              </div>
            </div>
          </div>

          <br />

          <div className='I6ebox'>
            <div className='I6eboxll'>数据权限：</div>
            <div className='I6eboxrr'>
              <div className='I6eboxrrBox I6eboxrrBox2'>
                <div className='I6eboxrrTit'>流程可见权限</div>
                <Radio.Group value={dataScope} onChange={e => setDataScope(e.target.value)}>
                  <Radio value={1}>所有流程</Radio>
                  <Radio value={2}>与自己相关流程（发起人、审批人、抄送人）</Radio>
                </Radio.Group>
              </div>

              <div className='I6eboxrrBox I6eboxrrBox2'>
                <div className='I6eboxrrTit'>藏品可见权限</div>
                <Radio.Group
                  value={scopeStorage}
                  onChange={e => {
                    if (
                      e.target.value === 2 &&
                      (!scopeStorageList || scopeStorageList.length === 0)
                    )
                      return MessageFu.warning('暂无库房信息，请先去库房设置中添加')
                    setScopeStorage(e.target.value)
                  }}
                  options={[
                    { value: 1, label: '所有藏品' },
                    { value: 2, label: '仅与库房相关的藏品' }
                  ]}
                />
                {scopeStorage === 2 && (
                  <div className='I6eboxrrBoxKuFang'>
                    {scopeStorageList.map(v => (
                      <Checkbox
                        key={v.id}
                        checked={scopeStorageIds.includes(v.id)}
                        onChange={e => {
                          if (scopeStorageIds.includes(v.id)) {
                            setScopeStorageIds(scopeStorageIds.filter(id => id !== v.id))
                          } else {
                            setScopeStorageIds([...scopeStorageIds, v.id])
                          }
                        }}
                      >
                        {v.name}
                      </Checkbox>
                    ))}
                  </div>
                )}
              </div>
            </div>
          </div>

          {/* 确定和取消按钮 */}
          <br />
          <Form.Item className='I6eBtn'>
            <Button type='primary' htmlType='submit'>
              提交
            </Button>
            &emsp;
            <MyPopconfirm txtK='取消' onConfirm={closeFu} />
          </Form.Item>
        </Form>
      </div>
    </Modal>
  )
}

const MemoI6edit = React.memo(I6edit)

export default MemoI6edit
