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

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

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

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

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

    // 确保 positions_ids 是字符串数组
    const positionsIds = selectedPositionsIds.map((id) => String(id));

    Apis.Company.CompanyPositions.BatchStore({
      companies_id: props?.item?.id ?? 0,
      positions_ids: positionsIds,
    })
      .then(() => {
        // 成功后重置选中状态
        setSelectedPositionsIds([]);
        setSelectedRows([]);
        props.reload?.();
        message.success('添加成功！');
      })
      .catch((error) => {
        console.error('添加失败:', error);
        message.error('添加失败: ' + (error.message || '未知错误'));
        return false;
      });
  };

  return (
    <MyModal
      title={'岗位库'}
      type="primary"
      size="middle"
      width="600px"
      node={
        <ProTable
          actionRef={tableRef}
          {...MyProTableProps.props}
          request={async (params, sort) =>
            MyProTableProps.request(
              {
                ...params,
                is_use: 1,
              },
              sort,
              Apis.Common.Positions.List,
              undefined,
              (res) => {
                // 确保响应数据正确处理
                console.log('加载岗位数据:', res);
                return res;
              },
            )
          }
          // style={{ height: '800px', overflowY: 'auto', overflowX: 'hidden' }}
          pagination={{
            showQuickJumper: true,
          }}
          rowSelection={{
            type: 'checkbox',
            preserveSelectedRowKeys: true, // 启用跨页选择
            selectedRowKeys: selectedPositionsIds,
            onChange: (selectedRowKeys, selectedRows) => {
              // 确保 selectedRowKeys 是数字类型
              const numericKeys = selectedRowKeys.map((key) =>
                typeof key === 'string' ? parseInt(key, 10) : key,
              ) as number[];

              // 更新选中状态
              setSelectedPositionsIds(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(),
            {
              title: '岗位名称',
              dataIndex: 'name',
              width: 300,
            },
            {
              title: '是否启用',
              dataIndex: 'is_use',
              search: false,
              render: (text) => (text ? '是' : '否'),
              width: 200,
            },
          ]}
        />
      }
    />
  );
}
