import { CODE, IMAGES_TYPE_MAP } from '@/constants/images.constants';
import { getImagesList } from '@/services/images';
import {
  DeleteOutlined,
  EyeOutlined,
  SettingOutlined,
} from '@ant-design/icons';
import type { TableProps } from 'antd';
import dayjs from 'dayjs';
import {
  Button,
  Checkbox,
  Input,
  message,
  Modal,
  Popconfirm,
  Popover,
  Space,
  Table,
  Tooltip,
  Tag,
} from 'antd';
import React, { useEffect, useState } from 'react';
import { ImportModal, ModalDetailShow } from './components/modalShow/modalShow';
import './index.less';

import { ReactComponent as RefreshIcon } from '@/assets/icons/refresh.svg';

// 列配置定义
type ColumnConfig = {
  key: string;
  title: string;
  dataIndex?: string;
  width: number;
  render?: (text: any, record: any, index: number) => React.ReactNode;
  fixed?: 'left' | 'right';
  defaultVisible: boolean; // 默认是否显示
  alwaysVisible?: boolean; // 始终显示的列
};

type TableColumn = {
  title: string;
  dataIndex?: string;
  key: string;
  width: number;
  render?: any;
  fixed?: 'left' | 'right';
  hidden?: boolean;
};

const ImageList: React.FC = () => {
  const [images, setImages] = useState<IMAGES.ImageItem[]>([]);
  const [loading, setLoading] = useState(false);
  const [selectedImage, setSelectedImage] = useState<IMAGES.ImageItem | null>(
    null,
  );
  const [searchText, setSearchText] = useState<string>('');
  const [detailVisible, setDetailVisible] = useState(false);
  const [importModalVisible, setImportModalVisible] = useState(false);
  const [tableParams, setTableParams] = useState<IMAGES.TableParams>({
    pagination: {
      current: 1,
      pageSize: 10,
    },
  });

  const [columnSettingsVisible, setColumnSettingsVisible] = useState(false);

  // 表格参数变化 获取镜像列表
  useEffect(() => {
    loadImages();
  }, [
    tableParams.pagination?.current,
    tableParams.pagination?.pageSize,
    tableParams?.sortOrder,
    tableParams?.sortField,
    JSON.stringify(tableParams.filters),
    JSON.stringify(tableParams.image_name),
  ]);

  // 定义所有列的配置
  const columnConfigs: ColumnConfig[] = [
    {
      key: 'index',
      title: '序号',
      width: 120,
      render: (text: any, row: any, index: number) =>
        (tableParams.pagination?.current - 1) *
          tableParams.pagination?.pageSize +
        index +
        1,
      defaultVisible: true,
      alwaysVisible: true,
    },
    {
      key: 'image_name',
      title: '镜像名称',
      dataIndex: 'image_name',
      width: 120,
      defaultVisible: true,
      alwaysVisible: true,
    },
    {
      key: 'image_type',
      title: '桌面类型',
      dataIndex: 'image_type',
      width: 80,
      render: (text: number) => {
        const key = text as keyof typeof IMAGES_TYPE_MAP;
        return <Tooltip>{IMAGES_TYPE_MAP[key] || '--'}</Tooltip>;
      },
      defaultVisible: true,
    },
    {
      key: 'storage_path',
      title: '模板存放路径',
      dataIndex: 'storage_path',
      width: 140,
      defaultVisible: true,
    },
    {
      key: 'bt_path',
      title: 'BT路径',
      dataIndex: 'bt_path',
      width: 140,
      defaultVisible: true,
    },
    {
      key: 'image_version',
      title: '镜像版本',
      dataIndex: 'image_version',
      width: 100,
      defaultVisible: true,
    },
    {
      key: 'os_version',
      title: '操作系统',
      dataIndex: 'os_version',
      width: 100,
      defaultVisible: true,
    },
    {
      key: 'image_status',
      title: '镜像状态',
      dataIndex: 'image_status',
      width: 80,
      render: (text: number) => <Tooltip>{getStatusTag(text)}</Tooltip>,
      defaultVisible: true,
    },
    {
      key: 'create_time',
      title: '创建时间',
      dataIndex: 'create_time',
      width: 180,
      render: (text: string) => (
        <Tooltip>{dayjs(text).format('YYYY-MM-DD HH:mm:ss')}</Tooltip>
      ),
      defaultVisible: true,
    },
    {
      key: 'action',
      title: '操作',
      width: 100,
      fixed: 'right' as 'right',
      render: (_: any, record: IMAGES.ImageItem) => (
        <Space size="small">
          <Button
            type="text"
            icon={<EyeOutlined />}
            onClick={() => handleViewDetail(record)}
            title="查看详情"
          />
          <Popconfirm
            title="确定要删除这个镜像吗？"
            description="删除后无法恢复，请谨慎操作。"
            onConfirm={() => handleDelete(record)}
            okText="确定"
            cancelText="取消"
          >
            <Button type="text" icon={<DeleteOutlined />} title="删除" danger />
          </Popconfirm>
        </Space>
      ),
      defaultVisible: true,
    },
  ];

  // 初始化 visibleColumns 状态
  const initialVisibleColumns = columnConfigs.reduce<Record<string, boolean>>(
    (acc, column) => {
      if (!column.alwaysVisible) {
        acc[column.key] = column.defaultVisible;
      }
      return acc;
    },
    {},
  );

  const [visibleColumns, setVisibleColumns] = useState<Record<string, boolean>>(
    initialVisibleColumns,
  );

  // 重置列设置
  const resetColumns = () => {
    setVisibleColumns(initialVisibleColumns);
  };

  /**
   * 表格参数转换
   * @param params - 表格参数对象，包含分页、过滤、排序等信息
   * @returns 转换后的接口参数对象
   */
  const getRandomuserParams = (params: IMAGES.TableParams) => {
    const {
      pagination,
      filters,
      sortField,
      sortOrder,
      image_name,
      ...restParams
    } = params;
    const result: Record<string, any> = {};

    result.page_size = pagination?.pageSize;
    result.page_num = pagination?.current;

    if (image_name) {
      result.image_name = image_name;
    }

    if (filters) {
      Object.entries(filters).forEach(([key, value]) => {
        if (value !== undefined && value !== null) {
          result[key] = value;
        }
      });
    }

    if (sortField) {
      result.orderby = sortField;
      result.order = sortOrder === 'ascend' ? 'asc' : 'desc';
    }

    // 处理其他参数
    Object.entries(restParams).forEach(([key, value]) => {
      if (value !== undefined && value !== null) {
        result[key] = value;
      }
    });

    return result;
  };
  const params = getRandomuserParams(tableParams);

  const loadImages = async () => {
    setLoading(true);
    try {
      const imagesRes = await getImagesList(params);
      if (imagesRes.code == CODE) {
        setImages(imagesRes.data.data || []);
        setLoading(false);
        // 直接使用后端返回的分页信息
        setTableParams((prev) => ({
          ...prev,
          pagination: {
            ...prev.pagination,
            current: imagesRes.data.paging.page_num || 1,
            total: imagesRes.data.paging.total || 0,
            pageSize: imagesRes.data.paging.page_size || 10,
          },
        }));
      } else {
        message.error(imagesRes.message || '获取镜像列表失败');
        setLoading(false);
      }
    } catch (err) {
      message.error('获取镜像列表失败');
      setLoading(false);
    }
  };
  const getStatusTag = (status: number) => {
    const statusMap = {
      1: { color: 'green', text: '成功' },
      2: { color: 'red', text: '失败' },
    };
    const config = statusMap[status as keyof typeof statusMap];
    return <Tag color={config.color}>{config.text}</Tag>;
  };

  const handleViewDetail = (record: IMAGES.ImageItem) => {
    setSelectedImage(record);
    setDetailVisible(true);
  };

  const handleDelete = (record: IMAGES.ImageItem) => {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除镜像 "${record.image_name}" 吗？`,
      onOk: () => {
        // TODO: 调用删除接口
        setImages(images.filter((img) => img.image_id !== record.image_id));
        message.success('删除成功');
      },
    });
  };

  // 列设置相关函数
  const handleColumnChange = (columnKey: string, checked: boolean) => {
    setVisibleColumns((prev) => ({
      ...prev,
      [columnKey]: checked,
    }));
  };

  // 列设置内容
  const columnSettingsContent = (
    <div style={{ padding: '8px 0' }}>
      {columnConfigs
        .filter((config) => !config.alwaysVisible) // 只显示可控制的列
        .map((config) => (
          <div key={config.key} style={{ padding: '4px 12px' }}>
            <Checkbox
              checked={visibleColumns[config.key]}
              onChange={(e) => handleColumnChange(config.key, e.target.checked)}
            >
              {config.title}
            </Checkbox>
          </div>
        ))}
      <div
        style={{
          padding: '8px 12px',
          borderTop: '1px solid #f0f0f0',
          marginTop: 8,
        }}
      >
        <Button type="link" onClick={resetColumns} style={{ padding: 0 }}>
          重置
        </Button>
      </div>
    </div>
  );

  // 根据visibleColumns过滤显示的列
  const filteredColumns = columnConfigs
    .map((config) => {
      // 对于始终显示的列
      if (config.alwaysVisible) {
        return {
          title: config.title,
          dataIndex: config.dataIndex,
          key: config.key,
          width: config.width,
          render: config.render,
          fixed: config.fixed,
          hidden: undefined,
        };
      }

      // 对于可控制显示/隐藏的列
      return {
        title: config.title,
        dataIndex: config.dataIndex,
        key: config.key,
        width: config.width,
        render: config.render,
        fixed: config.fixed,
        ...(visibleColumns[config.key] ? {} : { hidden: true }),
      };
    })
    .filter((column) => !column.hidden) as TableColumn[];

  // 处理表格分页、过滤和排序变化
  const handleTableChange: TableProps<IMAGES.ImageItem>['onChange'] = (
    pagination,
    filters,
    sorter,
  ) => {
    setTableParams({
      pagination: {
        current: pagination.current || 1,
        pageSize: pagination.pageSize || 10,
      },
      filters,
      sortOrder: Array.isArray(sorter) ? undefined : sorter.order,
      sortField: Array.isArray(sorter)
        ? undefined
        : (sorter.field as string | number | undefined),
    });

    if (pagination.pageSize !== tableParams.pagination?.pageSize) {
      setImages([]);
    }
  };

  const handleRefresh = () => {
    loadImages();
  };

  // 导入镜像成功后的回调
  const handleImportSuccess = () => {
    setTimeout(() => {
      loadImages();
    }, 5000);
  };

  // 自定义分页配置
  const paginationConfig = {
    ...tableParams.pagination,
    showTotal: (total: number) => `共 ${total} 条记录`,
    showSizeChanger: true,
    showQuickJumper: true,
    pageSizeOptions: ['10', '20', '50', '100'],
  };

  return (
    <div className="image-list">
      <div className="search-box">
        <Button onClick={() => setImportModalVisible(true)}>导入</Button>
        <div className="search-input">
          <Input.Search
            placeholder="镜像名称"
            value={searchText}
            onChange={(e) => setSearchText(e.target.value)}
            style={{ width: 300 }}
            onSearch={(value) => {
              setTableParams((prev) => ({
                ...prev,
                pagination: {
                  ...prev.pagination,
                  current: 1,
                },
                image_name: value,
              }));
            }}
          />
          <Button
            onClick={handleRefresh}
            loading={loading}
            icon={<RefreshIcon style={{ width: 13, height: 13 }} />}
          ></Button>
          <Popover
            content={columnSettingsContent}
            title="列设置"
            trigger="click"
            open={columnSettingsVisible}
            onOpenChange={setColumnSettingsVisible}
            placement="bottomRight"
          >
            <Button icon={<SettingOutlined />}></Button>
          </Popover>
        </div>
      </div>
      <div className="images-list-container">
        <div className="images-list-table">
          <Table
            columns={filteredColumns}
            dataSource={images}
            rowKey="image_id"
            loading={loading}
            pagination={paginationConfig}
            onChange={handleTableChange}
            scroll={{ y: '100%' }}
          />
        </div>
      </div>

      {detailVisible ? (
        <ModalDetailShow
          title="镜像详情"
          detailVisible={detailVisible}
          setDetailVisible={setDetailVisible}
          selectedImage={selectedImage}
        />
      ) : null}
      {/* 导入弹窗 */}
      <ImportModal
        visible={importModalVisible}
        onCancel={() => setImportModalVisible(false)}
        onImportSuccess={handleImportSuccess}
      />
    </div>
  );
};

export default ImageList;
