import React, { useState, useEffect } from 'react';
import { history } from 'umi';
import {
  Button,
  Table,
  Space,
  message,
  Input,
  Select,
  Form,
  Tooltip,
  Tag,
  Modal,
} from 'antd';
import type { TablePaginationConfig } from 'antd';
import {
  PlusOutlined,
  DeleteOutlined,
  SearchOutlined,
} from '@ant-design/icons';
import CategorySelector from '@/components/CategorySelector/CategorySelector';
import { getAnnualTemplateList, enableAnnualTemplate, disableAnnualTemplate } from '@/servers/api/supplierAnnual';
import { AnnualTemplateStatus, AnnualTemplateStatusText, AnnualTemplateStatusColor } from '@/dicts/supplierAnnualDict';

const { Option } = Select;

// 搜索参数类型
interface AnnualTemplateSearchParams {
  templateName?: string;
  tenantName?: string;
  categoryId?: string;
  dateRange?: string[];
  [key: string]: any;
}

const SupplierAnnualTemplateManage: React.FC = () => {
  const [loading, setLoading] = useState<boolean>(false);
  const [form] = Form.useForm();

  const [templateData, setTemplateData] = useState<supplierAnnualTemplateManage.TemplateRecord[]>([]);
  const [pagination, setPagination] = useState<TablePaginationConfig>({
    current: 1,
    pageSize: 10,
    total: 0,
    showSizeChanger: true,
    showQuickJumper: true,
    showTotal: (total) => `共 ${total} 条记录`,
  });
  const [searchParams, setSearchParams] = useState<AnnualTemplateSearchParams>({});

  // 部门下拉选项
  const [companyOptions, setCompanyOptions] = useState<{ label: string, value: string }[]>([
    { label: '中山市合创展包装材料有限公司', value: '中山市合创展包装材料有限公司' },
    { label: '广州市科技发展有限公司', value: '广州市科技发展有限公司' },
    { label: '深圳市创新科技有限公司', value: '深圳市创新科技有限公司' },
    { label: '东莞市制造业有限公司', value: '东莞市制造业有限公司' },
  ]);

  // 获取模板列表
  const fetchTemplateList = async (
    current = 1,
    pageSize = 10,
    params: AnnualTemplateSearchParams = searchParams,
  ) => {
    // 更新搜索参数状态
    if (params !== searchParams) {
      setSearchParams(params);
    }

    setLoading(true);
    try {
      // 构建请求参数
      const requestParams: supplierAnnualTemplateManage.TemplateRequest = {
        basePageRequest: {
          pageNo: current,
          pageSize: pageSize,
        },
      };

      // 添加搜索条件
      if (params.templateName) {
        requestParams.templateName = params.templateName;
      }
      if (params.tenantName) {
        requestParams.tenantName = params.tenantName;
      }
      if (params.categoryId) {
        requestParams.categoryId = params.categoryId;
      }

      const response = await getAnnualTemplateList(requestParams);

      if (response.success && response.data) {
        const { records, total, current: currentPage, size } = response.data;
        setTemplateData(records);
        setPagination({
          ...pagination,
          current: currentPage,
          pageSize: size,
          total,
        });
      } else {
        message.error(response.message || '获取模板列表失败');
      }
    } catch (error) {
      console.error('获取模板列表失败:', error);
      message.error('获取模板列表失败');
    } finally {
      setLoading(false);
    }
  };

  // 首次加载获取数据
  useEffect(() => {
    fetchTemplateList(pagination.current, pagination.pageSize, {});
  }, []);

  // 处理查看
  const handleView = (record: supplierAnnualTemplateManage.TemplateRecord) => {
    history.push({
      pathname: 'supplierAnnualTemplateManageDetail',
      state: {
        id: record.id,
      }
    });
  };

  // 处理启用模板
  const handleEnableTemplate = (id: string) => {
    Modal.confirm({
      title: '确认启用',
      content: '确定要启用此模板吗？',
      okText: '确定',
      cancelText: '取消',
      onOk: async () => {
        try {
          setLoading(true);
          const res = await enableAnnualTemplate(id);
          if (res.success) {
            message.success('模板启用成功');
            fetchTemplateList(pagination.current, pagination.pageSize, searchParams);
          } else {
            message.error(res.message || '启用模板失败');
          }
        } catch (error) {
          console.error('启用模板失败:', error);
          message.error('启用模板失败');
        } finally {
          setLoading(false);
        }
      }
    });
  };

  // 处理禁用模板
  const handleDisableTemplate = (id: string) => {
    Modal.confirm({
      title: '确认禁用',
      content: '确定要禁用此模板吗？',
      okText: '确定',
      cancelText: '取消',
      onOk: async () => {
        try {
          setLoading(true);
          const res = await disableAnnualTemplate(id);
          if (res.success) {
            message.success('模板禁用成功');
            fetchTemplateList(pagination.current, pagination.pageSize, searchParams);
          } else {
            message.error(res.message || '禁用模板失败');
          }
        } catch (error) {
          console.error('禁用模板失败:', error);
          message.error('禁用模板失败');
        } finally {
          setLoading(false);
        }
      }
    });
  };

  // 处理编辑
  const handleEdit = (record: supplierAnnualTemplateManage.TemplateRecord) => {
    history.push({
      pathname: 'supplierAnnualTemplateManageAdd',
      state: {
        isEdit: true,
        editData: record
      }
    });
  };

  // 获取状态标签
  const getStatusTag = (status: string | undefined) => {
    if (!status) return <Tag>未知状态</Tag>;
    const color = AnnualTemplateStatusColor[status as keyof typeof AnnualTemplateStatusColor] || 'default';
    const text = AnnualTemplateStatusText[status as keyof typeof AnnualTemplateStatusText] || '未知状态';
    return <Tag color={color}>{text}</Tag>;
  };

  // 处理表格分页变化
  const handleTableChange = (newPagination: TablePaginationConfig) => {
    fetchTemplateList(newPagination.current, newPagination.pageSize, searchParams);
  };

  const columns = [
    {
      title: '序号',
      render: (_: any, __: supplierAnnualTemplateManage.TemplateRecord, index: number) =>
        (pagination.current! - 1) * pagination.pageSize! + index + 1,
      width: 80,
    },
    {
      title: '模板名称',
      dataIndex: 'templateName',
      key: 'templateName',
      width: 200,
      ellipsis: {
        showTitle: false,
      },
      render: (templateName: string) => (
        <Tooltip placement="topLeft" title={templateName}>
          {templateName}
        </Tooltip>
      ),
    },
    {
      title: '品类',
      dataIndex: 'categoryName',
      key: 'categoryName',
      width: 120,
    },
    {
      title: '创建单位',
      dataIndex: 'tenantName',
      key: 'tenantName',
      width: 180,
      ellipsis: {
        showTitle: false,
      },
      render: (text: string) => (
        <Tooltip placement="topLeft" title={text}>
          {text}
        </Tooltip>
      ),
    },
    {
      title: '创建部门',
      dataIndex: 'deptName',
      key: 'deptName',
      width: 120,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width: 150,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status: string) => getStatusTag(status),
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      align: 'center' as const,
      render: (_: unknown, record: supplierAnnualTemplateManage.TemplateRecord) => (
        <Space size="middle">
          {/* 草稿状态可以编辑，其他状态不可编辑 */}
          {record.status === AnnualTemplateStatus.DRAFT && (
            <Button type="link" onClick={() => handleEdit(record)} size="small">
              编辑
            </Button>
          )}

          {/* 所有状态都可以查看 */}
          <Button type="link" onClick={() => handleView(record)} size="small">
            查看
          </Button>

          {/* 草稿状态显示启用按钮 */}
          {record.status === AnnualTemplateStatus.DRAFT && (
            <Button type="link" onClick={() => handleEnableTemplate(record.id)} size="small">
              启用
            </Button>
          )}

          {/* 草稿状态显示禁用按钮 */}
          {record.status === AnnualTemplateStatus.DRAFT && (
            <Button type="link" danger onClick={() => handleDisableTemplate(record.id)} size="small">
              禁用
            </Button>
          )}

          {/* 禁用状态显示启用按钮 */}
          {record.status === AnnualTemplateStatus.DISABLED && (
            <Button type="link" onClick={() => handleEnableTemplate(record.id)} size="small">
              启用
            </Button>
          )}

          {/* 启用状态显示禁用按钮 */}
          {record.status === AnnualTemplateStatus.ENABLED && (
            <Button type="link" danger onClick={() => handleDisableTemplate(record.id)} size="small">
              禁用
            </Button>
          )}
        </Space>
      ),
    },
  ];

  // 处理添加
  const handleAdd = () => {
    // message.info('新增功能尚未开发');
    // 将来实现新增功能时使用：
    history.push('supplierAnnualTemplateManageAdd');
  };

  // 处理搜索
  const handleSearch = (values: any) => {
    const { dateRange, ...rest } = values;
    const params: AnnualTemplateSearchParams = { ...rest };

    if (dateRange && dateRange.length === 2) {
      params.dateRange = [dateRange[0].format('YYYY-MM-DD'), dateRange[1].format('YYYY-MM-DD')];
    }

    fetchTemplateList(1, pagination.pageSize, params);
  };

  // 重置搜索表单
  const handleReset = () => {
    form.resetFields();
    fetchTemplateList(1, pagination.pageSize, {});
  };

  return (
    <div className="common-container">
      <div className="filter-action-row">
        <Form
          form={form}
          name="search"
          onFinish={handleSearch}
          layout="inline"
          className="filter-form"
        >
          <Form.Item name="templateName" label="模板名称">
            <Input placeholder="请输入模板名称" allowClear />
          </Form.Item>
          <Form.Item name="tenantName" label="创建单位">
            <Select placeholder="请选择创建单位" allowClear style={{ width: 200 }}>
              {companyOptions.map(option => (
                <Option key={option.value} value={option.value}>{option.label}</Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item name="categoryId" label="品类">
            <CategorySelector multiple={false} style={{ width: 200 }} />
          </Form.Item>
          <Form.Item className="filter-btns">
            <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
              搜索
            </Button>
            <Button
              type="primary"
              danger
              icon={<DeleteOutlined />}
              onClick={handleReset}
            >
              重置
            </Button>
          </Form.Item>
        </Form>
        <div className="right-buttons">
          <Button type="primary" ghost icon={<PlusOutlined />} onClick={handleAdd}>
            新增
          </Button>
        </div>
      </div>

      <div className="content-area">
        <Table
          columns={columns}
          rowKey="id"
          dataSource={templateData}
          pagination={pagination}
          loading={loading}
          onChange={handleTableChange}
          scroll={{ x: 1200 }}
        />
      </div>
    </div>
  );
};

export default SupplierAnnualTemplateManage;
