import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import styles from './index.module.scss'
import {
  Button,
  Checkbox,
  Form,
  FormInstance,
  Input,
  InputNumber,
  Modal,
  Radio,
  Select
} from 'antd'
import TextArea from 'antd/es/input/TextArea'
import MyPopconfirm from '@/components/MyPopconfirm'
import { Z5_APIgetAddTreeList, Z5_APIgetInfo, Z5_APIsave } from '@/store/action/Z5role'
import { TypeZ5Role } from './type'
import classNmaes from 'classnames'
import { MessageFu } from '@/utils/message'
import { useDispatch, useSelector } from 'react-redux'
import { D2_APIgetList } from '@/store/action/D2storSet'
import { RootState } from '@/store'

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

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

  // 编辑进来获取详情
  const getInfoFu = useCallback(async (id: number) => {
    const res = await Z5_APIgetInfo(id)
    if (res.code === 0) {
      const data: any = res.data

      FormBoxRef.current?.setFieldsValue(data.role)
      setRoleArr(data.permission)

      setScopeGoodsFile(data.role.scopeGoodsFile)
      setScopeGoodsFileDownload(data.role.scopeGoodsFileDownload)
      setScopeStorage(data.role.scopeStorage)
      if (data.role.scopeStorageIds)
        setScopeStorageIds(data.role.scopeStorageIds.split(',').map((v: string) => Number(v)))
    }
  }, [])

  // 新增进来获取权限数据
  const [roleArr, setRoleArr] = useState<TypeZ5Role[]>([])
  const getAddInfoFu = useCallback(async () => {
    const res = await Z5_APIgetAddTreeList()
    if (res.code === 0) {
      // 新增模块 自己反转所有权限为 false

      const resArr: TypeZ5Role[] = res.data || []

      resArr.forEach(v1 => {
        if (v1.children) {
          v1.children.forEach(v2 => {
            v2.authority = false
          })
        }
      })

      setRoleArr(resArr)
    }
  }, [])

  useEffect(() => {
    if (sId > 0) {
      getInfoFu(sId)
    } else {
      FormBoxRef.current?.setFieldsValue({ sort: 999, dataScope: 2 })
      getAddInfoFu()
      setScopeGoodsFile(1)
      setScopeGoodsFileDownload(2)
      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 [scopeGoodsFile, setScopeGoodsFile] = useState(-1)
  const [scopeGoodsFileDownload, setScopeGoodsFileDownload] = useState(-1)

  // 库房权限
  const [scopeStorage, setScopeStorage] = useState(-1)
  // 指定库房数据
  const [scopeStorageIds, setScopeStorageIds] = useState<number[]>([])
  const dispatch = useDispatch()
  useEffect(() => {
    dispatch(D2_APIgetList({ pageNum: 1, pageSize: 99999 }))
  }, [dispatch])

  const { list: storSetList } = useSelector((state: RootState) => state.D2storSet.tableInfo)

  // 通过校验点击确定
  const onFinish = useCallback(
    async (values: any) => {
      if (scopeStorage === 3) {
        if (!scopeStorageIds || scopeStorageIds.length === 0)
          return MessageFu.warning('至少选中一个指定库房')
      }

      const obj = {
        ...values,
        id: sId > 0 ? sId : null,
        resources: checkIds,
        scopeGoodsFile,
        scopeGoodsFileDownload,
        scopeStorage,
        scopeStorageIds: scopeStorageIds.join(',')
      }

      const res = await Z5_APIsave(obj)

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

  return (
    <Modal
      wrapClassName={styles.Z5edit}
      open={true}
      title={sId > 0 ? '编辑' : '新增'}
      footer={
        [] // 设置footer为空，去掉 取消 确定默认按钮
      }
    >
      <div className='Z5eMain'>
        <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='Z5ebox'>
            <div className='Z5eboxll'>
              <span> * </span> 功能权限：
            </div>
            <div className='Z5eboxrr'>
              {roleArr.map(v => (
                <div key={v.id} className='Z5eRow'>
                  <div className='Z5eRow1'>{v.name}</div>
                  <div className='Z5eRow2'>
                    {v.children.map(c => (
                      <Checkbox
                        disabled={c.name === '角色管理'}
                        key={c.id}
                        checked={c.authority}
                        onChange={e => onChange(e.target.checked, v.id, c.id)}
                      >
                        {c.name}
                        {c.name === '角色管理' ? '(超级管理员才有)' : ''}
                      </Checkbox>
                    ))}
                  </div>
                </div>
              ))}

              <div className={classNmaes('Z5eErr', checkIds.length <= 0 ? 'Z5eErrAc' : '')}>
                至少选中一个
              </div>
            </div>
          </div>
          <br />
          <Form.Item
            className='Z5ebox0'
            label='数据权限'
            name='dataScope'
            rules={[{ required: true, message: '' }]}
          >
            <Radio.Group>
              <Radio value={0} className='Z5Rtit'>
                流程可见权限
              </Radio>
              <Radio value={1}>所有流程</Radio>
              <Radio value={2}>与自己相关流程（发起人、审批人、抄送人）</Radio>
            </Radio.Group>
          </Form.Item>

          <div className='Z5ebox Z5ebox1'>
            <div className='Z5eboxll'>藏品附件权限</div>
            <div className='Z5eboxrr'>
              <div>
                <Radio.Group
                  value={scopeGoodsFile}
                  onChange={e => setScopeGoodsFile(e.target.value)}
                  options={[
                    { value: 1, label: '可见' },
                    { value: 0, label: '不可见' }
                  ]}
                />
              </div>
              <div className='Z5eboxrr_1'>
                <Radio.Group
                  disabled={scopeGoodsFile === 0}
                  value={scopeGoodsFileDownload}
                  onChange={e => setScopeGoodsFileDownload(e.target.value)}
                  options={[
                    { value: 1, label: '下载原图和缩略图' },
                    { value: 2, label: '仅下载缩略图' }
                  ]}
                />
              </div>
            </div>
          </div>
          <br />
          <div className='Z5ebox Z5ebox1'>
            <div className='Z5eboxll'>库房权限</div>
            <div className='Z5eboxrr'>
              <div>
                <Radio.Group
                  value={scopeStorage}
                  onChange={e => setScopeStorage(e.target.value)}
                  options={[
                    { value: 1, label: '全部库房' },
                    { value: 2, label: '相关库房' },
                    { value: 3, label: '指定库房' }
                  ]}
                />
              </div>
              <div className='Z5eboxrr_1' hidden={scopeStorage !== 3}>
                <Select
                  showSearch={false}
                  mode='multiple'
                  allowClear
                  style={{ width: '100%' }}
                  placeholder='请选择'
                  value={scopeStorageIds}
                  onChange={value => setScopeStorageIds(value)}
                  options={storSetList}
                  fieldNames={{ value: 'id', label: 'name' }}
                />
              </div>
            </div>
          </div>

          {/* 确定和取消按钮 */}
          <br />
          <Form.Item wrapperCol={{ offset: 9, span: 16 }} className='Z5eBtn'>
            <Button type='primary' htmlType='submit' disabled={checkIds.length <= 0}>
              提交
            </Button>
            <br />
            <br />
            <MyPopconfirm txtK='取消' onConfirm={closeFu} />
          </Form.Item>
        </Form>
      </div>
    </Modal>
  )
}

const MemoZ5edit = React.memo(Z5edit)

export default MemoZ5edit
