import {forwardRef, memo, useCallback, useEffect, useMemo, useRef} from "react";
import {ModalConfigPanel} from "../../ModalManage/components/ModalConfigPanel";
import {Button, Modal, Tag} from "antd";
import {columnsFactory, optionFactory} from "../../../../utils/columnsFactory";
import {useAppDispatch, useAppSelector} from "../../../../redux/configureStore";
import {selectRoleAuth, selectRoles} from "../../MainPage/slice/selectors";
import {getAuthList, getRoles} from "../../MainPage/slice/thunks";
import {AUTH_TYPE, TYPE_ENUM_CN} from "../../../constants";
import useI18NPrefix from "../../../hooks/useI18NPrefix";

const component = forwardRef(({
  type,
  open,
  values,
  onCancel,
  onFinish,
  onDelete
},ref)=>{
  const t = useI18NPrefix('global');
  /** 初始渲染的钩子 */
  useEffect(()=>{
    if (open){
      // 获取角色基础数据
      dispatch(getRoles({}))
      // 打开时加载授权列表
      dispatch(getAuthList({
        params:{
          dataId:values?.id,
          dataType:type
        }
      }))
    }
  },[open])

  const dispatch = useAppDispatch();
  /** 操作钩子 */
  const actionRef = useRef(null);
  /** 角色数据 */
  const roleList = useAppSelector(selectRoles);
  /** 授权列表 */
  const roleAuthList = useAppSelector(selectRoleAuth);
  /** 表头 */
  const configColumns = useMemo(()=>
    columnsFactory({
      dataSource: [
        {
          title: t("columns.role"),
          dataIndex: 'roleId',
          valueType:'select',
          fieldProps: {
            allowClear:false,
            options: optionFactory(roleList)
          },
        },
        {
          title: t("columns.allowCreateVersion"),
          dataIndex: 'allowAdd',
          valueType: 'switch',
          render: (text,row) => <Tag color={row.allowAdd?"success":"error"}>{text}</Tag>,
        },
        {
          title: t("columns.allowDetail"),
          dataIndex: 'allowDetail',
          valueType: 'switch',
          render: (text,row) => <Tag color={row.allowDetail?"success":"error"}>{text}</Tag>,
        },
        {
          title: t("columns.allowPublish"),
          dataIndex: 'allowPublish',
          valueType: 'switch',
          render: (text,row) => <Tag color={row.allowPublish?"success":"error"}>{text}</Tag>,
        },
      ],
      onEditRow:true,
      onDelete,
    })
    ,[roleList]
  )

  const formatAuthList = useMemo(()=>
    roleAuthList.map(item=> {
      const random = Math.random()
      return {
        id: random,//`${item.dataType}^${item.roleId}^${item.dataId}`,
        key: random,//`${item.dataType}^${item.roleId}^${item.dataId}`,
        ...item,
        allowAdd:item.authType.includes(AUTH_TYPE.ADMIN),
        allowDetail:item.authType.includes(AUTH_TYPE.VISIBLE),
        allowPublish:item.authType.includes(AUTH_TYPE.PUBLISH)
      }
    })
    ,[roleAuthList]
  )

  // 保存行数据
  const onSave = useCallback((rowKey, params, row) => {
    const newObj = JSON.stringify(params);
    const oldObj = JSON.stringify(row);
    if (newObj !== oldObj) {
      let authType = [];
      if (params.allowAdd){
        authType = authType.concat(AUTH_TYPE.ADMIN)
      }
      if (params.allowDetail){
        authType = authType.concat(AUTH_TYPE.VISIBLE)
      }
      if (params.allowPublish){
        authType = authType.concat(AUTH_TYPE.PUBLISH)
      }
      onFinish && onFinish({
        roleId:params.roleId,
        dataId:values?.id || null,
        dataType:type,
        authType
      })
    }
  },[values])

  return (
    <Modal
      width={1200}
      title={`${t("title.authConfig")}(${TYPE_ENUM_CN[type]}-${values.name})`}
      open={open}
      footer={null}
      maskClosable={false}
      destroyOnClose
      onCancel={onCancel}
    >
      <ModalConfigPanel
        ref={ref}
        rowKey="key"
        actionRef={actionRef}
        values={formatAuthList}
        columns={configColumns}
        editable={{
          type: 'multiple',
          onSave,
        }}
        toolBarRender={()=>[
          <Button
            type='primary'
            onClick={() => {
              actionRef.current?.addEditRecord?.(
                {key: (Math.random() * 1000000).toFixed(0)},
                {position: "top"}
              )
            }}
          >
            + {t("button.create")}
          </Button>
        ]}
      />
    </Modal>
  )
})

export const AuthorizationPanel = memo(component)