import React, { useState, useEffect } from 'react';
import { history, useIntl } from 'umi';
import {
  Button,
  Table,
  Space,
  message,
  Input,
  Select,
  Form,
  Tooltip,
  Tag,
} from 'antd';
import type { TablePaginationConfig } from 'antd';
import {
  PlusOutlined,
  DeleteOutlined,
  SearchOutlined,
} from '@ant-design/icons';
import {
  TemplateStatusText,
  TemplateStatusColor,
  TemplateStatus,
} from '@/dicts/supplierTemplateDict';
import {
  getTemplateList,
} from '@/servers/api/supplierEvaluate';
import CategorySelector from '@/components/CategorySelector/CategorySelector';

const { Option } = Select;

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

  const [templateData, setTemplateData] = useState<SupplierTemplateManage.TemplateItem[]>([]);
  const [pagination, setPagination] = useState<TablePaginationConfig>({
    current: 1,
    pageSize: 10,
    total: 0,
    showSizeChanger: true,
    showQuickJumper: true,
    showTotal: (total) => intl.formatMessage(
      { id: 'supplierTemplateManage.pagination.total' },
      { total }
    ),
  });
  const [searchParams, setSearchParams] = useState({});

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

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

    setLoading(true);
    try {
      const requestParams: SupplierTemplateManage.TemplateRequest = {
        basePageRequest: {
          pageNo: current,
          pageSize: pageSize,
        },
        ...params,
      };

      const res = await getTemplateList(requestParams);

      if (res.success && res.data) {
        // 处理返回的数据
        const records = res.data.records

        setTemplateData(records);
        setPagination({
          ...pagination,
          current: res.data.current,
          pageSize: res.data.size,
          total: res.data.total,
        });
      } else {
        message.error(intl.formatMessage({ id: 'supplierTemplateManage.message.fetchFailed' }) || res.message);
      }
    } catch (error) {
      console.error('获取模板列表失败:', error);
      message.error(intl.formatMessage({ id: 'supplierTemplateManage.message.fetchFailed' }));
    } finally {
      setLoading(false);
    }
  };

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

  // 处理查看
  const handleView = (record: SupplierTemplateManage.TemplateItem) => {
    // 跳转到详情页面
    history.push({
      pathname: 'supplierTemplateManageDetail',
      state: {
        id: record.id,
      }
    });
  };

  // 处理编辑
  const handleEdit = (record: SupplierTemplateManage.TemplateItem) => {
    // 跳转到新增页面并传递编辑数据
    history.push({
      pathname: 'supplierTemplateManageAdd',
      state: {
        isEdit: true,
        editData: record
      }
    });
  };

  // 获取状态标签
  const getStatusTag = (status: string | undefined) => {
    if (!status) return <Tag>{intl.formatMessage({ id: 'supplierTemplateManage.status.unknown' })}</Tag>;
    const color = TemplateStatusColor[status as keyof typeof TemplateStatusColor] || 'default';
    const text = TemplateStatusText[status as keyof typeof TemplateStatusText] || intl.formatMessage({ id: 'supplierTemplateManage.status.unknown' });
    return <Tag color={color}>{text}</Tag>;
  };

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

  const columns = [
    {
      title: intl.formatMessage({ id: 'supplierTemplateManage.column.index' }),
      render: (_: any, __: SupplierTemplateManage.TemplateItem, index: number) =>
        (pagination.current! - 1) * pagination.pageSize! + index + 1,
      width: 80,
    },
    {
      title: intl.formatMessage({ id: 'supplierTemplateManage.column.templateName' }),
      dataIndex: 'templateName',
      key: 'templateName',
      width: 200,
      ellipsis: {
        showTitle: false,
      },
      render: (templateName: string) => (
        <Tooltip placement="topLeft" title={templateName}>
          {templateName}
        </Tooltip>
      ),
    },
    {
      title: intl.formatMessage({ id: 'supplierTemplateManage.column.category' }),
      dataIndex: 'categoryName',
      key: 'categoryName',
      width: 120,
    },
    {
      title: intl.formatMessage({ id: 'supplierTemplateManage.column.tenantName' }),
      dataIndex: 'tenantName',
      key: 'tenantName',
      width: 180,
      ellipsis: {
        showTitle: false,
      },
      render: (text: string) => (
        <Tooltip placement="topLeft" title={text}>
          {text}
        </Tooltip>
      ),
    },
    {
      title: intl.formatMessage({ id: 'supplierTemplateManage.column.deptName' }),
      dataIndex: 'deptName',
      key: 'deptName',
      width: 120,
    },
    {
      title: intl.formatMessage({ id: 'supplierTemplateManage.column.createTime' }),
      dataIndex: 'createTime',
      key: 'createTime',
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'supplierTemplateManage.column.status' }),
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status: string) => getStatusTag(status),
    },
    {
      title: intl.formatMessage({ id: 'supplierTemplateManage.column.action' }),
      key: 'action',
      width: 150,
      align: 'center' as const,
      render: (_: unknown, record: SupplierTemplateManage.TemplateItem) => (
        <Space size="middle">
          <Button type="link" onClick={() => handleEdit(record)}>
            {intl.formatMessage({ id: 'supplierTemplateManage.button.edit' })}
          </Button>
          <Button type="link" onClick={() => handleView(record)}>
            {intl.formatMessage({ id: 'supplierTemplateManage.button.view' })}
          </Button>
        </Space>
      ),
    },
  ];

  // 处理添加
  const handleAdd = () => {
    // 跳转到新增页面
    history.push('supplierTemplateManageAdd');
  };

  // 处理搜索
  const handleSearch = (values: any) => {
    const { dateRange, ...rest } = values;
    const params = { ...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);
  };

  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={intl.formatMessage({ id: 'supplierTemplateManage.column.templateName' })}>
            <Input placeholder={intl.formatMessage({ id: 'supplierTemplateManage.placeholder.templateName' })} allowClear />
          </Form.Item>
          <Form.Item name="tenantName" label={intl.formatMessage({ id: 'supplierTemplateManage.column.tenantName' })}>
            <Select placeholder={intl.formatMessage({ id: 'supplierTemplateManage.placeholder.tenantName' })} 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={intl.formatMessage({ id: 'supplierTemplateManage.column.category' })}>
            <CategorySelector multiple={false} style={{ width: 200 }} />
          </Form.Item>
          <Form.Item className="filter-btns">
            <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
              {intl.formatMessage({ id: 'supplierTemplateManage.button.search' })}
            </Button>
            <Button
              type="primary"
              danger
              icon={<DeleteOutlined />}
              onClick={() => {
                form.resetFields();
                fetchTemplateList(1, pagination.pageSize, {});
              }}
            >
              {intl.formatMessage({ id: 'supplierTemplateManage.button.reset' })}
            </Button>
          </Form.Item>
        </Form>
        <div className="right-buttons">
          <Button type="primary" ghost icon={<PlusOutlined />} onClick={handleAdd}>
            {intl.formatMessage({ id: 'supplierTemplateManage.button.add' })}
          </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 SupplierTemplateManage;
