import {
  MyButtons,
  MyColumns,
  MyPageContainer,
  MyProTableProps,
  usePageTabs,
} from '@/common';
import { Apis } from '@/gen/Apis';
import {
  AssetHousesOwnershipTypeEnum,
  AssetHousesUsageEnum,
} from '@/gen/Enums';
import { ProCard, ProTable } from '@ant-design/pro-components';
import { useNavigate } from '@umijs/max';
import { Alert, message, Space, Typography } from 'antd';
import { useCallback, useMemo, useRef, useState } from 'react';
import BuildingsCreate from './modals/BuildingsCreate';
import AssetBuildingsUpdate from './modals/BuildingsUpdate';
import HousesCreate from './modals/HousesCreate';
import HousesUpdate from './modals/HousesUpdate';
import UnitsCreate from './modals/UnitsCreate';
import AssetUnitsUpdate from './modals/UnitsUpdate';

const { Title } = Typography;
interface SelectedAsset {
  id: number;
  name: string;
}

interface SelectedBuilding {
  id: number;
  name: string;
}

interface SelectedUnit {
  id: number;
  name: string;
}

export default function Index({ title = '项目列表' }) {
  usePageTabs({
    tabKey: 'asset-buildings',
    tabLabel: title,
  });

  const actionAssetRef: any = useRef();
  const actionBuildingsRef: any = useRef();
  const actionUnitsRef: any = useRef();
  const actionHousesRef: any = useRef();
  const navigate = useNavigate();

  const [selectedAsset, setSelectedAsset] = useState<SelectedAsset | null>(
    null,
  );
  const [selectedBuilding, setSelectedBuilding] =
    useState<SelectedBuilding | null>(null);
  const [selectedUnit, setSelectedUnit] = useState<SelectedUnit | null>(null);
  const [loading, setLoading] = useState({
    buildings: false,
    units: false,
    houses: false,
  });

  // 选择项目的回调函数
  const handleAssetSelect = useCallback(
    (asset: SelectedAsset) => {
      if (selectedAsset?.id === asset.id) return; // 避免重复选择

      setSelectedAsset(asset);
      setSelectedBuilding(null); // 重置楼栋选择
      setSelectedUnit(null); // 重置单元选择

      // 刷新楼栋和单元列表
      actionBuildingsRef?.current?.reload();
      actionUnitsRef?.current?.reload();
      actionHousesRef?.current?.reload();
    },
    [selectedAsset?.id],
  );

  // 选择楼栋的回调函数
  const handleBuildingSelect = useCallback(
    (building: SelectedBuilding) => {
      if (selectedBuilding?.id === building.id) return; // 避免重复选择

      setSelectedBuilding(building);
      setSelectedUnit(null); // 重置单元选择

      // 刷新单元和房屋列表
      actionUnitsRef?.current?.reload();
      actionHousesRef?.current?.reload();
    },
    [selectedBuilding?.id],
  );

  // 选择单元的回调函数
  const handleUnitSelect = useCallback(
    (unit: SelectedUnit) => {
      if (selectedUnit?.id === unit.id) return; // 避免重复选择

      setSelectedUnit(unit);
      // 刷新房屋列表
      actionHousesRef?.current?.reload();
    },
    [selectedUnit?.id],
  );

  // 删除操作的通用处理
  const handleDelete = useCallback(
    async (deleteApi: any, id: number, reloadAction: any, itemName: string) => {
      try {
        await deleteApi({ id });
        message.success(`${itemName}删除成功`);
        reloadAction();

        // 如果删除的是当前选中项，清空选择
        if (itemName === '项目' && selectedAsset?.id === id) {
          setSelectedAsset(null);
          setSelectedBuilding(null);
          setSelectedUnit(null);
        } else if (itemName === '楼栋' && selectedBuilding?.id === id) {
          setSelectedBuilding(null);
          setSelectedUnit(null);
        } else if (itemName === '单元' && selectedUnit?.id === id) {
          setSelectedUnit(null);
        }
      } catch (error) {
        message.error(`${itemName}删除失败`);
        console.error(`删除${itemName}失败:`, error);
      }
    },
    [selectedAsset?.id, selectedBuilding?.id, selectedUnit?.id],
  );

  // 通用表格配置
  const getTableConfig = useMemo(
    () => ({
      ...MyProTableProps.props,
      search: false as const,
      size: 'middle' as const,
      options: false as const,
      pagination: {
        pageSize: 10,
        showSizeChanger: false,
      },
    }),
    [],
  );

  // 项目表格列配置
  const projectColumns = useMemo(
    () => [
      {
        title: '项目',
        dataIndex: 'name',
        ellipsis: true,
        search: {
          transform: (value: string) => ({ name: value }),
        },
      },
      MyColumns.Option({
        width: 120,
        render: (_, item: any, index, action) => (
          <Space key={index} size="small">
            <MyButtons.View
              title="配置"
              onClick={() => {
                navigate(`/asset/list/show/${item.id}`);
              }}
            />
          </Space>
        ),
      }),
    ],
    [handleDelete],
  );

  // 楼栋表格列配置
  const buildingColumns = useMemo(
    () => [
      {
        title: '楼栋',
        dataIndex: 'name',
        ellipsis: true,
      },
      MyColumns.Option({
        width: 120,
        render: (_, item: any, index, action) => (
          <Space key={index} size="small">
            <AssetBuildingsUpdate item={item} reload={action?.reload} />
            {/* <MyButtons.Delete
              size="small"
              onConfirm={() =>
                handleDelete(
                  Apis.Asset.AssetBuildings.Delete,
                  item.id,
                  action?.reload,
                  '楼栋',
                )
              }
            /> */}
          </Space>
        ),
      }),
    ],
    [handleDelete],
  );

  // 单元表格列配置
  const unitColumns = useMemo(
    () => [
      {
        title: '单元',
        dataIndex: 'name',
        ellipsis: true,
      },
      MyColumns.Option({
        width: 120,
        render: (_, item: any, index, action) => (
          <Space key={index} size="small">
            <AssetUnitsUpdate item={item} reload={action?.reload} />
            {/* <MyButtons.Delete
              size="small"
              onConfirm={() =>
                handleDelete(
                  Apis.Asset.AssetUnits.Delete,
                  item.id,
                  action?.reload,
                  '单元',
                )
              }
            /> */}
          </Space>
        ),
      }),
    ],
    [handleDelete],
  );

  // 房屋表格列配置
  const houseColumns = useMemo(
    () => [
      MyColumns.EnumTag({
        title: '用途',
        dataIndex: 'usage',
        valueEnum: AssetHousesUsageEnum,
      }),
      {
        title: '房屋名称',
        dataIndex: 'full_name',
      },
      {
        title: '楼层',
        dataIndex: 'floor',
        render(_, record) {
          return `${record?.floor}层`;
        },
      },
      {
        title: '房号',
        dataIndex: 'name',
      },
      {
        title: '计费面积',
        dataIndex: 'chargeable_area',
        render(_, record) {
          return `${
            record?.chargeable_area ? record?.chargeable_area + ' m²' : '-'
          } `;
        },
      },

      MyColumns.EnumTag({
        title: '房屋属性',
        dataIndex: 'ownership_type',
        valueEnum: AssetHousesOwnershipTypeEnum,
      }),
      MyColumns.Option({
        width: 120,
        render: (_, item: any, index, action) => (
          <Space key={index} size="small">
            <HousesUpdate item={item} reload={action?.reload} title="编辑" />
            {/* <MyButtons.Delete
              size="small"
              onConfirm={() =>
                handleDelete(
                  Apis.Asset.AssetHouses.Delete,
                  item.id,
                  action?.reload,
                  '房屋',
                )
              }
            /> */}
          </Space>
        ),
      }),
    ],
    [handleDelete],
  );

  return (
    <MyPageContainer title={title}>
      <ProCard
        title={
          <Alert
            message="操作提示：可在项目中添加楼栋，在楼栋中添加单元，在单元中添加房屋！"
            type="info"
            showIcon
            style={{ margin: 0 }}
          />
        }
      >
        <Space align="start" size="large" style={{ width: '100%' }}>
          <div style={{ flex: 1 }}>
            <Title level={5} style={{ marginBottom: 16 }}>
              <Space
                style={{ display: 'flex', justifyContent: 'space-between' }}
              >
                项目信息
              </Space>
            </Title>
            <ProTable
              {...getTableConfig}
              // search={{
              //   labelWidth: 'auto',
              //   collapsed: false,
              //   collapseRender: false,
              // }}
              actionRef={actionAssetRef}
              rowClassName={(record: any) => {
                return selectedAsset?.id === record?.id
                  ? 'ant-table-row-selected'
                  : '';
              }}
              onRow={(record: any) => {
                return {
                  onClick: () => {
                    handleAssetSelect(record);
                  },
                  style: {
                    cursor: 'pointer',
                  },
                };
              }}
              request={async (params, sort) =>
                MyProTableProps.request(
                  { ...params },
                  sort,
                  Apis.Asset.AssetProjects.List,
                )
              }
              columns={projectColumns}
            />
          </div>

          {/* 楼栋列表 */}
          {selectedAsset ? (
            <div style={{ flex: 1 }}>
              <Title level={5} style={{ marginBottom: 16 }}>
                <Space
                  style={{ display: 'flex', justifyContent: 'space-between' }}
                >
                  <span>{selectedAsset?.name}</span>
                  <BuildingsCreate
                    key="BuildingsCreate"
                    item={{ ...selectedAsset, size: 'small' }}
                    reload={() => actionBuildingsRef?.current?.reload()}
                    title="楼栋"
                  />
                </Space>
              </Title>
              <ProTable
                {...getTableConfig}
                actionRef={actionBuildingsRef}
                rowClassName={(record: any) => {
                  return selectedBuilding?.id === record?.id
                    ? 'ant-table-row-selected'
                    : '';
                }}
                onRow={(record: any) => {
                  return {
                    onClick: () => {
                      handleBuildingSelect(record);
                    },
                    style: {
                      cursor: 'pointer',
                    },
                  };
                }}
                request={async (params, sort) =>
                  MyProTableProps.request(
                    { ...params, asset_projects_id: selectedAsset?.id },
                    sort,
                    Apis.Asset.AssetBuildings.List,
                  )
                }
                columns={buildingColumns}
              />
            </div>
          ) : (
            <div
              style={{
                flex: 1,
                // minWidth: 300,
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                color: '#999',
              }}
            >
              请先选择项目
            </div>
          )}
          {/* 单元列表 */}
          {selectedBuilding ? (
            <div style={{ flex: 1 }}>
              <Title level={5} style={{ marginBottom: 16 }}>
                <Space
                  style={{ display: 'flex', justifyContent: 'space-between' }}
                >
                  <span>{selectedBuilding.name}</span>
                  <UnitsCreate
                    key="UnitsCreate"
                    item={{
                      ...selectedBuilding,
                      asset_buildings_id: selectedBuilding?.id,
                      size: 'small',
                    }}
                    reload={() => actionUnitsRef?.current?.reload()}
                    title="单元"
                  />
                </Space>
              </Title>
              <ProTable
                {...getTableConfig}
                actionRef={actionUnitsRef}
                request={async (params, sort) =>
                  MyProTableProps.request(
                    {
                      ...params,
                      asset_projects_id: selectedAsset?.id,
                      asset_buildings_id: selectedBuilding?.id,
                    },
                    sort,
                    Apis.Asset.AssetUnits.List,
                  )
                }
                rowClassName={(record: any) => {
                  return selectedUnit?.id === record?.id
                    ? 'ant-table-row-selected'
                    : '';
                }}
                onRow={(record: any) => {
                  return {
                    onClick: () => {
                      handleUnitSelect(record);
                    },
                    style: {
                      cursor: 'pointer',
                    },
                  };
                }}
                columns={unitColumns}
              />
            </div>
          ) : (
            <div
              style={{
                flex: 1,
                // minWidth: 300,
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                color: '#999',
              }}
            >
              请先选择楼栋
            </div>
          )}

          {/* 房屋列表 */}
          {selectedUnit ? (
            <div style={{ flex: 1 }}>
              <Title level={5} style={{ marginBottom: 16 }}>
                <Space
                  style={{ display: 'flex', justifyContent: 'space-between' }}
                >
                  <span>{selectedUnit.name}</span>
                  <HousesCreate
                    key="HousesCreate"
                    item={{
                      ...selectedUnit,
                      asset_projects_id: selectedAsset?.id,
                      asset_buildings_id: selectedBuilding?.id,
                      asset_units_id: selectedUnit?.id,
                      size: 'small',
                    }}
                    reload={() => actionHousesRef?.current?.reload()}
                    title="房屋"
                  />
                </Space>
              </Title>
              <ProTable
                {...getTableConfig}
                actionRef={actionHousesRef}
                request={async (params, sort) =>
                  MyProTableProps.request(
                    {
                      ...params,
                      asset_projects_id: selectedAsset?.id,
                      asset_buildings_id: selectedBuilding?.id,
                      asset_units_id: selectedUnit?.id,
                    },
                    sort,
                    Apis.Asset.AssetHouses.List,
                  )
                }
                columns={houseColumns}
              />
            </div>
          ) : (
            <div
              style={{
                flex: 1,
                // minWidth: 400,
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                color: '#999',
              }}
            >
              {selectedBuilding ? '请先选择单元' : '请先选择楼栋'}
            </div>
          )}
        </Space>
      </ProCard>
    </MyPageContainer>
  );
}
