import {
  MyBetaModalFormProps,
  MyButtons,
  MyColumns,
  MyProTableProps,
} from '@/common';
import { MyModal } from '@/components/MyModal';

import { Apis } from '@/gen/Apis';
import {
  AssetCarPortsPropertyTypeEnum,
  AssetCarPortsStatusEnum,
  AssetCarPortsTypeEnum,
} from '@/gen/Enums';
import { ProTable } from '@ant-design/pro-components';
import { message, Space } from 'antd';
import { useRef, useState } from 'react';

export default function ChargeStandardHasHouse(props: MyBetaModalFormProps) {
  // 使用 useState 保存选中的房屋 ID 和行数据，确保跨页选中状态保持
  const [selectedHousesIds, setSelectedHousesIds] = useState<number[]>([]);
  const [selectedRows, setSelectedRows] = useState<any[]>([]);

  // 添加 tableRef 用于操作表格
  const tableRef = useRef<any>();

  const onShowContactPhone = () => {
    if (selectedRows.length === 0) {
      message.warning('请至少选择一个车位');
      return;
    }

    // 确保 houses_ids 是字符串数组
    const carPortsIds = selectedRows.map((row) => String(row.id));

    Apis.HouseCharge.HouseChargeHasCarPorts.Store({
      house_charge_standards_id: props?.item?.id ?? 0,
      car_ports_ids: carPortsIds,
    })
      .then(() => {
        // 成功后重置选中状态
        setSelectedHousesIds([]);
        setSelectedRows([]);
        props.reload?.();
        message.success('绑车位成功！');
      })
      .catch((error) => {
        console.error('绑车位失败:', error);
        message.error('绑车位失败: ' + (error.message || '未知错误'));
        return false;
      });
  };

  return (
    <MyModal
      title={props.title || '查看'}
      type="primary"
      width="920px"
      size={props?.item?.size || 'small'}
      node={
        <ProTable
          actionRef={tableRef}
          {...MyProTableProps.props}
          request={async (params, sort) =>
            MyProTableProps.request(
              {
                ...params,
                asset_projects_id: props?.item?.asset_projects_id,
              },
              sort,
              Apis.Asset.AssetCarPorts.List,
              undefined,
              (res) => {
                // 确保响应数据正确处理
                console.log('加载房屋数据:', res);
                return res;
              },
            )
          }
          style={{
            padding: '20px',
            height: '680px',
            overflowY: 'auto',
            overflowX: 'hidden',
          }}
          pagination={{
            showQuickJumper: true,
            // pageSizeOptions: [10, 20, 50, 100, 200, 500, 1000, 2000],
          }}
          rowSelection={{
            type: 'checkbox',
            preserveSelectedRowKeys: true, // 启用跨页选择
            selectedRowKeys: selectedHousesIds,
            onChange: (selectedRowKeys, selectedRows) => {
              // 确保 selectedRowKeys 是数字类型
              const numericKeys = selectedRowKeys.map((key) =>
                typeof key === 'string' ? parseInt(key, 10) : key,
              ) as number[];

              // 更新选中状态
              setSelectedHousesIds(numericKeys);

              // 合并当前页面选中的行和之前选中的行
              const newSelectedRows = [...selectedRows];

              // 设置选中行数据
              setSelectedRows(newSelectedRows);
            },
          }}
          tableAlertOptionRender={({ selectedRowKeys, onCleanSelected }) => {
            return (
              <Space>
                <span>已选 {selectedRowKeys.length} 项</span>
                <a onClick={onCleanSelected}>清空</a>
                <MyButtons.Create
                  title="批量添加"
                  type="primary"
                  key="create2"
                  onClick={() => onShowContactPhone()}
                />
              </Space>
            );
          }}
          options={false}
          columns={[
            {
              title: '项目名称',
              dataIndex: ['asset_project', 'name'],
              search: false,
            },
            {
              title: '车场名称',
              dataIndex: ['asset_parking_place', 'name'],
              search: {
                transform: (value) => {
                  return { parking_place_name: value };
                },
              },
            },
            {
              title: '车位号',
              dataIndex: 'name',
              search: false,
            },
            {
              title: '车位全称',
              dataIndex: 'full_name',
            },
            {
              title: '建筑面积',
              dataIndex: 'built_area',
              search: false,
            },
            MyColumns.EnumTag({
              title: '类型',
              dataIndex: 'type',
              valueEnum: AssetCarPortsTypeEnum,
            }),
            MyColumns.EnumTag({
              title: '产权类型',
              dataIndex: 'property_type',
              valueEnum: AssetCarPortsPropertyTypeEnum,
            }),
            MyColumns.EnumTag({
              title: '状态',
              dataIndex: 'status',
              valueEnum: AssetCarPortsStatusEnum,
            }),
          ]}
        />
      }
    />
  );
}
