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

import { Apis } from '@/gen/Apis';
import {
  AssetHousesOwnershipTypeEnum,
  AssetHousesUsageEnum,
} 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 (selectedHousesIds.length === 0) {
      message.warning('请至少选择一个房屋');
      return;
    }

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

    Apis.HouseCharage.HouseChargeHasHouses.Store({
      house_charge_standards_id: props?.item?.id ?? 0,
      houses_ids: housesIds,
    })
      .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"
      node={
        <ProTable
          actionRef={tableRef}
          {...MyProTableProps.props}
          request={async (params, sort) =>
            MyProTableProps.request(
              {
                ...params,
                asset_projects_id: props?.item?.asset_projects_id,
              },
              sort,
              Apis.Asset.AssetHouses.List,
              undefined,
              (res) => {
                // 确保响应数据正确处理
                console.log('加载房屋数据:', res);
                return res;
              },
            )
          }
          style={{ height: '800px', 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={[
            MyColumns.ID(),
            MyColumns.EnumTag({
              title: '用途',
              dataIndex: 'usage',
              valueEnum: AssetHousesUsageEnum,
            }),
            {
              title: '项目名称',
              dataIndex: ['asset_project', 'name'],
              search: false,
            },
            {
              title: '楼栋名称',
              dataIndex: ['asset_building', 'name'],
              search: {
                transform: (value) => {
                  return { building_name: value };
                },
              },
            },
            {
              title: '单元名称',
              dataIndex: ['asset_unit', 'name'],
              search: {
                transform: (value) => {
                  return { unit_name: value };
                },
              },
            },
            {
              title: '房号',
              dataIndex: 'name',
            },

            {
              title: '楼层',
              dataIndex: 'floor',
              render(_, record) {
                return `${record?.floor}层`;
              },
              search: false,
            },

            {
              title: '建筑面积',
              dataIndex: 'built_area',
              render(_, record) {
                return `${
                  record?.built_area ? record?.built_area + ' m²' : '-'
                } `;
              },
              search: false,
            },
            {
              title: '套内面积',
              dataIndex: 'inside_area',
              render(_, record) {
                return `${
                  record?.inside_area ? record?.inside_area + ' m²' : '-'
                } `;
              },
              search: false,
            },
            {
              title: '计费面积',
              dataIndex: 'chargeable_area',
              render(_, record) {
                return `${
                  record?.chargeable_area
                    ? record?.chargeable_area + ' m²'
                    : '-'
                } `;
              },
              search: false,
            },
            // {
            //   title: '户型',
            //   render(_, record) {
            //     return `${record?.room || 'x'}室${record?.hall || 'x'}厅${
            //       record?.bathroom || 'x'
            //     }卫${record?.kitchen || 'x'}厨${record?.balcony || 'x'}阳台`;
            //   },
            //   search: false,
            // },
            MyColumns.EnumTag({
              title: '产权性质',
              dataIndex: 'ownership_type',
              valueEnum: AssetHousesOwnershipTypeEnum,
              search: false,
            }),
          ]}
        />
      }
    />
  );
}
