import { MyButtons, MyPageContainer, MyProTableProps } from '@/common';
import { flattenToMultiLevelFormatWithRowSpanAdvancedNew } from '@/common/utils/flattenIterative';
import { Apis } from '@/gen/Apis';
import { ProCard, ProTable } from '@ant-design/pro-components';
import { Checkbox, message, Space, Tabs } 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>([]);
  const [dataTabsSource, setDataTabsSource] = useState<any>([]);
  const [tabsKey, setTabsKey] = useState<any>('');
  const getSysPermissions = () => {
    Apis.Permission.SysPermissions.List({ guard_name: 'Admin' }).then((res) => {
      setDataSource(
        flattenToMultiLevelFormatWithRowSpanAdvancedNew(
          res?.data[0]?.children || [],
        ),
      );
      console.log(res, 'res');
    });
  };

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

  const getPermissions = (id: any) => {
    setTabsKey(id);
    // 更新选中的角色信息
    const selectedRole = dataTabsSource.find((item: any) => item.id === id);
    if (selectedRole) {
      setSelectedBuilding({
        id: selectedRole.id,
        name: selectedRole.name,
      });
    }
    Apis.Permission.SysRoles.GetPermissions({
      id: id ?? 0,
    }).then((res) => {
      setSelectedPermissionsIds(res?.data?.permissions_ids || []);
    });
  };

  const getSysRoles = () => {
    Apis.Permission.SysRoles.List().then((res) => {
      setDataTabsSource(res?.data || []);
      if (res?.data?.length) {
        const firstRole = res.data[0];
        getPermissions(firstRole?.id || 0);
        // 初始化选中第一个角色
        setSelectedBuilding({
          id: firstRole.id,
          name: firstRole.name,
        });
      }
      console.log(res, 'res');
    });
  };

  const onSelect = () => {
    //删除角色
    Apis.Permission.SysRoles.Delete({
      id: tabsKey,
    }).then(() => {
      getSysRoles();
      message.success('删除成功');
    });
  };
  useEffect(() => {
    getSysRoles();
    getSysPermissions();
  }, []);
  return (
    <MyPageContainer
      title={title}
      enableTabs={true}
      tabKey="system-roles"
      tabLabel={title}
    >
      <ProCard
        title="权限配置"
        style={{ width: '100%' }}
        headerBordered
        extra={
          <Space size="large">
            <Space size="small">
              <Create key="Create" reload={() => getSysRoles()} title={title} />
              <MyButtons.Default
                key="delete"
                size="middle"
                color="danger"
                variant="solid"
                isConfirm
                description="是否确定删除当前角色?"
                title="删除当前角色"
                onConfirm={() => onSelect()}
                // 如果当前选中角色是管理员，则禁用删除按钮
                disabled={selectedBuilding?.name === '管理员'}
              />
            </Space>
            <MyButtons.Default
              key="save"
              type="primary"
              size="middle"
              title="保存权限"
              onClick={() => onSave()}
            />
          </Space>
        }
      >
        <div style={{ display: 'flex' }}>
          <div style={{ width: '130px' }}>
            <Tabs
              tabPosition="left"
              items={dataTabsSource.map((item: any) => ({
                label: item?.name,
                key: item?.id,
              }))}
              onChange={(key: any) => {
                getPermissions(key);
                console.log(key, 'key');
              }}
            />
          </div>

          <div style={{ flex: 1 }}>
            <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 - 280px)', // 设置最大高度，可根据实际需求调整
                  overflowY: 'auto', // 启用垂直滚动
                }}
                dataSource={dataSource}
                options={false}
                size="small"
                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: '160px',
                    render: (_, item: any) => {
                      return item?.name2 ? (
                        <Checkbox value={item?.id2}>{item?.name2}</Checkbox>
                      ) : null;
                    },
                  },
                  {
                    title: '页签/按钮',
                    width: '800px',
                    render: (_, item: any) => {
                      if (item?.buttonList?.length) {
                        return item?.buttonList?.map(
                          (res: any, index: number) => {
                            return res?.name ? (
                              <Checkbox value={res?.id} key={`index_${index}`}>
                                {res?.name}
                              </Checkbox>
                            ) : null;
                          },
                        );
                      }
                    },
                  },
                ]}
              />
            </Checkbox.Group>
          </div>
        </div>
      </ProCard>
    </MyPageContainer>
  );
}
