import {
  MyButtons,
  MyPageContainer,
  MyProTableProps,
  usePageTabs,
} from '@/common';
import { flattenToMultiLevelFormatWithRowSpanAdvancedNew } from '@/common/utils/flattenIterative';
import { Apis } from '@/gen/Apis';
import { ProCard, ProTable } from '@ant-design/pro-components';
import { Checkbox, message } from 'antd';
import { useEffect, useState } from 'react';
import Create from './modals/Create';
interface SelectedBuilding {
  id: number;
  name: string;
}
export default function Index({ title = '角色' }) {
  const [selectedBuilding, setSelectedBuilding] =
    useState<SelectedBuilding | null>(null);
  const [selectedPermissionsIds, setSelectedPermissionsIds] = useState<any[]>(
    [],
  );
  const [dataSource, setDataSource] = useState<any>([]);
  // 注册当前页面为标签页
  usePageTabs({
    tabKey: 'system-roles',
    tabLabel: title,
  });

  const getSysPermissions = () => {
    Apis.Permission.SysPermissions.List({ guard_name: 'Admin' }).then((res) => {
      setDataSource(
        flattenToMultiLevelFormatWithRowSpanAdvancedNew(
          res?.data[0]?.children || [],
        ),
      );
      console.log(res, 'res');
    });
  };

  useEffect(() => {
    getSysPermissions();
  }, []);

  const onSave = () => {
    if (selectedPermissionsIds?.length && selectedBuilding?.id) {
      Apis.Permission.SysRoles.SetPermissions({
        permissions_ids: selectedPermissionsIds,
        id: selectedBuilding?.id || 0,
      }).then(() => {
        message.success('保存成功');
      });
    } else {
      message.error('请选择角色和勾选权限!');
    }
  };

  return (
    <MyPageContainer
      title={title}
      enableTabs={true}
      tabKey="system-roles"
      tabLabel={title}
    >
      <ProCard split="vertical">
        <ProCard colSpan="200px" ghost>
          <ProTable
            {...MyProTableProps.props}
            search={false}
            // headerTitle="角色"
            pagination={false}
            request={async (params, sort) =>
              MyProTableProps.request(
                params,
                sort,
                Apis.Permission.SysRoles.List,
              )
            }
            toolBarRender={(action) => [
              <Create key="Create" reload={action?.reload} title={title} />,
            ]}
            rowClassName={(record: any) => {
              return selectedBuilding?.id === record?.id
                ? 'ant-table-row-selected'
                : '';
            }}
            onRow={(record: any) => {
              return {
                onClick: () => {
                  setSelectedBuilding(record);
                  Apis.Permission.SysRoles.GetPermissions({
                    id: record?.id,
                  }).then((res) => {
                    setSelectedPermissionsIds(res?.data?.permissions_ids || []);
                  });
                },
                style: {
                  cursor: 'pointer',
                },
              };
            }}
            options={false}
            columns={[{ dataIndex: 'name', title: '名称' }]}
          />
        </ProCard>

        <ProCard>
          <Checkbox.Group
            style={{ width: '100%' }}
            value={selectedPermissionsIds}
            onChange={(e) => {
              setSelectedPermissionsIds(e);
              console.log(e, 'e');
            }}
          >
            <ProTable
              {...MyProTableProps.props}
              search={false}
              pagination={false}
              // style={{ width: '100%' }}
              style={{
                width: '100%',
                maxHeight: 'calc(100vh - 200px)', // 设置最大高度，可根据实际需求调整
                overflowY: 'auto', // 启用垂直滚动
              }}
              dataSource={dataSource}
              options={false}
              size="small"
              headerTitle="权限配置"
              toolBarRender={() => [
                <MyButtons.Default
                  key="save"
                  type="primary"
                  size="middle"
                  title="保存"
                  onClick={() => onSave()}
                />,
              ]}
              columns={[
                {
                  title: '目录',
                  dataIndex: 'name',
                  key: 'name',
                  width: '120px',
                  render: (_, item: any) => {
                    return <Checkbox value={item?.id1}>{item?.name}</Checkbox>;
                  },
                  onCell: (res, index?: number) => {
                    const rowSpan = res.row_spans?.rowSpan;
                    const firstIndex = res.row_spans?.firstIndex;
                    if (index === firstIndex && rowSpan > 0) {
                      return { rowSpan };
                    }
                    return { rowSpan: 0 };
                  },
                },
                {
                  title: '页面',
                  dataIndex: 'name2',
                  key: 'name2',
                  width: '140px',
                  render: (_, item: any) => {
                    return <Checkbox value={item?.id2}>{item?.name2}</Checkbox>;
                  },
                },
                {
                  title: '页签/按钮',
                  width: '800px',
                  render: (_, item: any) => {
                    if (item?.buttonList?.length) {
                      return item?.buttonList?.map(
                        (res: any, index: number) => {
                          return (
                            <Checkbox value={res?.id} key={`index_${index}`}>
                              {res?.name}
                            </Checkbox>
                          );
                        },
                      );
                    }
                  },
                },
              ]}
            />
          </Checkbox.Group>
        </ProCard>
      </ProCard>
    </MyPageContainer>
  );
}
