import React, { useState, useEffect, useRef } from 'react';
import { Search, Plus, RefreshCw, Edit2, Trash2, Download } from 'lucide-react';
import { postApi, PostVO, PostStatus, PageParam } from '../api/Post';
import { toast } from 'sonner';
import { formatDateTimeFull } from '../utils/formatTime';
import { DICT_TYPE, getDictLabel, getDictOptions, setDictOptions, DictDataType } from '../utils/dict';
import { dictDataApi } from '../api/DictData';
import { Modal, Button, Input, Space, Tooltip, Switch as AntdSwitch } from 'antd';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import { Button as UIButton } from './ui/button';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from './ui/table';
import PostForm, { PostFormRef } from './PostForm';
import PermissionWrapper from './PermissionWrapper';
import { useTranslation } from 'react-i18next';
import './IsolationWorkListTable.css';

export default function PostManagement() {
  const { t } = useTranslation();
  const [loading, setLoading] = useState(true);
  const [list, setList] = useState<PostVO[]>([]);
  const [total, setTotal] = useState(0);
  const [queryParams, setQueryParams] = useState<PageParam>({
    pageNo: 1,
    pageSize: 10,
    name: undefined,
    code: undefined,
    userId: undefined, // 添加用户ID参数
  });
  const [exportLoading, setExportLoading] = useState(false);
  const [postStatusUpdating, setPostStatusUpdating] = useState<Record<number, boolean>>({});
  const formRef = useRef<PostFormRef>(null);

  // 从 sessionStorage 读取用户ID（如果存在）
  useEffect(() => {
    const userId = sessionStorage.getItem('selectedUserId');
    if (userId) {
      setQueryParams(prev => ({ ...prev, userId: Number(userId) }));
      // 读取后清除，避免下次进入时还使用旧的用户ID
      sessionStorage.removeItem('selectedUserId');
    }
  }, []);

  // 获取岗位列表
  const getList = async (params?: PageParam) => {
    const currentParams = params || queryParams;
    setLoading(true);
    try {
      console.log('PostManagement: 开始获取岗位列表', currentParams);
      const response = await postApi.getPostPage(currentParams);
      console.log('PostManagement: API 响应', response);
      
      // 处理响应数据
      let data;
      if (response && typeof response === 'object') {
        // 如果响应有 data 属性，使用 data；否则直接使用 response
        data = (response as any).data !== undefined ? (response as any).data : response;
      } else {
        data = response;
      }
      
      // 确保 data 是对象
      if (!data || typeof data !== 'object') {
        console.warn('PostManagement: 响应数据格式异常', data);
        setList([]);
        setTotal(0);
        return;
      }
      
      setList(data.list || []);
      setTotal(data.total || 0);
      console.log('PostManagement: 设置列表数据', data.list, '总数', data.total);
    } catch (error: any) {
      console.error('PostManagement: 获取岗位列表失败', error);
      // 即使请求失败，也设置空列表，避免一直显示加载中
      setList([]);
      setTotal(0);
      
      // 显示错误信息
      const errorMessage = error?.response?.data?.message || 
                          error?.message || 
                          '获取岗位列表失败，请检查网络连接或联系管理员';
      toast.error(errorMessage);
    } finally {
      setLoading(false);
    }
  };

  // 加载 COMMON_STATUS 字典数据
  const loadCommonStatusDict = async () => {
    try {
      const response = await dictDataApi.getDictDataPage({
        pageNo: 1,
        pageSize: -1,
        dictType: DICT_TYPE.COMMON_STATUS,
      });
      const data = (response as any)?.data || response;
      const dictList = data?.list || [];
      if (Array.isArray(dictList) && dictList.length > 0) {
        const dictOptions: DictDataType[] = dictList.map((item: any) => ({
          dictType: item.dictType,
          label: item.label,
          value: item.value,
          colorType: item.colorType || '',
          cssClass: item.cssClass || '',
        }));
        setDictOptions(DICT_TYPE.COMMON_STATUS, dictOptions);
        console.log('PostManagement: 获取通用状态字典成功', dictOptions);
      }
    } catch (error) {
      console.error('加载通用状态字典数据失败:', error);
    }
  };

  // 组件挂载时加载字典数据
  useEffect(() => {
    loadCommonStatusDict();
  }, []);

  // 组件挂载和分页参数变化时获取数据
  useEffect(() => {
    console.log('PostManagement: useEffect 触发，queryParams =', queryParams);
    getList();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [queryParams.pageNo, queryParams.pageSize]);

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

  // 重置搜索
  const resetQuery = () => {
    const resetParams: PageParam = {
      pageNo: 1,
      pageSize: 10,
      name: undefined,
      code: undefined,
      userId: queryParams.userId, // 保留userId，避免重置时丢失
    };
    // 先设置状态，确保搜索框能同步更新
    setQueryParams(resetParams);
    // 使用重置后的参数立即获取列表
    getList(resetParams);
  };

  // 打开表单
  const openForm = (type: string, id?: number) => {
    console.log('PostManagement: 打开表单', type, id, 'formRef.current =', formRef.current);
    if (formRef.current) {
      formRef.current.open(type, id);
    } else {
      console.error('PostManagement: formRef.current 为 null');
      toast.error('表单组件未初始化，请刷新页面重试');
    }
  };

  // 删除岗位
  const handleDelete = async (id: number, name: string) => {
    Modal.confirm({
      title: t('common.confirmDelete'),
      icon: <ExclamationCircleOutlined />,
      content: (
        <div>
          <p>{t('common.confirmDeleteText')} <strong>"{name}"</strong>?</p>
          <p style={{ color: '#ff4d4f', marginTop: '8px' }}>{t('common.confirmDeleteWarning')}</p>
        </div>
      ),
      okText: t('common.confirmDelete'),
      okType: 'danger',
      cancelText: t('common.cancel'),
      onOk: async () => {
        try {
          await postApi.deletePost(id);
          toast.success(t('common.deleteSuccess'));
          await getList();
        } catch (error: any) {
          toast.error(error.message || t('common.deleteFailed'));
        }
      },
    });
  };

  // 导出岗位
  const handleExport = async () => {
    Modal.confirm({
      title: t('common.exportPostConfirm'),
      icon: <ExclamationCircleOutlined />,
      content: t('common.exportPostConfirmText'),
      okText: t('common.exportPostConfirmButton'),
      cancelText: t('common.cancel'),
      onOk: async () => {
        setExportLoading(true);
        try {
          const response = await postApi.exportPost(queryParams);
          const blob = (response as any)?.data || response;
          const url = window.URL.createObjectURL(blob);
          const link = document.createElement('a');
          link.href = url;
          link.download = t('common.postDataFileName');
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
          window.URL.revokeObjectURL(url);
          toast.success(t('common.exportPostSuccess'));
        } catch (error: any) {
          toast.error(error.message || t('common.exportPostFailed'));
        } finally {
          setExportLoading(false);
        }
      },
    });
  };


  // 处理状态变更
  const handleStatusChanged = async (post: PostVO, newStatus: number) => {
    if (!post.id) {
      toast.error(t('common.error'));
      return;
    }

    setPostStatusUpdating(prev => ({ ...prev, [post.id!]: true }));

    try {
      const updatedPost: PostVO = {
        id: post.id,
        name: post.name,
        code: post.code,
        sort: post.sort ?? 0,
        remark: post.remark || '',
        status: newStatus,
      };
      await postApi.updatePost(updatedPost);
      toast.success(t('common.updateSuccess'));
      await getList();
    } catch (error: any) {
      toast.error(error.message || t('common.updateFailed'));
    } finally {
      setPostStatusUpdating(prev => {
        const newState = { ...prev };
        delete newState[post.id!];
        return newState;
      });
    }
  };

  return (
    <>
      <style>{`
        .ant-switch-checked-green.ant-switch-checked {
          background-color: #52c41a !important;
        }
      `}</style>
      <div className="space-y-4">
        {/* 搜索栏 */}
      <div className="bg-white rounded-xl border border-gray-200/50 shadow-sm p-4 lg:p-5">
        <div className="flex items-center justify-between gap-3 lg:gap-4 flex-wrap min-w-0">
          {/* 搜索条件 + 搜索、重置紧跟其后 */}
          <div className="flex items-center gap-2 lg:gap-3 flex-wrap min-w-0">
            <div className="flex items-center gap-2 lg:gap-3 w-[200px] min-w-[100px] flex-shrink">
              <label className="text-sm font-medium text-gray-700 whitespace-nowrap flex-shrink-0">{t('form.postName')}：</label>
              <Input
                value={queryParams.name || ''}
                onChange={(e) => setQueryParams(prev => ({ ...prev, name: e.target.value }))}
                onPressEnter={handleQuery}
                placeholder={t('form.postNamePlaceholder')}
                className="min-w-0 w-full"
                allowClear
              />
            </div>
            <div className="flex items-center gap-2 lg:gap-3 w-[200px] min-w-[100px] flex-shrink">
              <label className="text-sm font-medium text-gray-700 whitespace-nowrap flex-shrink-0">{t('form.postCode')}：</label>
              <Input
                value={queryParams.code || ''}
                onChange={(e) => setQueryParams(prev => ({ ...prev, code: e.target.value }))}
                onPressEnter={handleQuery}
                placeholder={t('form.postCodePlaceholder')}
                className="min-w-0 w-full"
                allowClear
              />
            </div>
            <Space className="flex-shrink-0" size="small">
              <PermissionWrapper permission="system:post:query">
                <Button
                  type="primary"
                  icon={<Search className="w-4 h-4" />}
                  onClick={handleQuery}
                >
                  {t('common.search')}
                </Button>
              </PermissionWrapper>
              
              <PermissionWrapper permission="system:post:query">
                <Button
                  icon={<RefreshCw className="w-4 h-4" />}
                  onClick={resetQuery}
                >
                  {t('common.reset')}
                </Button>
              </PermissionWrapper>
            </Space>
          </div>

          {/* 新增、导出等按钮组保持在最右侧 */}
          <Space className="flex-shrink-0" size="small">
            <PermissionWrapper permission="system:post:create">
              <Button
                type="primary"
                icon={<Plus className="w-4 h-4" />}
                onClick={() => openForm('create')}
              >
                {t('common.addNew')}
              </Button>
            </PermissionWrapper>
            
            <PermissionWrapper permission="system:post:export">
              <Button
                icon={<Download className="w-4 h-4" />}
                onClick={handleExport}
                loading={exportLoading}
              >
                {t('common.export')}
              </Button>
            </PermissionWrapper>
          </Space>
        </div>
      </div>

      {/* 表格 */}
      <div className="bg-white rounded-lg border border-gray-200 overflow-hidden">
        <div className="system-mgmt-shadcn-table">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead className="w-[80px] text-center">{t('table.postId')}</TableHead>
              <TableHead className="w-[150px]">{t('table.postName')}</TableHead>
              <TableHead className="w-[150px]">{t('table.postCode')}</TableHead>
              <TableHead className="w-[100px] text-center">{t('table.postSort')}</TableHead>
              <TableHead>{t('table.postRemark')}</TableHead>
              <TableHead className="w-[100px] text-center">{t('table.status')}</TableHead>
              <TableHead className="w-[180px] text-center">{t('table.createTime')}</TableHead>
              <TableHead className="w-[160px] text-center">{t('table.operation')}</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {loading ? (
              <TableRow>
                <TableCell colSpan={8} className="text-center py-8 text-gray-500">
                  {t('common.loading')}
                </TableCell>
              </TableRow>
            ) : list.length === 0 ? (
              <TableRow>
                <TableCell colSpan={8} className="text-center py-8 text-gray-500">
                  {t('common.noData')}
                </TableCell>
              </TableRow>
            ) : (
              list.map((row, index) => (
                <TableRow
                  key={row.id}
                  className={index % 2 === 1 ? 'system-mgmt-row-alt hover:bg-gray-50' : 'hover:bg-gray-50'}
                >
                  <TableCell className="text-center">{row.id}</TableCell>
                  <TableCell className="font-medium">{row.name}</TableCell>
                  <TableCell>{row.code}</TableCell>
                  <TableCell className="text-center">{row.sort}</TableCell>
                  <TableCell className="text-sm text-gray-600">
                    {(() => {
                      const text = row.remark || '-';
                      const maxLength = 20;
                      const shouldTruncate = text.length > maxLength;
                      const displayText = shouldTruncate ? text.slice(0, maxLength) + '...' : text;
                      
                      return (
                        <Tooltip placement="topLeft" title={text}>
                          <span>{displayText}</span>
                        </Tooltip>
                      );
                    })()}
                  </TableCell>
                  <TableCell className="text-center">
                    {(() => {
                      const status = Number(row.status);
                      // 使用字典值显示状态
                      const statusLabel = getDictLabel(DICT_TYPE.COMMON_STATUS, status) || '-';
                      // 根据字典的 label 来判断颜色：开启/启用显示绿色，禁用/关闭显示灰色
                      const isEnabled = statusLabel === '开启' || statusLabel === '启用' || statusLabel === '正常';
                      const statusStyle = isEnabled 
                        ? 'bg-green-100 text-green-700' 
                        : 'bg-gray-100 text-gray-700';
                      return (
                        <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${statusStyle}`}>
                          {statusLabel}
                        </span>
                      );
                    })()}
                  </TableCell>
                  <TableCell className="text-center text-sm text-gray-600">
                    {formatDateTimeFull(row.createTime)}
                  </TableCell>
                  <TableCell>
                    <div className="flex items-center gap-2 justify-center">
                      <PermissionWrapper permission="system:post:update">
                        <UIButton
                          variant="ghost"
                          size="sm"
                          onClick={() => openForm('update', row.id)}
                          className="h-8 px-2 transition-colors hover:underline"
                          style={{ color: '#000000' }}
                          onMouseEnter={(e) => {
                            e.currentTarget.style.color = '#1677ff';
                            e.currentTarget.querySelector('svg')?.setAttribute('style', 'color: #1677ff');
                          }}
                          onMouseLeave={(e) => {
                            e.currentTarget.style.color = '#000000';
                            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="system:post:delete">
                        <UIButton
                          variant="ghost"
                          size="sm"
                          onClick={() => handleDelete(row.id!, row.name)}
                          className="h-8 px-2 transition-colors hover:underline"
                          style={{ color: '#000000' }}
                          onMouseEnter={(e) => {
                            e.currentTarget.style.color = '#1677ff';
                            e.currentTarget.querySelector('svg')?.setAttribute('style', 'color: #1677ff');
                          }}
                          onMouseLeave={(e) => {
                            e.currentTarget.style.color = '#000000';
                            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>
                  </TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
        </div>
      </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, pageNo: queryParams.pageNo! - 1 })}
                disabled={queryParams.pageNo! <= 1}
              >
                {t('common.prevPage')}
              </Button>
              <span className="px-4 py-2 text-sm text-gray-600 flex items-center">
                {queryParams.pageNo} / {Math.ceil(total / queryParams.pageSize!) || 1}
              </span>
              <Button
                onClick={() => setQueryParams({ ...queryParams, pageNo: queryParams.pageNo! + 1 })}
                disabled={queryParams.pageNo! >= Math.ceil(total / queryParams.pageSize!)}
              >
                {t('common.nextPage')}
              </Button>
            </div>
          </div>
        </div>
      )}

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

