import {
  MyBetaModalFormProps,
  MyButtons,
  MyColumns,
  MyImportModal,
  MyProTableProps,
} from '@/common';
import { Apis } from '@/gen/Apis';
import {
  AssetCarPortsPropertyTypeEnum,
  AssetCarPortsTypeEnum,
} from '@/gen/Enums';
import { ProTable } from '@ant-design/pro-components';
import { Alert, message, Space, Typography } from 'antd';
import { useCallback, useRef, useState } from 'react';
import { default as AreaCreate } from '../../parking_area/modals/AreaCreate';
import ParkingPlaceUpdate from '../../parking_area/modals/AreaUpdate';
import SpaceCreate from '../../parking_space/modals/SpaceCreate';
import CarPortUpdate from '../../parking_space/modals/SpaceUpdate';

const { Title } = Typography;

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

export default function ParkingSpaces(props: MyBetaModalFormProps) {
  const actionParkingPlacesRef: any = useRef();
  const actionCarPortsRef: any = useRef();
  const [selectedParkingPlace, setSelectedParkingPlace] =
    useState<SelectedParkingPlace | null>(null);

  // 选择车场的回调函数
  const handleParkingPlaceSelect = useCallback(
    (place: SelectedParkingPlace) => {
      setSelectedParkingPlace(place);
      // 刷新车位列表
      actionCarPortsRef?.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>
                <AreaCreate
                  key="ParkingPlaceCreate"
                  item={props?.item}
                  reload={() => actionParkingPlacesRef?.current?.reload()}
                  title="车场"
                />
              </Space>
            </Space>
          </Title>
          <ProTable
            {...MyProTableProps.props}
            search={false}
            actionRef={actionParkingPlacesRef}
            rowClassName={(record: any) => {
              return selectedParkingPlace?.id === record?.id
                ? 'ant-table-row-selected'
                : '';
            }}
            onRow={(record: any) => {
              return {
                onClick: () => {
                  handleParkingPlaceSelect(record);
                },
                style: {
                  cursor: 'pointer',
                },
              };
            }}
            request={async (params, sort) =>
              MyProTableProps.request(
                { ...params, asset_projects_id: props?.item?.id },
                sort,
                Apis.Asset.AssetParkingPlaces.List,
              )
            }
            options={false}
            pagination={{
              pageSize: 10,
              showSizeChanger: false,
            }}
            columns={[
              {
                title: '车场名称',
                dataIndex: 'name',
                ellipsis: true,
                width: 200,
              },
              MyColumns.Option({
                width: 120,
                render: (_, item: any, index, action) => (
                  <Space key={index} size="small">
                    <ParkingPlaceUpdate
                      item={item}
                      title="车场"
                      reload={action?.reload}
                    />
                    <MyButtons.Delete
                      size="small"
                      onConfirm={() =>
                        handleDelete(
                          Apis.Asset.AssetParkingPlaces.Delete,
                          item.id,
                          action?.reload,
                          '车场',
                        )
                      }
                    />
                  </Space>
                ),
              }),
            ]}
          />
        </div>

        {/* 车位列表 */}
        {selectedParkingPlace && (
          <div style={{ flex: 1, minHeight: 500 }}>
            <Title level={5} style={{ marginBottom: 16 }}>
              <Space
                style={{ display: 'flex', justifyContent: 'space-between' }}
              >
                {selectedParkingPlace.name}
                {selectedParkingPlace && (
                  <Space>
                    <MyImportModal
                      key="ImportCarPorts"
                      params={{ asset_projects_id: props?.item?.id }}
                      title="导入"
                      type="default"
                      size="middle"
                      templateApi={Apis.Asset.AssetCarPorts.DownloadTemplate}
                      importApi={Apis.Asset.AssetCarPorts.Import}
                      reload={() => actionCarPortsRef?.current?.reload()}
                    />
                    <SpaceCreate
                      key="SpaceCreate"
                      item={{
                        ...props?.item,
                        asset_projects_id: props?.item?.id,
                        asset_parking_places_id: selectedParkingPlace?.id,
                      }}
                      reload={() => actionCarPortsRef?.current?.reload()}
                      title="车位"
                    />
                  </Space>
                )}
              </Space>
            </Title>
            <ProTable
              {...MyProTableProps.props}
              search={false}
              actionRef={actionCarPortsRef}
              request={async (params, sort) =>
                MyProTableProps.request(
                  {
                    ...params,
                    asset_projects_id: props?.item?.id,
                    asset_parking_places_id: selectedParkingPlace?.id,
                  },
                  sort,
                  Apis.Asset.AssetCarPorts.List,
                )
              }
              options={false}
              pagination={{
                pageSize: 10,
                showSizeChanger: false,
              }}
              columns={[
                MyColumns.ID({
                  search: false,
                }),
                {
                  title: '车位全称',
                  dataIndex: 'full_name',
                },
                {
                  title: '车位号',
                  dataIndex: 'name',
                  search: false,
                },
                {
                  title: '建筑面积',
                  dataIndex: 'built_area',
                  search: false,
                },
                MyColumns.EnumTag({
                  title: '类型',
                  dataIndex: 'type',
                  valueEnum: AssetCarPortsTypeEnum,
                }),
                MyColumns.EnumTag({
                  title: '产权类型',
                  dataIndex: 'property_type',
                  valueEnum: AssetCarPortsPropertyTypeEnum,
                }),
                MyColumns.Option({
                  width: 160,
                  render: (_, item: any, index, action) => (
                    <Space key={index} size="small">
                      <CarPortUpdate item={item} reload={action?.reload} />
                      <MyButtons.Delete
                        size="small"
                        onConfirm={() =>
                          handleDelete(
                            Apis.Asset.AssetCarPorts.Delete,
                            item.id,
                            action?.reload,
                            '车位',
                          )
                        }
                      />
                    </Space>
                  ),
                }),
              ]}
            />
          </div>
        )}
      </Space>
    </Space>
  );
}
