import { QuestionCircleOutlined } from '@ant-design/icons';
import { Checkbox, Collapse, Drawer, Tabs } from 'antd';
import type { CSSProperties } from 'react';
import { useEffect, useState } from 'react';
import { request, useIntl, useRequest } from 'umi';
import CustomCheckboxGroup from '../CustomCheckboxGroup';
import CustomTree from '../CustomTree';
import { leafBuildTree } from '../utils/array';
import './index.less';

const { Panel } = Collapse;

export type BindAllPermissionProps = {
  appId?: number;
  roleId: number;
  roleName: string;
  iconStyle?: CSSProperties;
};

const BindAllPermission = (props: BindAllPermissionProps) => {
  const { appId, roleId, roleName, iconStyle } = props;
  const { formatMessage } = useIntl();
  const [visible, setVisible] = useState(false);
  const [flagOptions, setFlagOptions] = useState({});
  const [onlyShowBind, setOnlyShowBind] = useState(true);

  const { data, run } = useRequest(
    () => ({
      url: `/goapi/app/rolePermission/detail`,
      method: 'POST',
      data: { appId, roleId },
    }),
    { manual: true },
  );
  const { featureIds, featureTree, flagList, optionIds, policyList } = data || {};

  useEffect(() => {
    if (visible && appId) {
      run();
    }
  }, [visible, run, appId]);

  useEffect(() => {
    if (flagList?.length > 0 && appId) {
      flagList?.map((flag: any) => {
        request('/goapi/option/tree', {
          method: 'POST',
          data: { appId, flagId: flag.id },
        }).then((res) => {
          setFlagOptions((flagmap) => {
            return { ...flagmap, [flag.id]: res.data };
          });
        });
      });
    }
  }, [flagList, appId]);

  const title = `${formatMessage({
    id: 'component.BindAllPermission.title.1',
    defaultMessage: '角色',
  })} (${roleName}) ${formatMessage({
    id: 'component.BindAllPermission.title.2',
    defaultMessage: '绑定的全部权限',
  })}`;

  const featureValue = featureIds?.map((id: any) => ({ id }));

  const treeDataFilter = (tree: any[], ids: number[]) => {
    if (!onlyShowBind) return tree;
    return leafBuildTree(ids, tree);
  };

  return (
    <>
      <Drawer
        title={title}
        width={800}
        open={visible}
        onClose={() => setVisible(false)}
        maskClosable={false}
      >
        <Tabs
          // tabBarExtraContent={
          //   <Checkbox checked={onlyShowBind} onClick={() => setOnlyShowBind(!onlyShowBind)}>
          //     {formatMessage({ id: 'component.BindAllPermission.onlyShowBind' })}
          //   </Checkbox>
          // }
        >
          {featureTree?.length > 0 && (
            <Tabs.TabPane
              tab={formatMessage({
                id: 'component.ApplyDetail.detail.features.name',
                defaultMessage: '功能权限',
              })}
              key={1}
            >
              <CustomTree
                type={'feature'}
                oldData={[]}
                isAllowApply={false}
                disabled
                value={{ data: featureValue }}
                treeData={treeDataFilter(featureTree || [], featureIds)}
                appId={appId}
              />
            </Tabs.TabPane>
          )}

          {flagList?.length > 0 && (
            <Tabs.TabPane
              tab={formatMessage({
                id: 'component.ApplyDetail.detail.flags.name',
                defaultMessage: '数据权限',
              })}
              key={2}
            >
              {flagList?.map((flag: any) => {
                const treeData = flagOptions?.[flag.id] || [];
                const value = optionIds?.map((id: any) => ({ id }));
                return (
                  <Collapse key={flag.id} defaultActiveKey={[1]}>
                    <Panel key={flag.id} header={flag.name}>
                      <CustomTree
                        type={'option'}
                        oldData={[]}
                        isAllowApply={false}
                        disabled
                        value={{ data: value }}
                        treeData={treeDataFilter(treeData, optionIds)}
                        appId={appId}
                      />
                    </Panel>
                  </Collapse>
                );
              })}
            </Tabs.TabPane>
          )}

          {policyList?.length > 0 && (
            <Tabs.TabPane
              tab={formatMessage({
                id: 'component.ApplyDetail.detail.policies.name',
                defaultMessage: '策略权限',
              })}
              key={3}
            >
              <CustomCheckboxGroup
                disabled
                options={policyList || []}
                value={{ data: policyList }}
                oldData={[]}
              />
            </Tabs.TabPane>
          )}
        </Tabs>
      </Drawer>

      <QuestionCircleOutlined
        className={'bind-all-permission-icon'}
        style={iconStyle}
        onClick={() => setVisible(true)}
      />
    </>
  );
};
export default BindAllPermission;
