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 [selectedHouseId, setSelectedHouseId] = useState<number | null>(null);
  const [selectedRow, setSelectedRow] = useState<any>(null);

  // 添加 tableRef 用于操作表格
  const tableRef = useRef<any>();
  // 添加 modalRef 用于关闭窗口
  const modalRef = useRef<any>();

  const onShowContactPhone = () => {
    if (!selectedHouseId) {
      message.warning('请选择一个房屋');
      return;
    }

    // 确保 houses_ids 是字符串数组
    const housesIds = [String(selectedHouseId)];

    Apis.Meter.HouseMeterHasHouses.StoreOrUpdate({
      house_meters_id: props?.item?.id ?? 0,
      asset_houses_ids: housesIds,
    })
      .then(() => {
        // 成功后重置选中状态
        setSelectedHouseId(null);
        setSelectedRow(null);
        props.reload?.();
        message.success('添加成功！');
        // 关闭窗口
        modalRef.current?.close();
      })
      .catch((error) => {
        console.error('添加失败:', error);
        message.error('添加失败: ' + (error.message || '未知错误'));
        return false;
      });
  };
  return (
    <MyModal
      title={props.title || '查看'}
      type="primary"
      width="920px"
      myRef={modalRef}
      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.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: 'radio', // 改为单选
            selectedRowKeys: selectedHouseId ? [selectedHouseId] : [],
            onChange: (selectedRowKeys, selectedRows) => {
              // 单选模式下，只取第一个选中的项
              if (selectedRowKeys.length > 0) {
                const selectedKey =
                  typeof selectedRowKeys[0] === 'string'
                    ? parseInt(selectedRowKeys[0], 10)
                    : (selectedRowKeys[0] as number);

                setSelectedHouseId(selectedKey);
                setSelectedRow(selectedRows[0]);
              } else {
                setSelectedHouseId(null);
                setSelectedRow(null);
              }
            },
          }}
          tableAlertOptionRender={({ selectedRowKeys, onCleanSelected }) => {
            return (
              <Space>
                <span>已选 {selectedRowKeys.length} 项</span>
                <a
                  onClick={() => {
                    onCleanSelected();
                    setSelectedHouseId(null);
                    setSelectedRow(null);
                  }}
                >
                  清空
                </a>
                <MyButtons.Create
                  title="添加"
                  type="primary"
                  key="create2"
                  onClick={() => onShowContactPhone()}
                />
              </Space>
            );
          }}
          options={false}
          columns={[
            MyColumns.ID(),
            MyColumns.EnumTag({
              title: '用途',
              dataIndex: 'usage',
              valueEnum: AssetHousesUsageEnum,
              search: false,
            }),
            {
              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,
            },
            MyColumns.EnumTag({
              title: '产权性质',
              dataIndex: 'ownership_type',
              valueEnum: AssetHousesOwnershipTypeEnum,
              search: false,
            }),
          ]}
        />
      }
    />
  );
}
