import React, { useState, useEffect, useRef, useMemo } from 'react';
import { Plus, Search, RefreshCw, Edit2, Trash2 } from 'lucide-react';
import { segregationPointApi, SegregationPointVO, PageParam } from '../api/spm/index';
import { dictDataApi } from '../api/DictData';
import { postApi, PostVO } from '../api/Post';
import { toast } from 'sonner';
import { Modal, Table, Input, Button, Select, TreeSelect, Space, Image, Switch } from 'antd';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import { getStrDictOptions, setDictOptions, getDictLabel, DICT_TYPE } from '../utils/dict';
import SegregationPointForm, { SegregationPointFormRef } from './SegregationPointForm';
import { Button as UIButton } from './ui/button';
import PermissionWrapper from './PermissionWrapper';
import { useTranslation } from 'react-i18next';
import './IsolationWorkListTable.css';

interface SegregationPointManagementProps {
  subMenu?: string;
}

export default function SegregationPointManagement({ subMenu }: SegregationPointManagementProps) {
  const { t, i18n } = useTranslation();
  // 顶部查询条件：先隐藏（不删除代码），后续需要再打开改为 true 即可
  const showAdvancedQueryFilters = false;
  const [loading, setLoading] = useState(true);
  const [list, setList] = useState<SegregationPointVO[]>([]);
  const [total, setTotal] = useState(0);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [queryParams, setQueryParams] = useState<PageParam>({
    current: 1,
    size: 10,
    pointName: undefined,
    workstationId: undefined,
    machineryId: undefined,
    lotoId: undefined,
    powerType: undefined,
  });

  // 下拉选项数据
  const [deptOptions, setDeptOptions] = useState<any[]>([]);
  const [machineryOptions, setMachineryOptions] = useState<any[]>([]);
  const [lotoOptions, setLotoOptions] = useState<Array<{ label: string; value: number }>>([]);
  const [powerTypeOptions, setPowerTypeOptions] = useState<Array<{ label: string; value: string }>>([]);
  /** 岗位 id -> name，用于列表岗位列回显 */
  const [postNameMap, setPostNameMap] = useState<Map<number, string>>(new Map());

  const formRef = useRef<SegregationPointFormRef>(null);

  // 获取隔离点列表
  const getList = async (params?: PageParam) => {
    const currentParams = params || queryParams;
    setLoading(true);
    try {
      console.log('SegregationPointManagement: 开始获取隔离点列表', currentParams);
      const response = await segregationPointApi.getIsIsolationPointPage(currentParams);
      console.log('SegregationPointManagement: API 响应', response);
      
      // 处理响应数据
      let data;
      if (response && typeof response === 'object') {
        // 如果响应有 data 属性，使用 data；否则直接使用 response
        if ('data' in response && response.data) {
          data = response.data;
        } else if ('list' in response || 'total' in response) {
          data = response;
        } else {
          data = response;
        }
      } else {
        data = response;
      }
      
      setList(data?.list || []);
      setTotal(data?.total || 0);
      console.log('SegregationPointManagement: 设置列表数据', { list: data?.list || [], total: data?.total || 0 });
    } catch (error: any) {
      console.error('SegregationPointManagement: 获取列表失败', error);
      toast.error(error.message || t('form.getSegregationPointListFailed'));
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    getList();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [queryParams.current, queryParams.size]);

  // 初始化数据
  useEffect(() => {
    const initData = async () => {
      try {
        // 页面初始化即调用岗位接口，存储 id -> name，供列表岗位列回显
        try {
          const postRes = await postApi.getPostPage({ pageNo: 1, pageSize: -1 });
          const raw = (postRes as any)?.data ?? postRes;
          const postList: PostVO[] = Array.isArray(raw?.list) ? raw.list : Array.isArray(raw?.records) ? raw.records : Array.isArray(raw) ? raw : [];
          const map = new Map<number, string>();
          postList.forEach((item: any) => {
            const id = item.id != null ? Number(item.id) : NaN;
            const name = item.name != null ? String(item.name) : '';
            if (!Number.isNaN(id) && name) map.set(id, name);
          });
          setPostNameMap(map);
        } catch (postError) {
          console.error('获取岗位列表失败:', postError);
          setPostNameMap(new Map());
        }
        setDeptOptions([]);

        // 锁定站和设备/工艺接口已废弃，设置为空数组
        setLotoOptions([]);
        setMachineryOptions([]);

        // 获取点位分组数据（从字典 point_group，用于列表列回显）
        try {
          const pointGroupRes = await dictDataApi.getDictDataPage({ pageNo: 1, pageSize: -1, dictType: DICT_TYPE.POINT_GROUP });
          const pgData = (pointGroupRes as any)?.list ?? (pointGroupRes as any)?.data?.list ?? (Array.isArray(pointGroupRes) ? pointGroupRes : []);
          const pgList = Array.isArray(pgData) ? pgData : [];
          setDictOptions(DICT_TYPE.POINT_GROUP, pgList.map((item: any) => ({
            dictType: DICT_TYPE.POINT_GROUP,
            label: item.label,
            value: item.value,
            colorType: item.colorType || '',
            cssClass: item.cssClass || '',
          })));
        } catch (pgError) {
          console.error('获取点位分组字典失败:', pgError);
        }

        // 获取能量源数据（从字典 power_source）
        try {
          const powerRes = await dictDataApi.getDictDataPage({ pageNo: 1, pageSize: -1, dictType: DICT_TYPE.POWER_SOURCE });
          const powerData = (powerRes as any)?.list ?? (powerRes as any)?.data?.list ?? (Array.isArray(powerRes) ? powerRes : []);
          const powerList = Array.isArray(powerData) ? powerData : [];
          setDictOptions(DICT_TYPE.POWER_SOURCE, powerList.map((item: any) => ({
            dictType: DICT_TYPE.POWER_SOURCE,
            label: item.label,
            value: item.value,
            colorType: item.colorType || '',
            cssClass: item.cssClass || '',
          })));
          setPowerTypeOptions(getStrDictOptions(DICT_TYPE.POWER_SOURCE));
        } catch (powerError) {
          console.error('获取能量源字典失败:', powerError);
          setPowerTypeOptions([]);
        }
      } catch (error) {
        console.error('初始化数据失败:', error);
      }
    };
    initData();
  }, []);


  // 搜索
  const handleQuery = () => {
    setQueryParams({ ...queryParams, current: 1 });
    getList({ ...queryParams, current: 1 });
  };

  // 重置搜索
  const resetQuery = () => {
    const resetParams: PageParam = {
      current: 1,
      size: 10,
      pointName: undefined,
      workstationId: undefined,
      machineryId: undefined,
      lotoId: undefined,
      powerType: undefined,
    };
    setQueryParams(resetParams);
    getList(resetParams);
  };

  // 打开表单
  const openForm = (type: string, id?: number) => {
    formRef.current?.open(type, id);
  };

  // 删除隔离点
  const handleDelete = async (id?: number) => {
    // 如果传入了 id，使用传入的 id；否则使用选中的行
    const pointIds = id !== undefined && id !== null ? [id] : selectedRowKeys.map(key => Number(key));
    
    // 如果没有可删除的数据，提示用户
    if (!pointIds || pointIds.length === 0 || pointIds.every(id => !id || isNaN(id))) {
      toast.error(t('common.pleaseSelectData') || '请选择要删除的数据');
      return;
    }
    
    // 过滤掉无效的 ID
    const validPointIds = pointIds.filter(id => id !== undefined && id !== null && !isNaN(id));
    
    if (validPointIds.length === 0) {
      toast.error(t('common.pleaseSelectData') || '请选择要删除的数据');
      return;
    }
    
    Modal.confirm({
      title: t('common.confirmDelete'),
      icon: <ExclamationCircleOutlined />,
      content: `${t('common.confirmDeleteText')} ${validPointIds.length} ${t('common.records')}?`,
      okText: t('common.confirmDelete'),
      okType: 'danger',
      cancelText: t('common.cancel'),
      onOk: async () => {
        try {
          await segregationPointApi.deleteIsIsolationPointByPointIds(validPointIds);
          toast.success(t('common.deleteSuccess'));
          setSelectedRowKeys([]);
          await getList();
        } catch (error: any) {
          toast.error(error.message || t('common.deleteFailed'));
        }
      },
    });
  };

  // 表格列配置
  const columns: ColumnsType<SegregationPointVO> = useMemo(() => [
    {
      title: t('table.segregationPointId'),
      dataIndex: 'id',
      width: 100,
      align: 'center',
    },
    {
      title: t('table.segregationPointName'),
      dataIndex: 'pointName',
      align: 'center',
    },
    {
      title: t('table.icon'),
      dataIndex: 'pointIcon',
      width: 100,
      align: 'center',
      render: (text: string) => {
        if (text) {
          return <Image src={text} width={50} height={50} style={{ objectFit: 'cover' }} />;
        }
        return '-';
      },
    },
    {
      title: t('table.switchStatus'),
      dataIndex: 'switchStatus',
      width: 100,
      align: 'center',
      render: (status: number | string | null) => {
        if (status === null || status === undefined) {
          return '-';
        }
        const isChecked = String(status) === '1';
        return (
          <Switch
            checked={isChecked}
            checkedChildren="ON"
            unCheckedChildren="OFF"
            disabled
            style={{ pointerEvents: 'none' }}
          />
        );
      },
    },
    {
      title: t('table.segregationPointNfc'),
      dataIndex: 'pointNfc',
      align: 'center',
    },
    {
      title: t('table.position'),
      dataIndex: 'workstationId',
      align: 'center',
      render: (value: number | string | undefined) => {
        if (value == null || value === '') return '-';
        const id = Number(value);
        if (Number.isNaN(id)) return '-';
        return postNameMap.get(id) ?? '-';
      },
    },
    {
      title: t('form.pointGroup'),
      dataIndex: 'lotoId',
      width: 120,
      align: 'center',
      render: (value: number | null | undefined) => (value != null ? getDictLabel(DICT_TYPE.POINT_GROUP, value) : null) || '-',
    },
    {
      title: t('table.segregationPointSerial'),
      dataIndex: 'pointSerialNumber',
      width: 120,
      align: 'center',
    },
    {
      title: t('table.function'),
      dataIndex: 'remark',
      align: 'center',
    },
    {
      title: t('table.image'),
      dataIndex: 'pointPicture',
      width: 100,
      align: 'center',
      render: (text: string) => {
        if (text) {
          return <Image src={text} width={50} height={50} style={{ objectFit: 'cover' }} />;
        }
        return '-';
      },
    },
    {
      title: t('table.energySource'),
      dataIndex: 'powerType',
      align: 'center',
      render: (value: string) => {
        const option = powerTypeOptions.find(opt => opt.value === value);
        return option ? option.label : value || '-';
      },
    },
    {
      title: t('table.operation'),
      width: 150,
      align: 'center',
      fixed: 'right',
      render: (_: any, record: SegregationPointVO) => (
        <div className="flex items-center gap-2 justify-center">
          <PermissionWrapper permission="iscs:point:update">
            <UIButton
              variant="ghost"
              size="sm"
              onClick={() => {
                console.log('SegregationPointManagement: 点击编辑, record =', record);
                const editId = record.pointId || (record as any).id;
                console.log('SegregationPointManagement: 编辑ID =', editId);
                openForm('update', editId);
              }}
              className="h-8 px-2 transition-colors hover:underline"
              style={{ color: '#000000' }}
              onMouseEnter={(e) => {
                e.currentTarget.style.color = '#1677ff';
                e.currentTarget.style.textDecoration = 'underline';
                e.currentTarget.querySelector('svg')?.setAttribute('style', 'color: #1677ff');
              }}
              onMouseLeave={(e) => {
                e.currentTarget.style.color = '#000000';
                e.currentTarget.style.textDecoration = 'none';
                e.currentTarget.querySelector('svg')?.setAttribute('style', 'color: #000000');
              }}
            >
              <Edit2 className="w-4 h-4" style={{ color: '#000000' }} />
              <span className="ml-1">{t('common.edit')}</span>
            </UIButton>
          </PermissionWrapper>
          <PermissionWrapper permission="iscs:point:delete">
            <UIButton
              variant="ghost"
              size="sm"
              onClick={() => {
                // 使用和 rowKey 相同的逻辑获取 ID：优先使用 pointId，如果没有则使用 id
                const deleteId = record.pointId ?? record.id;
                if (deleteId !== undefined && deleteId !== null) {
                  handleDelete(deleteId);
                } else {
                  toast.error(t('common.deleteIdNotFound') || '无法获取删除ID');
                }
              }}
              className="h-8 px-2 transition-colors hover:underline"
              style={{ color: '#000000' }}
              onMouseEnter={(e) => {
                e.currentTarget.style.color = '#1677ff';
                e.currentTarget.style.textDecoration = 'underline';
                e.currentTarget.querySelector('svg')?.setAttribute('style', 'color: #1677ff');
              }}
              onMouseLeave={(e) => {
                e.currentTarget.style.color = '#000000';
                e.currentTarget.style.textDecoration = 'none';
                e.currentTarget.querySelector('svg')?.setAttribute('style', 'color: #000000');
              }}
            >
              <Trash2 className="w-4 h-4" style={{ color: '#000000' }} />
              <span className="ml-1">{t('common.delete')}</span>
            </UIButton>
          </PermissionWrapper>
        </div>
      ),
    },
  ], [t, i18n.language, powerTypeOptions, postNameMap]);

  return (
    <div className="p-6 space-y-4">
      {/* 搜索栏 */}
      <div className="bg-white rounded-xl border border-gray-200/50 shadow-sm p-5">
        <div className="flex flex-col gap-4">
          {/* 搜索字段 + 操作按钮 */}
          <div className="flex items-center justify-between gap-3 flex-wrap">
            {/* 搜索条件 + 搜索、重置紧跟其后 */}
            <div className="flex items-center gap-3 flex-wrap">
              <div className="flex items-center gap-2">
                <label className="text-sm font-medium text-gray-700 whitespace-nowrap">{t('form.segregationPointName')}：</label>
                <Input
                  value={queryParams.pointName}
                  onChange={(e) => setQueryParams({ ...queryParams, pointName: e.target.value })}
                  onPressEnter={handleQuery}
                  placeholder={t('form.segregationPointNamePlaceholder')}
                  className="w-[180px]"
                  allowClear
                />
              </div>
            {showAdvancedQueryFilters && (
              <>
                <div className="flex items-center gap-2">
                  <label className="text-sm font-medium text-gray-700 whitespace-nowrap">{t('form.workstation')}：</label>
                  <TreeSelect
                    value={queryParams.workstationId}
                    onChange={(value) => setQueryParams({ ...queryParams, workstationId: value })}
                    treeData={deptOptions}
                    placeholder={t('form.workstationPlaceholder')}
                    allowClear
                    className="w-[180px]"
                  />
                </div>
                <div className="flex items-center gap-2">
                  <label className="text-sm font-medium text-gray-700 whitespace-nowrap">{t('form.deviceProcess')}：</label>
                  <TreeSelect
                    value={queryParams.machineryId}
                    onChange={(value) => setQueryParams({ ...queryParams, machineryId: value })}
                    treeData={machineryOptions}
                    placeholder={t('form.deviceProcessPlaceholder')}
                    allowClear
                    className="w-[180px]"
                  />
                </div>
                <div className="flex items-center gap-2">
                  <label className="text-sm font-medium text-gray-700 whitespace-nowrap">{t('form.lotoStation')}：</label>
                  <Select
                    value={queryParams.lotoId}
                    onChange={(value) => setQueryParams({ ...queryParams, lotoId: value })}
                    placeholder={t('form.lotoStationPlaceholder')}
                    allowClear
                    className="w-[180px]"
                    options={lotoOptions}
                  />
                </div>
                <div className="flex items-center gap-2">
                  <label className="text-sm font-medium text-gray-700 whitespace-nowrap">{t('form.energySource')}：</label>
                  <Select
                    value={queryParams.powerType}
                    onChange={(value) => setQueryParams({ ...queryParams, powerType: value })}
                    placeholder={t('form.energySourcePlaceholder')}
                    allowClear
                    className="w-[180px]"
                    options={powerTypeOptions}
                  />
                </div>
              </>
            )}
            {/* 搜索、重置紧跟最后一个搜索条件 */}
            <Space className="flex-shrink-0" size="small">
              <PermissionWrapper permission="iscs:point:query">
                <Button
                  type="primary"
                  icon={<Search />}
                  onClick={handleQuery}
                >
                  {t('common.search')}
                </Button>
              </PermissionWrapper>
              <PermissionWrapper permission="iscs:point:query">
                <Button
                  icon={<RefreshCw />}
                  onClick={resetQuery}
                >
                  {t('common.reset')}
                </Button>
              </PermissionWrapper>
            </Space>
          </div>

          {/* 新增、批量删除等按钮保持在最右侧 */}
          <div className="flex justify-end">
            <Space size="small">
              <PermissionWrapper permission="iscs:point:create">
                <Button
                  type="primary"
                  icon={<Plus />}
                  onClick={() => openForm('create')}
                >
                  {t('common.addNew')}
                </Button>
              </PermissionWrapper>
              <PermissionWrapper permission="iscs:point:delete">
                <Button
                  danger
                  icon={<Trash2 className="w-4 h-4" />}
                  disabled={selectedRowKeys.length === 0}
                  onClick={() => handleDelete()}
                >
                  {t('common.batchDelete')}
                </Button>
              </PermissionWrapper>
            </Space>
          </div>
          </div>
        </div>
      </div>

      {/* 表格 */}
      <div className="bg-white rounded-lg border border-gray-200 isolation-work-list-table">
        <Table
          columns={columns}
          dataSource={list}
          rowKey={(record, index) => {
            // 优先使用 pointId，如果没有则使用 id，最后使用索引
            const key = record.pointId ?? record.id ?? `row-${index}`;
            return key;
          }}
          loading={loading}
          pagination={false}
          scroll={{ x: 'max-content' }}
          rowSelection={{
            selectedRowKeys,
            onChange: (keys) => {
              setSelectedRowKeys(keys);
            },
            onSelect: (record, selected) => {
              const recordKey = record.pointId ?? record.id;
              if (!recordKey) return;
              
              if (selected) {
                // 选中时，只添加当前行的 key
                setSelectedRowKeys(prev => {
                  if (prev.includes(recordKey)) {
                    return prev;
                  }
                  return [...prev, recordKey];
                });
              } else {
                // 取消选中时，只移除当前行的 key
                setSelectedRowKeys(prev => prev.filter(key => key !== recordKey));
              }
            },
            onSelectAll: (selected, selectedRows, changeRows) => {
              if (selected) {
                // 全选时，只选中当前页的数据
                const currentPageKeys = list
                  .map(item => item.pointId ?? item.id)
                  .filter((id): id is number => id !== undefined && id !== null)
                  .map(id => id as React.Key);
                setSelectedRowKeys(prev => {
                  const newKeys = new Set(prev);
                  currentPageKeys.forEach(key => newKeys.add(key));
                  return Array.from(newKeys);
                });
              } else {
                // 取消全选时，只取消当前页的选中
                const currentPageKeys = new Set(
                  list
                    .map(item => item.pointId ?? item.id)
                    .filter((id): id is number => id !== undefined && id !== null)
                    .map(id => id as React.Key)
                );
                setSelectedRowKeys(prev => prev.filter(key => !currentPageKeys.has(key)));
              }
            },
            getCheckboxProps: (record) => ({
              name: record.pointName,
            }),
          }}
          rowClassName={(_, index) =>
            index !== undefined && index % 2 === 1 ? 'isolation-work-list-row-alt' : ''
          }
        />
      </div>

      {/* 分页 */}
      {!loading && list.length > 0 && (
        <div className="bg-white rounded-lg border border-gray-200 px-6 py-4">
          <div className="flex items-center justify-between">
            <div className="text-sm text-gray-600">
              {t('common.total')} <span className="text-blue-600 font-medium">{total}</span> {t('common.records')}
            </div>
            <div className="flex gap-2">
              <Button
                onClick={() => setQueryParams({ ...queryParams, current: (queryParams.current || 1) - 1 })}
                disabled={(queryParams.current || 1) <= 1}
              >
                {t('common.prevPage')}
              </Button>
              <span className="px-4 py-2 text-sm text-gray-600 flex items-center">
                {queryParams.current || 1} / {Math.ceil(total / (queryParams.size || 10)) || 1}
              </span>
              <Button
                onClick={() => setQueryParams({ ...queryParams, current: (queryParams.current || 1) + 1 })}
                disabled={(queryParams.current || 1) >= Math.ceil(total / (queryParams.size || 10))}
              >
                {t('common.nextPage')}
              </Button>
            </div>
          </div>
        </div>
      )}

      {/* 表单弹窗 */}
      <SegregationPointForm ref={formRef} onSuccess={getList} />
    </div>
  );
}

