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

const { Title } = Typography;

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

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

export default function AssetBuildings(props: MyBetaModalFormProps) {
  const actionBuildingsRef: any = useRef();
  const actionUnitsRef: any = useRef();
  const actionHousesRef: any = useRef();
  const [selectedBuilding, setSelectedBuilding] =
    useState<SelectedBuilding | null>(null);
  const [selectedUnit, setSelectedUnit] = useState<SelectedUnit | null>(null);

  // 选择楼栋的回调函数
  const handleBuildingSelect = useCallback((building: SelectedBuilding) => {
    setSelectedBuilding(building);
    setSelectedUnit(null); // 重置单元选择
    // 刷新单元和房屋列表
    actionUnitsRef?.current?.reload();
    actionHousesRef?.current?.reload();
  }, []);

  // 选择单元的回调函数
  const handleUnitSelect = useCallback((unit: SelectedUnit) => {
    setSelectedUnit(unit);
    // 刷新房屋列表
    actionHousesRef?.current?.reload();
  }, []);

  // 删除操作的通用处理
  const handleDelete = useCallback(
    async (deleteApi: any, id: number, reloadAction: any, itemName: string) => {
      try {
        await deleteApi({ id });
        message.success(`${itemName}删除成功`);
        reloadAction();
      } catch (error) {
        message.error(`${itemName}删除失败`);
      }
    },
    [],
  );
  return (
    <Space direction="vertical" size={30} style={{ display: 'flex' }}>
      <Alert
        message="操作提示：需依次点击楼栋、单元、房屋，才能进行对应操作！"
        type="info"
        showIcon
        style={{ width: 600 }}
      />
      <Space align="start" size={30} style={{ width: '100%' }}>
        {/* 楼栋列表 */}
        <div style={{ flex: 1, minHeight: 500 }}>
          <Title level={5} style={{ marginBottom: 16 }}>
            <Space style={{ display: 'flex', justifyContent: 'space-between' }}>
              楼栋
              <Space>
                {/* <MyImportModal
                  key="ImportHouse"
                  params={{ asset_projects_id: props?.item?.id }}
                  title="导入"
                  type="default"
                  // size="small"
                  templateApi={Apis.Asset.AssetHouses.DownloadTemplate}
                  importApi={Apis.Asset.AssetHouses.Import}
                  reload={props?.reload}
                /> */}
                <BuildingsCreate
                  key="BuildingsCreate"
                  item={props?.item}
                  reload={() => actionBuildingsRef?.current?.reload()}
                  title="楼栋"
                />
              </Space>
            </Space>
          </Title>
          <ProTable
            {...MyProTableProps.props}
            search={false}
            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: props?.item?.id },
                sort,
                Apis.Asset.AssetBuildings.List,
              )
            }
            options={false}
            pagination={{
              pageSize: 10,
              showSizeChanger: false,
            }}
            columns={[
              {
                title: '楼栋名称',
                dataIndex: 'name',
                ellipsis: true,
                width: 140,
              },
              MyColumns.Option({
                width: 120,
                render: (_, item: any, index, action) => (
                  <Space key={index} size="small">
                    <BuildingsUpdate item={item} reload={action?.reload} />
                    <MyButtons.Delete
                      size="small"
                      onConfirm={() =>
                        handleDelete(
                          Apis.Asset.AssetBuildings.Delete,
                          item.id,
                          action?.reload,
                          '楼栋',
                        )
                      }
                    />
                  </Space>
                ),
              }),
            ]}
          />
        </div>

        {/* 单元列表 */}
        {selectedBuilding && (
          <div style={{ flex: 1, minHeight: 500 }}>
            <Title level={5} style={{ marginBottom: 16 }}>
              <Space
                style={{ display: 'flex', justifyContent: 'space-between' }}
              >
                {selectedBuilding.name}
                {selectedBuilding && (
                  <UnitsCreate
                    key="UnitsCreate"
                    item={{
                      ...props?.item,
                      asset_buildings_id: selectedBuilding?.id,
                    }}
                    reload={() => actionUnitsRef?.current?.reload()}
                    title="单元"
                    // title={`添加${selectedBuilding.name}单元`}
                  />
                )}
              </Space>
            </Title>
            <ProTable
              {...MyProTableProps.props}
              search={false}
              actionRef={actionUnitsRef}
              request={async (params, sort) =>
                MyProTableProps.request(
                  {
                    ...params,
                    asset_projects_id: props?.item?.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',
                  },
                };
              }}
              options={false}
              pagination={{
                pageSize: 10,
                showSizeChanger: false,
              }}
              columns={[
                {
                  title: '单元名称',
                  dataIndex: 'name',
                  ellipsis: true,
                  width: 140,
                },
                MyColumns.Option({
                  width: 120,
                  render: (_, item: any, index, action) => (
                    <Space key={index} size="small">
                      <UnitsUpdate item={item} reload={action?.reload} />
                      {/* <MyButtons.Delete
                        size="small"
                        onConfirm={() =>
                          handleDelete(
                            Apis.Asset.AssetUnits.Delete,
                            item.id,
                            action?.reload,
                            '单元',
                          )
                        }
                      /> */}
                    </Space>
                  ),
                }),
              ]}
            />
          </div>
        )}

        {/* 房屋列表 */}
        {selectedUnit && (
          <div style={{ flex: 1, minHeight: 500 }}>
            <Title level={5} style={{ marginBottom: 16 }}>
              <Space
                style={{ display: 'flex', justifyContent: 'space-between' }}
              >
                {selectedUnit.name}
                {selectedUnit && (
                  <HousesCreate
                    key="HousesCreate"
                    item={{
                      ...props?.item,
                      asset_buildings_id: selectedBuilding?.id,
                      asset_units_id: selectedUnit?.id,
                    }}
                    reload={() => actionHousesRef?.current?.reload()}
                    title="房屋"
                    // title={`${selectedUnit.name}房屋`}
                  />
                )}
              </Space>
            </Title>
            <ProTable
              {...MyProTableProps.props}
              search={false}
              actionRef={actionHousesRef}
              request={async (params, sort) =>
                MyProTableProps.request(
                  {
                    ...params,
                    asset_projects_id: props?.item?.id,
                    asset_buildings_id: selectedBuilding?.id,
                    asset_units_id: selectedUnit?.id,
                  },
                  sort,
                  Apis.Asset.AssetHouses.List,
                )
              }
              options={false}
              pagination={{
                pageSize: 10,
                showSizeChanger: false,
              }}
              columns={[
                {
                  title: '楼层',
                  dataIndex: 'floor',
                  width: 80,
                  render(_, record) {
                    return `${record?.floor}层`;
                  },
                },
                {
                  title: '房号',
                  dataIndex: 'name',
                  width: 80,
                },
                MyColumns.EnumTag({
                  title: '用途',
                  dataIndex: 'usage',
                  valueEnum: AssetHousesUsageEnum,
                  width: 100,
                }),
                MyColumns.EnumTag({
                  title: '房屋属性',
                  dataIndex: 'ownership_type',
                  valueEnum: AssetHousesOwnershipTypeEnum,
                  width: 100,
                }),
                MyColumns.Option({
                  width: 150,
                  render: (_, item: any, index, action) => (
                    <Space key={index} size="small">
                      {/* <HousesShow item={item} reload={action?.reload} /> */}
                      <HousesUpdate
                        item={item}
                        reload={action?.reload}
                        title="编辑"
                      />
                      <MyButtons.Delete
                        size="small"
                        onConfirm={() =>
                          handleDelete(
                            Apis.Asset.AssetHouses.Delete,
                            item.id,
                            action?.reload,
                            '房屋',
                          )
                        }
                      />
                    </Space>
                  ),
                }),
              ]}
            />
          </div>
        )}
      </Space>
    </Space>
  );
}
