import {
  MyBetaModalFormProps,
  MyButtons,
  MyColumns,
  MyImportModal,
  MyProTableProps,
} from '@/common';
import { Apis } from '@/gen/Apis';
import {
  AssetHousesOwnershipTypeEnum,
  AssetHousesUsageEnum,
} from '@/gen/Enums';
import { ProCard, ProTable } from '@ant-design/pro-components';
import { Alert, message, Space, Typography } from 'antd';
import { useCallback, useRef, useState } from 'react';
import BuildingsCreate from '../../dictionary/modals/BuildingsCreate';
import AssetBuildingsUpdate from '../../dictionary/modals/BuildingsUpdate';
import HousesCreate from '../../dictionary/modals/HousesCreate';
import HousesUpdate from '../../dictionary/modals/HousesUpdate';
import AssetUnitsCreate from '../../dictionary/modals/UnitsCreate';
import AssetUnitsUpdate from '../../dictionary/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 (
    <ProCard
      title={
        <Alert
          message="操作提示：在楼栋下添加单元，在单元下添加房屋！"
          type="info"
          showIcon
          style={{ margin: 0 }}
        />
      }
    >
      <Space align="start" size="large" style={{ width: '100%' }}>
        {/* 楼栋列表 */}
        <div style={{ flex: 1, minWidth: 300 }}>
          <Title level={5} style={{ marginBottom: 16 }}>
            <Space style={{ display: 'flex', justifyContent: 'space-between' }}>
              楼栋信息
              <MyImportModal
                key="ImportHouse"
                params={{ asset_projects_id: props?.item?.id }}
                title="批量导入"
                type="danger"
                size="middle"
                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>
          </Title>
          <ProTable
            {...MyProTableProps.props}
            search={false}
            actionRef={actionBuildingsRef}
            size="small"
            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,
              },
              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>
                ),
              }),
            ]}
          />
        </div>

        {/* 单元列表 */}
        {selectedBuilding && (
          <div style={{ flex: 1, minWidth: 300 }}>
            <Title level={5} style={{ marginBottom: 16 }}>
              <Space
                style={{ display: 'flex', justifyContent: 'space-between' }}
              >
                {selectedBuilding.name}
                {selectedBuilding && (
                  <AssetUnitsCreate
                    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}
              size="small"
              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,
                },
                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>
                  ),
                }),
              ]}
            />
          </div>
        )}

        {/* 房屋列表 */}
        {selectedUnit && (
          <div style={{ flex: 1, minWidth: 400 }}>
            <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}
              size="small"
              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>
    </ProCard>
  );
}
